QuantumLearner commited on
Commit
7692b47
·
verified ·
1 Parent(s): ae96aaf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -22
app.py CHANGED
@@ -38,7 +38,13 @@ with st.sidebar.expander("Asset Settings", expanded=True):
38
  # Download data
39
  @st.cache_data
40
  def download_data(ticker, start, end):
41
- data = yf.download(ticker, start=start, end=end)
 
 
 
 
 
 
42
  return data
43
 
44
  # Function to execute and cache strategy results
@@ -149,19 +155,22 @@ run_button = st.sidebar.button("Run Strategy")
149
 
150
  # Running the strategy
151
  if run_button:
152
- # Download data
153
- data = download_data(ticker, start_date, end_date)
 
154
 
155
- # Execute the strategy with optimized parameters
156
- data_with_signals, profit, equity_curve, _, best_params = execute_strategy(data, optimized_params)
157
 
158
- # Cache results in session state
159
- st.session_state['data_with_signals'] = data_with_signals
160
- st.session_state['equity_curve'] = equity_curve
161
- st.session_state['best_params'] = best_params
162
 
163
- # Display optimized parameters
164
- st.json(best_params)
 
 
165
 
166
  # If session state contains data, allow for post-run parameter adjustments
167
  if 'data_with_signals' in st.session_state:
@@ -188,7 +197,7 @@ if 'data_with_signals' in st.session_state:
188
  # Plotting with adjustments for easier comparison of x-axis
189
  fig = make_subplots(rows=3, cols=1, shared_xaxes=True,
190
  subplot_titles=("Price and Bollinger Bands", "RSI", "Equity Curve"),
191
- vertical_spacing=0.20) # Increased vertical spacing
192
 
193
  # Price and signal plot
194
  fig.add_trace(go.Scatter(x=updated_data.index, y=updated_data['Close'], mode='lines', name='Close Price'))
@@ -199,16 +208,16 @@ if 'data_with_signals' in st.session_state:
199
  buy_signals = updated_data[updated_data['signal'] == 'Buy']
200
  sell_signals = updated_data[updated_data['signal'] == 'Sell']
201
  fig.add_trace(go.Scatter(x=buy_signals.index, y=buy_signals['Close'], mode='markers', name='Buy Signal',
202
- marker=dict(color='green', symbol='triangle-up', size=12))) # Increased size
203
  fig.add_trace(go.Scatter(x=sell_signals.index, y=sell_signals['Close'], mode='markers', name='Sell Signal',
204
- marker=dict(color='red', symbol='triangle-down', size=12))) # Increased size
205
 
206
  # RSI Plot with black line, red upper threshold, and green lower threshold
207
  fig.add_trace(go.Scatter(x=updated_data.index, y=updated_data['rsi'], mode='lines', name='RSI', line=dict(color='white')), row=2, col=1)
208
  fig.add_shape(type="line", x0=updated_data.index[0], x1=updated_data.index[-1], y0=30, y1=30,
209
- line=dict(dash='dash', color='green'), row=2, col=1) # Lower threshold in green
210
  fig.add_shape(type="line", x0=updated_data.index[0], x1=updated_data.index[-1], y0=70, y1=70,
211
- line=dict(dash='dash', color='red'), row=2, col=1) # Upper threshold in red
212
 
213
  # Equity Curve Plot
214
  fig.add_trace(go.Scatter(x=updated_data.index, y=st.session_state['equity_curve'], mode='lines', name='Equity Curve'), row=3, col=1)
@@ -219,11 +228,10 @@ if 'data_with_signals' in st.session_state:
219
  xaxis_title='Date',
220
  yaxis_title='Price',
221
  legend=dict(orientation="h", yanchor="bottom", y=1.15, xanchor="center", x=0.5, traceorder='normal', valign='top', borderwidth=0),
222
- height=1000, # Increase the height for better visibility
223
- margin=dict(t=30, b=30), # Adjust margins for better spacing
224
- font=dict(size=12), # Adjust font size for better readability
225
- # Subplot title style adjustment for black color
226
- annotations=[dict(font=dict(color="white", size=14)) for _ in range(3)] # Adjusts all subplot titles to black
227
  )
228
 
229
  # Display the chart
