mmmapms commited on
Commit
c01e48a
1 Parent(s): 4e529c0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -13
app.py CHANGED
@@ -84,20 +84,62 @@ max_date_allowed_pred = df_filtered['Date'].max().date()
84
  end_date = df['Date'].max().date()
85
  start_date = end_date - pd.Timedelta(days=7)
86
 
87
- models_corr_matrix = ['Neural Network 1', 'Neural Network 2', 'Neural Network 3',
88
  'Neural Network 4', 'Regularized Linear Model 1',
89
  'Regularized Linear Model 2', 'Regularized Linear Model 3',
90
- 'Regularized Linear Model 4']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- st.title("Belgium: Electricity Price Forecasting")
93
 
94
  # Sidebar for inputs
95
  with st.sidebar:
96
  st.write("### Variables Selection for Graph")
97
  st.write("Select which variables you'd like to include in the graph. This will affect the displayed charts and available data for download.")
98
- selected_variables = st.multiselect("Select variables to display:", ['Real Price', 'Neural Network 1', 'Neural Network 2', 'Neural Network 3', 'Neural Network 4', 'Regularized Linear Model 1', 'Regularized Linear Model 2','Regularized Linear Model 3', 'Regularized Linear Model 4', 'Hybrid Ensemble', 'Persistence Model'], default=['Real Price','Neural Network 4', 'Regularized Linear Model 4', 'Persistence Model'])#options=['Real Price', 'Neural Network 1', 'Neural Network 2', 'Neural Network 3', 'Neural Network 4', 'Neural Network Ensemble', 'Regularized Linear Model 1', 'Regularized Linear Model 2','Regularized Linear Model 3', 'Regularized Linear Model 4', 'Regularized Linear Model Ensemble', 'Hybrid Ensemble', 'Persistence Model'], default=['Real Price', 'Neural Network Ensemble', 'Regularized Linear Model Ensemble', 'Persistence Model'])
99
  st.write("### Model Selection for Scatter Plot")
100
- model_selection = st.selectbox("Select which model's predictions to display:", options=['Neural Network 1', 'Neural Network 2', 'Neural Network 3', 'Neural Network 4', 'Regularized Linear Model 1', 'Regularized Linear Model 2','Regularized Linear Model 3', 'Regularized Linear Model 4', 'Hybrid Ensemble', 'Persistence Model'], index=8)#options=['Neural Network 1', 'Neural Network 2', 'Neural Network 3', 'Neural Network 4', 'Neural Network Ensemble', 'Regularized Linear Model 1', 'Regularized Linear Model 2','Regularized Linear Model 3', 'Regularized Linear Model 4', 'Regularized Linear Model Ensemble', 'Hybrid Ensemble', 'Persistence Model'], index=10) # Adjust the index as needed to default to your desired option
101
 
102
  st.write("### Date Range for Metrics Calculation")
103
  st.write("Select the date range to calculate the metrics for the predictions. This will influence the accuracy metrics displayed below. The complete dataset ranges from 10/03/2024 until today.")
@@ -107,14 +149,42 @@ with st.sidebar:
107
  if not selected_variables:
108
  st.warning("Please select at least one variable to display.")
109
  else:
110
- # Plotting
111
  st.write("## Belgian Day-Ahead Electricity Prices")
112
- temp_df = df[(df['Date'] >= pd.Timestamp(start_date))] #& (df['Date'] <= pd.Timestamp(end_date))]
 
 
 
 
 
 
 
113
  fig = go.Figure()
114
 
115
  for variable in selected_variables:
116
  fig.add_trace(go.Scatter(x=temp_df['Date'], y=temp_df[variable], mode='lines', name=variable))
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  fig.update_layout(xaxis_title="Date", yaxis_title="Price [EUR/MWh]")
119
  st.plotly_chart(fig, use_container_width=True)
120
  st.write("The graph presented here illustrates the day-ahead electricity price forecasts for Belgium, covering the period from one week ago up to tomorrow. It incorporates predictions from three distinct models: a Neural Network, a Regularized Linear Model, and Persistence, alongside the actual electricity prices up until today.")
@@ -146,7 +216,13 @@ else:
146
  fig.add_trace(go.Scatter(x=plot_df['Real Price'], y=regression_line, mode='lines', name=equation, line=dict(color='black')))
147
 
148
  # Update layout with appropriate titles
