QuantumLearner commited on
Commit
035df4e
·
verified ·
1 Parent(s): aee32b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -102
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import pandas as pd
2
  import numpy as np
3
- import matplotlib.pyplot as plt
4
  import yfinance as yf
5
  import streamlit as st
6
  import plotly.graph_objects as go
@@ -11,14 +10,12 @@ from ta.volatility import BollingerBands
11
 
12
  # Helper functions
13
  def fetch_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame:
14
- """Fetch stock or crypto data from Yahoo Finance."""
15
  return yf.download(ticker, start=start_date, end=end_date)
16
 
17
  def plot_z_score(close_prices: pd.Series, periods: list, z_thresh: float, n_days: int) -> go.Figure:
18
  fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
19
  subplot_titles=('Close Prices', 'Rolling Z-Scores'))
20
 
21
- # Plot stock price
22
  fig.add_trace(go.Scatter(x=close_prices.index, y=close_prices, mode='lines', name='Close Prices'), row=1, col=1)
23
 
24
  for period in periods:
@@ -46,7 +43,6 @@ def plot_z_score(close_prices: pd.Series, periods: list, z_thresh: float, n_days
46
  name=f'Sell Signal {period} days'), row=1, col=1)
47
  fig.add_trace(go.Scatter(x=close_prices.index, y=z_scores, mode='lines', name=f'Rolling Z-Score {period}'), row=2, col=1)
48
 
