import gradio as gr import pandas as pd import pmdarima as pm from pmdarima import auto_arima import matplotlib.pyplot as plt def forecast_time_series(file): # Load data data = pd.read_csv(file.name, skiprows=2) period_type = data.columns[0] data[period_type] = pd.to_datetime(data[period_type]) data.set_index(period_type, inplace=True) # Fit the SARIMAX model automatically model = auto_arima(data) # Forecasting n_periods = 24 # Number of periods to forecast forecast, conf_int = model.predict(n_periods=n_periods, return_conf_int=True) # Create a DataFrame with the forecast and confidence intervals forecast_index = pd.date_range(start=data.index[-1], periods=n_periods + 1, freq=data.index.inferred_freq)[1:] forecast_df = pd.DataFrame(forecast, index=forecast_index, columns=['Forecast']) conf_int_df = pd.DataFrame(conf_int, index=forecast_index, columns=['Lower CI', 'Upper CI']) forecast_df = pd.concat([forecast_df, conf_int_df], axis=1) # Calculate the YoY change sum_last_12_original = data.iloc[-12:, 0].sum() sum_first_12_forecast = forecast_df['Forecast'].iloc[:12].sum() yoy_change = (sum_first_12_forecast - sum_last_12_original) / sum_last_12_original # Plot the original time series and forecast plt.figure(figsize=(12, 6)) plt.plot(data.index, data.iloc[:, 0], label='Original Series') plt.plot(forecast_df.index, forecast_df['Forecast'], color='red', label='Forecast') plt.fill_between(forecast_df.index, forecast_df['Lower CI'], forecast_df['Upper CI'], color='pink', alpha=0.3, label='Confidence Interval') plt.xlabel('Date') plt.ylabel('Values') plt.title('Original Time Series and Forecast with Confidence Intervals') plt.legend() # Save plot to a file plot_file = 'forecast_plot.png' plt.savefig(plot_file) plt.close() # Return plot file path and YoY change return plot_file, f'Year-over-Year Change in Sum of Values: {yoy_change:.2%}' # Create Gradio interface interface = gr.Interface( theme=gr.themes.Monochrome(), fn=forecast_time_series, inputs=gr.File(label="Upload Time Series CSV"), outputs=[ gr.Image(label="Time Series + Forecast Chart"), gr.Text(label="YoY % Change") ], title="Time Series Forecasting", description="Upload a CSV file with a time series to forecast the next 24 periods and see the YoY % change." ) # Launch the interface interface.launch()