ojas121 commited on
Commit
c3e391e
·
verified ·
1 Parent(s): 922e510

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -0
app.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.graph_objs as go
4
+ from statsmodels.tsa.arima.model import ARIMA
5
+ from statsmodels.tsa.stattools import adfuller
6
+
7
+ # Set Streamlit page configuration
8
+ st.set_page_config(page_title="ARIMA Forecasting with Streamlit", layout="wide")
9
+
10
+ # Title of the Streamlit app
11
+ st.title("📈 Time Series Forecasting with ARIMA for Vegetable Prices")
12
+
13
+ # Sidebar configuration for user inputs
14
+ st.sidebar.header("User Configuration")
15
+ file_path = st.sidebar.text_input("Enter the path to your CSV file", 'arima.csv')
16
+
17
+ p = st.sidebar.number_input("ARIMA Parameter p (AR term)", min_value=0, max_value=5, value=1)
18
+ d = st.sidebar.number_input("ARIMA Parameter d (Differencing)", min_value=0, max_value=2, value=1)
19
+ q = st.sidebar.number_input("ARIMA Parameter q (MA term)", min_value=0, max_value=5, value=1)
20
+
21
+ # Load and preprocess data
22
+ try:
23
+ data = pd.read_csv(file_path)
24
+ data['Date'] = pd.to_datetime(data['Date'], format='%d-%m-%Y', errors='coerce')
25
+ data = data.dropna(subset=['Date', 'Average'])
26
+ commodities = data['Commodity'].unique()
27
+ except FileNotFoundError:
28
+ st.error("Data file not found. Please check the file path and try again.")
29
+ st.stop()
30
+
31
+ # Sidebar for user input to select a commodity
32
+ selected_commodity = st.sidebar.selectbox("Select a Vegetable Commodity", commodities)
33
+
34
+ # Filter data based on the selected commodity and sort by date
35
+ commodity_data = data[data['Commodity'] == selected_commodity].sort_values('Date')
36
+
37
+ # Display data and perform ADF Test
38
+ st.subheader(f"Data Overview and Stationarity Check for '{selected_commodity}'")
39
+ st.write(commodity_data.head())
40
+
41
+ # Perform the Augmented Dickey-Fuller (ADF) test
42
+ adf_result = adfuller(commodity_data['Average'])
43
+ is_stationary = adf_result[1] < 0.05
44
+
45
+ # Display ADF test results
46
+ with st.expander(f"Augmented Dickey-Fuller Test Results for '{selected_commodity}'", expanded=False):
47
+ st.write(f"ADF Statistic: {adf_result[0]:.4f}")
48
+ st.write(f"p-value: {adf_result[1]:.4f}")
49
+ st.write("Critical Values:")
50
+ for key, value in adf_result[4].items():
51
+ st.write(f" {key}: {value:.4f}")
52
+ st.success(f"The time series is {'stationary' if is_stationary else 'not stationary'} (p-value {'<' if is_stationary else '>='} 0.05).")
53
+
54
+ # ARIMA model fitting with user-selected parameters
55
+ st.subheader(f"ARIMA Model Fitting and Summary for '{selected_commodity}'")
56
+ model = ARIMA(commodity_data['Average'], order=(p, d, q))
57
+ model_fit = model.fit()
58
+
59
+ # Display model summary
60
+ with st.expander("ARIMA Model Summary", expanded=False):
61
+ st.write(model_fit.summary())
62
+
63
+ # Forecast future values up to December 31, 2025
64
+ last_date = commodity_data['Date'].max()
65
+ forecast_end_date = pd.to_datetime('2025-12-31')
66
+ forecast_periods = (forecast_end_date - last_date).days # Calculate days until end of 2025
67
+
68
+ # Make forecast
69
+ forecast = model_fit.get_forecast(steps=forecast_periods)
70
+ forecast_index = pd.date_range(start=last_date + pd.Timedelta(days=1), periods=forecast_periods)
71
+ forecast_values = forecast.predicted_mean
72
+ conf_int = forecast.conf_int()
73
+
74
+ # Plotly graph for interactive visualization
75
+ st.subheader(f"Forecast Visualization for '{selected_commodity}' until {forecast_end_date.date()}")
76
+ fig = go.Figure()
77
+
78
+ # Plot historical data
79
+ fig.add_trace(go.Scatter(
80
+ x=commodity_data['Date'],
81
+ y=commodity_data['Average'],
82
+ mode='lines+markers',
83
+ name='Historical Data',
84
+ line=dict(color='royalblue', width=2)
85
+ ))
86
+
87
+ # Plot forecasted data
88
+ fig.add_trace(go.Scatter(
89
+ x=forecast_index,
90
+ y=forecast_values,
91
+ mode='lines+markers',
92
+ name='Forecast',
93
+ line=dict(color='red', width=2, dash='dash'),
94
+ hovertemplate='Date: %{x}<br>Price: %{y:.2f}<extra></extra>'
95
+ ))
96
+
97
+ # Plot confidence intervals
98
+ fig.add_trace(go.Scatter(
99
+ x=forecast_index.tolist() + forecast_index[::-1].tolist(),
100
+ y=conf_int.iloc[:, 0].tolist() + conf_int.iloc[:, 1][::-1].tolist(),
101
+ fill='toself',
102
+ fillcolor='rgba(173, 216, 230,0.2)',
103
+ line=dict(color='rgba(255,255,255,0)'),
104
+ name='Confidence Interval'
105
+ ))
106
+
107
+ # Update layout for a better presentation
108
+ fig.update_layout(
109
+ title=f"ARIMA Forecast for '{selected_commodity}' Prices until 2025",
110
+ xaxis_title='Date',
111
+ yaxis_title='Average Price (in Kg)',
112
+ legend=dict(x=0.01, y=0.99),
113
+ template='plotly_white',
114
+ hovermode='x unified'
115
+ )
116
+
117
+ # Display Plotly chart
118
+ st.plotly_chart(fig, use_container_width=True)
119
+
120
+ # Display forecasted values in a table format for better visibility
121
+ st.subheader(f"Forecasted Prices for '{selected_commodity}' until 2025")
122
+ forecast_table = pd.DataFrame({
123
+ 'Date': forecast_index,
124
+ 'Forecasted Price': forecast_values,
125
+ 'Lower Confidence Interval': conf_int.iloc[:, 0],
126
+ 'Upper Confidence Interval': conf_int.iloc[:, 1]
127
+ })
128
+ st.dataframe(forecast_table)
129
+
130
+ st.info("Adjust the ARIMA parameters in the sidebar to see different results.")