@@ -235,4 +243,4 @@ hide_streamlit_style = """
235
  footer {visibility: hidden;}
236
  </style>
237
  """
238
- st.markdown(hide_streamlit_style, unsafe_allow_html=True)
 
38
  # Download data
39
  @st.cache_data
40
  def download_data(ticker, start, end):
41
+ data = yf.download(ticker, start=start, end=end, auto_adjust=False)
42
+ if isinstance(data.columns, pd.MultiIndex):
43
+ data.columns = data.columns.get_level_values(0)
44
+ if data.empty:
45
+ raise ValueError(f"No data retrieved for {ticker}")
46
+ if len(data) < 24: # Minimum needed for 24-period Pivot Point calculation
47
+ raise ValueError(f"Insufficient data points for {ticker}. Need at least 24 days.")
48
  return data
49
 
50
  # Function to execute and cache strategy results
 
155
 
156
  # Running the strategy
157
  if run_button:
158
+ try:
159
+ # Download data
160
+ data = download_data(ticker, start_date, end_date)
161
 
162
+ # Execute the strategy with optimized parameters
163
+ data_with_signals, profit, equity_curve, _, best_params = execute_strategy(data, optimized_params)
164
 
165
+ # Cache results in session state
166
+ st.session_state['data_with_signals'] = data_with_signals
167
+ st.session_state['equity_curve'] = equity_curve
168
+ st.session_state['best_params'] = best_params
169
 
170
+ # Display optimized parameters
171
+ st.json(best_params)
172
+ except Exception as e:
173
+ st.error(f"An error occurred while running the analysis: {e}")
174
 
175
  # If session state contains data, allow for post-run parameter adjustments
176
  if 'data_with_signals' in st.session_state:
 
197
  # Plotting with adjustments for easier comparison of x-axis
198
  fig = make_subplots(rows=3, cols=1, shared_xaxes=True,
199
  subplot_titles=("Price and Bollinger Bands", "RSI", "Equity Curve"),
200
+ vertical_spacing=0.20)
201
 
202
  # Price and signal plot
203
  fig.add_trace(go.Scatter(x=updated_data.index, y=updated_data['Close'], mode='lines', name='Close Price'))
 
208
  buy_signals = updated_data[updated_data['signal'] == 'Buy']
209
  sell_signals = updated_data[updated_data['signal'] == 'Sell']
210
  fig.add_trace(go.Scatter(x=buy_signals.index, y=buy_signals['Close'], mode='markers', name='Buy Signal',
211
+ marker=dict(color='green', symbol='triangle-up', size=12)))
212
  fig.add_trace(go.Scatter(x=sell_signals.index, y=sell_signals['Close'], mode='markers', name='Sell Signal',
213
+ marker=dict(color='red', symbol='triangle-down', size=12)))
214
 
215
  # RSI Plot with black line, red upper threshold, and green lower threshold
216
  fig.add_trace(go.Scatter(x=updated_data.index, y=updated_data['rsi'], mode='lines', name='RSI', line=dict(color='white')), row=2, col=1)
217
  fig.add_shape(type="line", x0=updated_data.index[0], x1=updated_data.index[-1], y0=30, y1=30,
218
+ line=dict(dash='dash', color='green'), row=2, col=1)
219
  fig.add_shape(type="line", x0=updated_data.index[0], x1=updated_data.index[-1], y0=70, y1=70,
220
+ line=dict(dash='dash', color='red'), row=2, col=1)
221
 
222
  # Equity Curve Plot
223
  fig.add_trace(go.Scatter(x=updated_data.index, y=st.session_state['equity_curve'], mode='lines', name='Equity Curve'), row=3, col=1)
 
228
  xaxis_title='Date',
229
  yaxis_title='Price',
230
  legend=dict(orientation="h", yanchor="bottom", y=1.15, xanchor="center", x=0.5, traceorder='normal', valign='top', borderwidth=0),
231
+ height=1000,
232
+ margin=dict(t=30, b=30),
233
+ font=dict(size=12),
234
+ annotations=[dict(font=dict(color="white", size=14)) for _ in range(3)]
 
235
  )
236
 
237
  # Display the chart
 
243
  footer {visibility: hidden;}
244
  </style>
245
  """
246
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)