XPMaster commited on
Commit
fde69ff
1 Parent(s): a3fa541

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -8
app.py CHANGED
@@ -1,12 +1,87 @@
1
- import pandas as pd
2
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- # Generate some test data
5
- test_index = pd.date_range(start='2023-01-01', periods=6, freq='M')
6
- test_data = pd.Series([100, 120, 130, 125, 140, 150], index=test_index)
7
 
8
- # Create a DataFrame
9
- test_df = pd.DataFrame(test_data, columns=['Test Forecast'])
 
 
 
 
 
 
 
 
10
 
11
- # Plot the test data
12
- st.line_chart(test_df)
 
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ from statsmodels.tsa.holtwinters import ExponentialSmoothing
4
+ import numpy as np
5
+ from itertools import product
6
+ from io import BytesIO
7
+
8
+ # Function to run the Exponential Smoothing Model
9
+ def run_exp_smoothing(city_data, trend, damped_trend, seasonal, seasonal_period):
10
+ try:
11
+ model = ExponentialSmoothing(city_data, trend=trend, damped_trend=damped_trend, seasonal=seasonal, seasonal_periods=seasonal_period)
12
+ model_fit = model.fit(optimized=True)
13
+ return model_fit.forecast(steps=6), model_fit.aic
14
+ except Exception as e:
15
+ return None, None
16
+
17
+ def create_data():
18
+ data = pd.read_csv('accident_count.csv', parse_dates=True, index_col=0)
19
+ data.index = pd.to_datetime(data.index, format='%Y%m')
20
+ data = data.groupby('City').resample('M').sum().reset_index()
21
+ #data = data[data['City'] == 'ARAR']
22
+ data.index = data['Accident Month Bracket']
23
+ data = data.drop(['Accident Month Bracket'],axis=1)
24
+ data.index = data.index.strftime('%Y-%m')
25
+ return data
26
+
27
+ # Function to convert DataFrame to Excel
28
+ def to_excel(df):
29
+ output = BytesIO()
30
+ writer = pd.ExcelWriter(output, engine='xlsxwriter')
31
+ df.to_excel(writer, sheet_name='Sheet1')
32
+ writer.save()
33
+ processed_data = output.getvalue()
34
+ return processed_data
35
+
36
+
37
+ st.title("Exponential Smoothing Forecasting")
38
+ # Upload Data Section
39
+ # uploaded_file = st.file_uploader("Choose a file")
40
+ # if uploaded_file is not None:
41
+
42
+ data = create_data()
43
+ unique_cities = data['City'].unique()
44
+
45
+ # Select a city
46
+ selected_city = st.selectbox('Select a City', unique_cities)
47
+
48
+ # Sliders for parameter adjustment
49
+ trend = st.select_slider('Select Trend', options=['add', 'mul', None])
50
+ damped_trend = st.checkbox('Damped Trend')
51
+ seasonal = st.select_slider('Select Seasonal', options=['add', 'mul', None])
52
+ seasonal_period = st.slider('Seasonal Period', 1, 24, 12)
53
+
54
+ # ... [previous code remains the same]
55
+
56
+ # Display forecast with current parameters
57
+ city_data = data[data['City'] == selected_city]['Accident Count']
58
+ forecast, aic = run_exp_smoothing(city_data, trend, damped_trend, seasonal, seasonal_period)
59
+
60
+ if forecast is not None:
61
+ st.write(f"Best Parameters with AIC: {aic}")
62
+ st.write(f"Trend: {trend}, Damped Trend: {damped_trend}, Seasonal: {seasonal}, Seasonal Period: {seasonal_period}")
63
+ forecast_index = pd.date_range(start=city_data.index[-1], periods=7, freq='M')[1:]
64
+ forecast_index = forecast_index.to_period('M') # Convert to period index with monthly frequency
65
+ forecast_df = pd.DataFrame(forecast, index=forecast_index, columns=['Forecast'])
66
+ # Ensure the index is correctly formatted as 'YYYY-MM'
67
+ forecast_df.index = forecast_df.index.strftime('%Y-%m')
68
+ st.line_chart(forecast_df)
69
+ # ... [rest of the code]
70
 
 
 
 
71
 
72
+ # Grid search button
73
+ if st.button('Run Grid Search'):
74
+ best_aic = float('inf')
75
+ best_params = None
76
+ for param_set in product(['add', 'mul', None], [True, False], ['add', 'mul', None], [12]):
77
+ _, temp_aic = run_exp_smoothing(city_data, *param_set)
78
+ if temp_aic and temp_aic < best_aic:
79
+ best_aic = temp_aic
80
+ best_params = param_set
81
+ st.write(f"Best Parameters: {best_params} with AIC: {best_aic}")
82
 
83
+ # Export to Excel button
84
+ # if st.button('Export to Excel'):
85
+ # df_to_export = pd.DataFrame(forecast)
86
+ # excel_data = to_excel(df_to_export)
87
+ # st.download_button(label='📥 Download Excel', data=excel_data, file_name='forecast.xlsx', mime='application/vnd.ms-excel')