49
- # Add threshold lines
50
  fig.add_hline(y=z_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
51
  fig.add_hline(y=-z_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
52
 
@@ -58,7 +54,6 @@ def plot_roc(prices: pd.Series, n: int = 14) -> go.Figure:
58
  fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
59
  subplot_titles=('Stock Price', 'Rate of Change (ROC)'))
60
 
61
- # Plot stock price
62
  fig.add_trace(go.Scatter(x=prices.index, y=prices, mode='lines', name='Stock Price'), row=1, col=1)
63
  fig.add_trace(go.Scatter(x=prices.index, y=roc, mode='lines', name='ROC'), row=2, col=1)
64
 
@@ -70,7 +65,6 @@ def plot_roc(prices: pd.Series, n: int = 14) -> go.Figure:
70
  fig.add_trace(go.Scatter(x=prices[sell_signals].index, y=prices[sell_signals], mode='markers',
71
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
72
 
73
- # Add threshold line
74
  fig.add_hline(y=0, line=dict(color='gray', dash='dash'), row=2, col=1)
75
 
76
  fig.update_layout(title='Rate of Change (ROC) with Buy/Sell Signals', xaxis_title='Date', yaxis_title='Price', yaxis2_title='ROC')
@@ -97,7 +91,6 @@ def plot_stochastic_oscillator(data: pd.DataFrame, buy_thresh: float, sell_thres
97
  fig.add_trace(go.Scatter(x=data[sell_signals].index, y=data[sell_signals]['Close'], mode='markers',
98
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
99
 
100
- # Add threshold lines
101
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
102
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
103
 
@@ -120,7 +113,6 @@ def plot_rsi(prices: pd.Series, buy_thresh: float, sell_thresh: float) -> go.Fig
120
  fig.add_trace(go.Scatter(x=prices[sell_signals].index, y=prices[sell_signals], mode='markers',
121
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
122
 
123
- # Add threshold lines
124
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
125
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
126
 
@@ -174,7 +166,6 @@ def plot_bollinger_bands(prices: pd.Series) -> go.Figure:
174
  return fig
175
 
176
  def plot_k_reversal(data: pd.DataFrame, n: int, buy_thresh: float, sell_thresh: float) -> go.Figure:
177
- """Plot K Reversal indicator with buy and sell signals."""
178
  high_n = data['High'].rolling(n).max()
179
  low_n = data['Low'].rolling(n).min()
180
  k_values = 100 * (data['Close'] - low_n) / (high_n - low_n)
@@ -193,7 +184,6 @@ def plot_k_reversal(data: pd.DataFrame, n: int, buy_thresh: float, sell_thresh:
193
  fig.add_trace(go.Scatter(x=data[sell_signals].index, y=data[sell_signals]['Close'], mode='markers',
194
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
195
 
196
- # Add threshold lines
197
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
198
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
199
 
@@ -201,7 +191,6 @@ def plot_k_reversal(data: pd.DataFrame, n: int, buy_thresh: float, sell_thresh:
201
  return fig
202
 
203
  def plot_awesome_oscillator(data: pd.DataFrame, signal_period: int, buy_thresh: float, sell_thresh: float) -> go.Figure:
204
- """Plot Awesome Oscillator with buy and sell signals."""
205
  ao_indicator = AwesomeOscillatorIndicator(high=data['High'], low=data['Low'])
206
  data['AO'] = ao_indicator.awesome_oscillator()
207
  data['Signal'] = data['AO'].rolling(window=signal_period).mean()
@@ -221,7 +210,6 @@ def plot_awesome_oscillator(data: pd.DataFrame, signal_period: int, buy_thresh:
221
  fig.add_trace(go.Scatter(x=data[sell_signals].index, y=data['Close'][sell_signals], mode='markers',
222
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
223
 
224
- # Add threshold lines
225
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
226
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
227
 
@@ -229,7 +217,6 @@ def plot_awesome_oscillator(data: pd.DataFrame, signal_period: int, buy_thresh:
229
  return fig
230
 
231
  def plot_williams_r(data: pd.DataFrame, n: int, buy_thresh: float, sell_thresh: float) -> go.Figure:
232
- """Plot Williams %R with buy and sell signals."""
233
  williams_r = WilliamsRIndicator(high=data['High'], low=data['Low'], close=data['Close'], lbp=n)
234
  data['Williams %R'] = williams_r.williams_r()
235
 
@@ -247,7 +234,6 @@ def plot_williams_r(data: pd.DataFrame, n: int, buy_thresh: float, sell_thresh:
247
  fig.add_trace(go.Scatter(x=data[sell_signals].index, y=data[sell_signals]['Close'], mode='markers',
248
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
249
 
250
- # Add threshold lines
251
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
252
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
253
 
@@ -255,7 +241,6 @@ def plot_williams_r(data: pd.DataFrame, n: int, buy_thresh: float, sell_thresh:
255
  return fig
256
 
257
  def plot_aroon(data: pd.DataFrame, aroon_osc: pd.Series, buy_signals: pd.Series, sell_signals: pd.Series) -> go.Figure:
258
- """Plot Aroon Oscillator with buy and sell signals."""
259
  fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
260
  subplot_titles=('Close Price', 'Aroon Oscillator'))
261
 
@@ -267,14 +252,12 @@ def plot_aroon(data: pd.DataFrame, aroon_osc: pd.Series, buy_signals: pd.Series,
267
  fig.add_trace(go.Scatter(x=sell_signals.index[sell_signals], y=data['Close'][sell_signals], mode='markers',
268
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
269
 
270
- # Add threshold line
271
  fig.add_hline(y=0, line=dict(color='black', dash='dash'), row=2, col=1)
272
 
273
  fig.update_layout(title='Aroon Oscillator with Buy/Sell Signals', xaxis_title='Date', yaxis_title='Price', yaxis2_title='Aroon Oscillator')
274
  return fig
275
 
276
  def aroon_oscillator(data: pd.DataFrame, period: int) -> pd.Series:
277
- """Calculate Aroon Oscillator."""
278
  aroon_up = 100 * (data['High'].rolling(period + 1).apply(lambda x: np.argmax(x[::-1]), raw=True) / period)
279
  aroon_down = 100 * (data['Low'].rolling(period + 1).apply(lambda x: np.argmin(x[::-1]), raw=True) / period)
280
  aroon_osc = aroon_up - aroon_down
@@ -284,95 +267,20 @@ def aroon_oscillator(data: pd.DataFrame, period: int) -> pd.Series:
284
  st.set_page_config(page_title="Technical Analysis", layout="wide")
285
  st.title('Technical Analysis Indicators')
286
 
 
 
 
 
 
 
 
 
 
 
287
  # Sidebar for method selection
288
  with st.sidebar.expander("Method Selection", expanded=True):
289
  selected = st.radio("Select Indicator", ["Rolling Z-Score", "Rate of Change (ROC)", "Stochastic Oscillator", "Relative Strength Index (RSI)", "MACD", "Bollinger Bands", "K Reversal", "Awesome Oscillator", "Williams %R", "Aroon Oscillator"])
290
 
291
- # Sidebar for "How to Use" instructions specific to the selected method
292
- with st.sidebar.expander("How to Use", expanded=True):
293
- if selected == "Rolling Z-Score":
294
- st.markdown("""
295
- 1. Enter the stock or crypto symbol (e.g., 'AAPL' for Apple or 'BTC-USD' for Bitcoin).
296
- 2. Choose the date range.
297
- 3. Set the number of days for the z-score calculation.
298
- 4. Set the z-score threshold.
299
- 5. Click 'Fetch Data' to load the data.
300
- 6. The chart will display the rolling z-scores and highlight buy/sell signals based on the thresholds.
301
- """)
302
- elif selected == "Rate of Change (ROC)":
303
- st.markdown("""
304
- 1. Enter the stock or crypto symbol.
305
- 2. Choose the date range.
306
- 3. Set the number of days for the ROC calculation.
307
- 4. Click 'Fetch Data' to load the data.
308
- 5. The chart will display the ROC and highlight buy/sell signals based on ROC crossing zero.
309
- """)
310
- elif selected == "Stochastic Oscillator":
311
- st.markdown("""
312
- 1. Enter the stock or crypto symbol.
313
- 2. Choose the date range.
314
- 3. Set the buy and sell thresholds.
315
- 4. Click 'Fetch Data' to load the data.
316
- 5. The chart will display the Stochastic Oscillator and highlight buy/sell signals.
317
- """)
318
- elif selected == "Relative Strength Index (RSI)":
319
- st.markdown("""
320
- 1. Enter the stock or crypto symbol.
321
- 2. Choose the date range.
322
- 3. Set the buy and sell thresholds.
323
- 4. Click 'Fetch Data' to load the data.
324
- 5. The chart will display the RSI and highlight buy/sell signals.
325
- """)
326
- elif selected == "MACD":
327
- st.markdown("""
328
- 1. Enter the stock or crypto symbol.
329
- 2. Choose the date range.
330
- 3. Click 'Fetch Data' to load the data.
331
- 4. The chart will display the MACD, Signal line, and Histogram, and highlight buy/sell signals based on MACD crossovers.
332
- """)
333
- elif selected == "Bollinger Bands":
334
- st.markdown("""
335
- 1. Enter the stock or crypto symbol.
336
- 2. Choose the date range.
337
- 3. Click 'Fetch Data' to load the data.
338
- 4. The chart will display the Bollinger Bands and highlight buy/sell signals based on price crossing the bands.
339
- """)
340
- elif selected == "K Reversal":
341
- st.markdown("""
342
- 1. Enter the stock or crypto symbol.
343
- 2. Choose the date range.
344
- 3. Set the period for the K Reversal calculation.
345
- 4. Set the buy and sell thresholds.
346
- 5. Click 'Fetch Data' to load the data.
347
- 6. The chart will display the K Reversal indicator and highlight buy/sell signals.
348
- """)
349
- elif selected == "Awesome Oscillator":
350
- st.markdown("""
351
- 1. Enter the stock or crypto symbol.
352
- 2. Choose the date range.
353
- 3. Set the signal line period.
354
- 4. Set the buy and sell thresholds.
355
- 5. Click 'Fetch Data' to load the data.
356
- 6. The chart will display the Awesome Oscillator and highlight buy/sell signals.
357
- """)
358
- elif selected == "Williams %R":
359
- st.markdown("""
360
- 1. Enter the stock or crypto symbol.
361
- 2. Choose the date range.
362
- 3. Set the look-back period.
363
- 4. Set the buy and sell thresholds.
364
- 5. Click 'Fetch Data' to load the data.
365
- 6. The chart will display the Williams %R and highlight buy/sell signals.
366
- """)
367
- elif selected == "Aroon Oscillator":
368
- st.markdown("""
369
- 1. Enter the stock or crypto symbol.
370
- 2. Choose the date range.
371
- 3. Set the look-back period.
372
- 4. Click 'Fetch Data' to load the data.
373
- 5. The chart will display the Aroon Oscillator and highlight buy/sell signals based on thresholds.
374
- """)
375
-
376
  # Sidebar for input parameters inside an expander
377
  with st.sidebar.expander("Input Parameters", expanded=True):
378
  ticker = st.text_input('Enter Stock or Crypto Symbol (e.g., AAPL or BTC-USD)', 'AAPL')
 
1
  import pandas as pd
2
  import numpy as np
 
3
  import yfinance as yf
4
  import streamlit as st
5
  import plotly.graph_objects as go
 
10
 
11
  # Helper functions
12
  def fetch_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame:
 
13
  return yf.download(ticker, start=start_date, end=end_date)
14
 
15
  def plot_z_score(close_prices: pd.Series, periods: list, z_thresh: float, n_days: int) -> go.Figure:
16
  fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
17
  subplot_titles=('Close Prices', 'Rolling Z-Scores'))
18
 
 
19
  fig.add_trace(go.Scatter(x=close_prices.index, y=close_prices, mode='lines', name='Close Prices'), row=1, col=1)
20
 
21
  for period in periods:
 
43
  name=f'Sell Signal {period} days'), row=1, col=1)
44
  fig.add_trace(go.Scatter(x=close_prices.index, y=z_scores, mode='lines', name=f'Rolling Z-Score {period}'), row=2, col=1)
45
 
 
46
  fig.add_hline(y=z_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
47
  fig.add_hline(y=-z_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
48
 
 
54
  fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
55
  subplot_titles=('Stock Price', 'Rate of Change (ROC)'))
56
 
 
57
  fig.add_trace(go.Scatter(x=prices.index, y=prices, mode='lines', name='Stock Price'), row=1, col=1)
58
  fig.add_trace(go.Scatter(x=prices.index, y=roc, mode='lines', name='ROC'), row=2, col=1)
59
 
 
65
  fig.add_trace(go.Scatter(x=prices[sell_signals].index, y=prices[sell_signals], mode='markers',
66
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
67
 
 
68
  fig.add_hline(y=0, line=dict(color='gray', dash='dash'), row=2, col=1)
69
 
70
  fig.update_layout(title='Rate of Change (ROC) with Buy/Sell Signals', xaxis_title='Date', yaxis_title='Price', yaxis2_title='ROC')
 
91
  fig.add_trace(go.Scatter(x=data[sell_signals].index, y=data[sell_signals]['Close'], mode='markers',
92
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
93
 
 
94
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
95
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
96
 
 
113
  fig.add_trace(go.Scatter(x=prices[sell_signals].index, y=prices[sell_signals], mode='markers',
114
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
115
 
 
116
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
117
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
118
 
 
166
  return fig
167
 
168
  def plot_k_reversal(data: pd.DataFrame, n: int, buy_thresh: float, sell_thresh: float) -> go.Figure:
 
169
  high_n = data['High'].rolling(n).max()
170
  low_n = data['Low'].rolling(n).min()
171
  k_values = 100 * (data['Close'] - low_n) / (high_n - low_n)
 
184
  fig.add_trace(go.Scatter(x=data[sell_signals].index, y=data[sell_signals]['Close'], mode='markers',
185
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
186
 
 
187
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
188
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
189
 
 
191
  return fig
192
 
193
  def plot_awesome_oscillator(data: pd.DataFrame, signal_period: int, buy_thresh: float, sell_thresh: float) -> go.Figure:
 
194
  ao_indicator = AwesomeOscillatorIndicator(high=data['High'], low=data['Low'])
195
  data['AO'] = ao_indicator.awesome_oscillator()
196
  data['Signal'] = data['AO'].rolling(window=signal_period).mean()
 
210
  fig.add_trace(go.Scatter(x=data[sell_signals].index, y=data['Close'][sell_signals], mode='markers',
211
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
212
 
 
213
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
214
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
215
 
 
217
  return fig
218
 
219
  def plot_williams_r(data: pd.DataFrame, n: int, buy_thresh: float, sell_thresh: float) -> go.Figure:
 
220
  williams_r = WilliamsRIndicator(high=data['High'], low=data['Low'], close=data['Close'], lbp=n)
221
  data['Williams %R'] = williams_r.williams_r()
222
 
 
234
  fig.add_trace(go.Scatter(x=data[sell_signals].index, y=data[sell_signals]['Close'], mode='markers',
235
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
236
 
 
237
  fig.add_hline(y=buy_thresh, line=dict(color='green', dash='dash'), row=2, col=1)
238
  fig.add_hline(y=sell_thresh, line=dict(color='red', dash='dash'), row=2, col=1)
239
 
 
241
  return fig
242
 
243
  def plot_aroon(data: pd.DataFrame, aroon_osc: pd.Series, buy_signals: pd.Series, sell_signals: pd.Series) -> go.Figure:
 
244
  fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
245
  subplot_titles=('Close Price', 'Aroon Oscillator'))
246
 
 
252
  fig.add_trace(go.Scatter(x=sell_signals.index[sell_signals], y=data['Close'][sell_signals], mode='markers',
253
  marker=dict(color='red', symbol='triangle-down', size=10), name='Sell Signal'), row=1, col=1)
254
 
 
255
  fig.add_hline(y=0, line=dict(color='black', dash='dash'), row=2, col=1)
256
 
257
  fig.update_layout(title='Aroon Oscillator with Buy/Sell Signals', xaxis_title='Date', yaxis_title='Price', yaxis2_title='Aroon Oscillator')
258
  return fig
259
 
260
  def aroon_oscillator(data: pd.DataFrame, period: int) -> pd.Series:
 
261
  aroon_up = 100 * (data['High'].rolling(period + 1).apply(lambda x: np.argmax(x[::-1]), raw=True) / period)
262
  aroon_down = 100 * (data['Low'].rolling(period + 1).apply(lambda x: np.argmin(x[::-1]), raw=True) / period)
263
  aroon_osc = aroon_up - aroon_down
 
267
  st.set_page_config(page_title="Technical Analysis", layout="wide")
268
  st.title('Technical Analysis Indicators')
269
 
270
+ # Sidebar for "How to Use" instructions specific to the selected method (top of the sidebar)
271
+ with st.sidebar.expander("How to Use", expanded=False):
272
+ st.markdown("""
273
+ 1. Use the sidebar to select an indicator and input parameters.
274
+ 2. Enter the stock or cryptocurrency symbol (e.g., 'AAPL' for Apple or 'BTC-USD' for Bitcoin).
275
+ 3. Choose the date range for the data.
276
+ 4. Click 'Fetch Data' to load and visualize the data.
277
+ 5. Use the parameter settings for each method to fine-tune the analysis.
278
+ """)
279
+
280
  # Sidebar for method selection
281
  with st.sidebar.expander("Method Selection", expanded=True):
282
  selected = st.radio("Select Indicator", ["Rolling Z-Score", "Rate of Change (ROC)", "Stochastic Oscillator", "Relative Strength Index (RSI)", "MACD", "Bollinger Bands", "K Reversal", "Awesome Oscillator", "Williams %R", "Aroon Oscillator"])
283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  # Sidebar for input parameters inside an expander
285
  with st.sidebar.expander("Input Parameters", expanded=True):
286
  ticker = st.text_input('Enter Stock or Crypto Symbol (e.g., AAPL or BTC-USD)', 'AAPL')