149
- fig.update_layout(xaxis_title="Real Price [EUR/MWh]", yaxis_title=f"{model_selection} Predictions [EUR/MWh]", title=f"Scatter Plot of Real Price vs {model_selection} Predictions from {min_date_allowed_pred} to {max_date_allowed_pred}")
 
 
 
 
 
 
150
  st.plotly_chart(fig, use_container_width=True)
151
 
152
 
@@ -158,11 +234,6 @@ if start_date_pred and end_date_pred:
158
  filtered_df = df_filtered[(df_filtered['Date'] >= pd.Timestamp(start_date_pred)) & (df_filtered['Date'] <= pd.Timestamp(end_date_pred))]
159
 
160
  # List of models for convenience
161
- #models = [
162
- # 'Neural Network 1', 'Neural Network 2', 'Neural Network 3', 'Neural Network 4', 'Neural Network Ensemble',
163
- # 'Regularized Linear Model 1', 'Regularized Linear Model 2', 'Regularized Linear Model 3', 'Regularized Linear Model 4', 'Regularized Linear Model Ensemble',
164
- # 'Persistence Model', 'Hybrid Ensemble'
165
- #]
166
  models = [
167
  'Neural Network 1', 'Neural Network 2', 'Neural Network 3', 'Neural Network 4',
168
  'Regularized Linear Model 1', 'Regularized Linear Model 2', 'Regularized Linear Model 3', 'Regularized Linear Model 4',
 
84
  end_date = df['Date'].max().date()
85
  start_date = end_date - pd.Timedelta(days=7)
86
 
87
+ models_corr_matrix = ['Persistence Model', 'Neural Network 1', 'Neural Network 2', 'Neural Network 3',
88
  'Neural Network 4', 'Regularized Linear Model 1',
89
  'Regularized Linear Model 2', 'Regularized Linear Model 3',
90
+ 'Regularized Linear Model 4', 'Hybrid Ensemble']
91
+
92
+ def conformal_predictions(data):
93
+ data['Residuals'] = data['Hybrid Ensemble'] - data['Real Price']
94
+ data.set_index('Date', inplace=True)
95
+ data['Hour'] = data.index.hour
96
+ min_date = data.index.min()
97
+ for date in data.index.normalize().unique():
98
+ if date >= min_date + pd.DateOffset(days=30):
99
+ start_date = date - pd.DateOffset(days=30)
100
+ end_date = date
101
+ calculation_window = data[start_date:end_date-pd.DateOffset(hours=1)]
102
+ quantiles = calculation_window.groupby('Hour')['Residuals'].quantile(0.9)
103
+ # Use .loc to safely access and modify data
104
+ if date in data.index:
105
+ current_day_data = data.loc[date.strftime('%Y-%m-%d')]
106
+ for hour in current_day_data['Hour'].unique():
107
+ if hour in quantiles.index:
108
+ hour_quantile = quantiles[hour]
109
+ idx = (data.index.normalize() == date) & (data.Hour == hour)
110
+ data.loc[idx, 'Quantile_90'] = hour_quantile
111
+ data.loc[idx, 'Lower_Interval'] = data.loc[idx, 'Hybrid Ensemble'] - hour_quantile
112
+ data.loc[idx, 'Upper_Interval'] = data.loc[idx, 'Hybrid Ensemble'] + hour_quantile
113
+ data.reset_index(inplace=True)
114
+ return data
115
+
116
+ # Main layout of the app
117
+ col1, col2 = st.columns([5, 2]) # Adjust the ratio to better fit your layout needs
118
+ with col1:
119
+ st.title("Belgium: Electricity Price Forecasting")
120
+
121
+ with col2:
122
+ upper_space = col2.empty()
123
+ upper_space = col2.empty()
124
+ col2_1, col2_2 = st.columns(2) # Create two columns within the right column for side-by-side images
125
+ with col2_1:
126
+ st.image("C:/Users/mmascare/Documents/KU_Leuven_logo.png", width=100) # Adjust the path and width as needed
127
+ with col2_2:
128
+ st.image("C:/Users/mmascare/Documents/energyville_logo.png", width=100)
129
+
130
+ upper_space.markdown("""
131
+ &nbsp;
132
+ &nbsp;
133
+ """, unsafe_allow_html=True)
134
 
 
135
 
136
  # Sidebar for inputs
137
  with st.sidebar:
138
  st.write("### Variables Selection for Graph")
139
  st.write("Select which variables you'd like to include in the graph. This will affect the displayed charts and available data for download.")
140
+ selected_variables = st.multiselect("Select variables to display:", options=['Real Price', 'Neural Network 1', 'Neural Network 2', 'Neural Network 3', 'Neural Network 4', 'Regularized Linear Model 1', 'Regularized Linear Model 2','Regularized Linear Model 3', 'Regularized Linear Model 4', 'Hybrid Ensemble', 'Persistence Model'], default=['Real Price', 'Hybrid Ensemble'])
141
  st.write("### Model Selection for Scatter Plot")
142
+ model_selection = st.selectbox("Select which model's predictions to display:", options=['Neural Network 1', 'Neural Network 2', 'Neural Network 3', 'Neural Network 4', 'Regularized Linear Model 1', 'Regularized Linear Model 2','Regularized Linear Model 3', 'Regularized Linear Model 4', 'Hybrid Ensemble', 'Persistence Model'], index=8) # Adjust the index as needed to default to your desired option
143
 
144
  st.write("### Date Range for Metrics Calculation")
145
  st.write("Select the date range to calculate the metrics for the predictions. This will influence the accuracy metrics displayed below. The complete dataset ranges from 10/03/2024 until today.")
 
149
  if not selected_variables:
150
  st.warning("Please select at least one variable to display.")
151
  else:
 
152
  st.write("## Belgian Day-Ahead Electricity Prices")
153
+
154
+ # Call conformal_predictions if 'Hybrid Ensemble' is selected
155
+ if 'Hybrid Ensemble' in selected_variables:
156
+ df = conformal_predictions(df) # Make sure this function modifies df correctly
157
+
158
+ temp_df = df[(df['Date'] >= pd.Timestamp(start_date))] # Ensure correct date filtering
159
+
160
+ # Initialize Plotly figure
161
  fig = go.Figure()
162
 
163
  for variable in selected_variables:
164
  fig.add_trace(go.Scatter(x=temp_df['Date'], y=temp_df[variable], mode='lines', name=variable))
165
 
166
+ # Check if conformal predictions should be added for Hybrid Ensemble
167
+ if variable == 'Hybrid Ensemble' and 'Quantile_90' in df.columns:
168
+ # Add the lower interval trace
169
+ fig.add_trace(go.Scatter(
170
+ x=temp_df['Date'],
171
+ y=temp_df['Lower_Interval'],
172
+ mode='lines',
173
+ line=dict(width=0),
174
+ showlegend=False
175
+ ))
176
+
177
+ # Add the upper interval trace and fill to the lower interval
178
+ fig.add_trace(go.Scatter(
179
+ x=temp_df['Date'],
180
+ y=temp_df['Upper_Interval'],
181
+ mode='lines',
182
+ line=dict(width=0),
183
+ fill='tonexty', # Fill between this trace and the previous one
184
+ fillcolor='rgba(68, 68, 68, 0.3)',
185
+ name='Conformal Prediction'
186
+ ))
187
+
188
  fig.update_layout(xaxis_title="Date", yaxis_title="Price [EUR/MWh]")
189
  st.plotly_chart(fig, use_container_width=True)
190
  st.write("The graph presented here illustrates the day-ahead electricity price forecasts for Belgium, covering the period from one week ago up to tomorrow. It incorporates predictions from three distinct models: a Neural Network, a Regularized Linear Model, and Persistence, alongside the actual electricity prices up until today.")
 
216
  fig.add_trace(go.Scatter(x=plot_df['Real Price'], y=regression_line, mode='lines', name=equation, line=dict(color='black')))
217
 
218
  # Update layout with appropriate titles
219
+ fig.update_layout(
220
+ title=f"Scatter Plot of Real Price vs {model_selection} Predictions from {min_date_allowed_pred} to {max_date_allowed_pred}",
221
+ xaxis_title="Real Price [EUR/MWh]",
222
+ yaxis_title=f"{model_selection} Predictions [EUR/MWh]",
223
+ xaxis=dict(range=[-160, 160]), # Setting the x-axis range
224
+ yaxis=dict(range=[-150, 150]) # Setting the y-axis range
225
+ )
226
  st.plotly_chart(fig, use_container_width=True)
227
 
228
 
 
234
  filtered_df = df_filtered[(df_filtered['Date'] >= pd.Timestamp(start_date_pred)) & (df_filtered['Date'] <= pd.Timestamp(end_date_pred))]
235
 
236
  # List of models for convenience
 
 
 
 
 
237
  models = [
238
  'Neural Network 1', 'Neural Network 2', 'Neural Network 3', 'Neural Network 4',
239
  'Regularized Linear Model 1', 'Regularized Linear Model 2', 'Regularized Linear Model 3', 'Regularized Linear Model 4',