import streamlit as st import pandas as pd from statsmodels.tsa.holtwinters import ExponentialSmoothing import numpy as np from itertools import product from io import BytesIO # Function to run the Exponential Smoothing Model def run_exp_smoothing(city_data, trend, damped_trend, seasonal, seasonal_period): try: model = ExponentialSmoothing(city_data, trend=trend, damped_trend=damped_trend, seasonal=seasonal, seasonal_periods=seasonal_period) model_fit = model.fit(optimized=True) return model_fit.forecast(steps=6), model_fit.aic except Exception as e: return None, None def create_data(): data = pd.read_csv('accident_count.csv', parse_dates=True, index_col=0) data.index = pd.to_datetime(data.index, format='%Y%m') data = data.groupby('City').resample('M').sum().reset_index() #data = data[data['City'] == 'ARAR'] data.index = data['Accident Month Bracket'] data = data.drop(['Accident Month Bracket'],axis=1) data.index = data.index.strftime('%Y-%m') return data # Function to convert DataFrame to Excel def to_excel(df): output = BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() processed_data = output.getvalue() return processed_data st.title("Exponential Smoothing Forecasting") # Upload Data Section # uploaded_file = st.file_uploader("Choose a file") # if uploaded_file is not None: data = create_data() unique_cities = data['City'].unique() # Select a city selected_city = st.selectbox('Select a City', unique_cities) # Sliders for parameter adjustment trend = st.select_slider('Select Trend', options=['add', 'mul', None]) damped_trend = st.checkbox('Damped Trend') seasonal = st.select_slider('Select Seasonal', options=['add', 'mul', None]) seasonal_period = st.slider('Seasonal Period', 1, 24, 12) # Display forecast with current parameters city_data = data[data['City'] == selected_city]['Accident Count'] forecast, aic = run_exp_smoothing(city_data, trend, damped_trend, seasonal, seasonal_period) if forecast is not None: st.write(f"Forecast with AIC: {aic}") st.line_chart(forecast) # Grid search button if st.button('Run Grid Search'): best_aic = float('inf') best_params = None for param_set in product(['add', 'mul', None], [True, False], ['add', 'mul', None], [12]): _, temp_aic = run_exp_smoothing(city_data, *param_set) if temp_aic and temp_aic < best_aic: best_aic = temp_aic best_params = param_set st.write(f"Best Parameters: {best_params} with AIC: {best_aic}") # Export to Excel button # if st.button('Export to Excel'): # df_to_export = pd.DataFrame(forecast) # excel_data = to_excel(df_to_export) # st.download_button(label='📥 Download Excel', data=excel_data, file_name='forecast.xlsx', mime='application/vnd.ms-excel')