Spaces:
Sleeping

QuantumLearner commited on
Commit
a5fac15
·
verified ·
1 Parent(s): 06b7be1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -63
app.py CHANGED
@@ -8,7 +8,10 @@ from plotly.subplots import make_subplots
8
  # Helper function to fetch stock or crypto data
9
  def fetch_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame:
10
  """Fetch stock or crypto data from Yahoo Finance."""
11
- return yf.download(ticker, start=start_date, end=end_date)
 
 
 
12
 
13
  # True Range Volatility Ratio
14
  def calculate_volatility_ratio(data: pd.DataFrame, n: int = 14, ratio: float = 1.75) -> go.Figure:
@@ -38,7 +41,9 @@ def calculate_volume_ratio(data: pd.DataFrame, percentile_threshold: float = 0.9
38
  data['50_day_MA'] = data['Close'].rolling(window=50).mean()
39
  data['200_day_MA'] = data['Close'].rolling(window=200).mean()
40
  data['Volume_MA20'] = data['Volume'].rolling(window=20).mean()
41
- data['Volume_Ratio'] = data['Volume'] / data['Volume_MA20']
 
 
42
 
43
  dynamic_percentile = data['Volume_Ratio'].quantile(percentile_threshold)
44
  mask = data['Volume_Ratio'] > dynamic_percentile
@@ -73,7 +78,6 @@ st.title('Unusual Volatility and Volume')
73
  st.sidebar.title('Input Parameters')
74
 
75
  with st.sidebar.expander("Select Analysis", expanded=True):
76
- # Sidebar for method selection
77
  selected = st.radio("Select Analysis", ["Volatility Ratio", "Volume Ratio"])
78
 
79
  # Sidebar for "How to Use" instructions specific to the selected method
@@ -107,8 +111,12 @@ with st.sidebar.expander("Input Parameters", expanded=True):
107
  fetch_data = st.button('Fetch Data') # Capture the button state
108
 
109
  # Fetch data
110
- if 'data' not in st.session_state or fetch_data: # Use the fetch_data variable here
111
- st.session_state.data = fetch_stock_data(ticker, start_date, end_date)
 
 
 
 
112
 
113
  # Parameters for each method inside an expander
114
  with st.sidebar.expander(f"Parameters for {selected}", expanded=True):
@@ -118,65 +126,66 @@ with st.sidebar.expander(f"Parameters for {selected}", expanded=True):
118
  elif selected == "Volume Ratio":
119
  percentile_threshold = st.slider('Percentile Threshold', min_value=0.5, max_value=1.0, value=0.97, step=0.01, help="Set the percentile threshold for identifying high volume periods.")
120
 
121
- data = st.session_state.data
 
122
 
123
- # Display results based on the selected method
124
- if selected == "Volatility Ratio":
125
- st.markdown("### Volatility Ratio")
126
-
127
- st.markdown("This method calculates the True Range Volatility Ratio, which helps identify periods of high volatility. A ratio above a specified threshold indicates high volatility.")
128
-
129
- with st.expander("How it Works", expanded=False):
130
- st.markdown("""
131
- **How Volatility Ratio Works:**
132
- 1. **Calculate True Range:**
133
- - True Range is the maximum of the following:
134
- """)
135
- st.latex(r'''
136
- \text{True Range} = \max(\text{High} - \text{Low}, \left| \text{High} - \text{Previous Close} \right|, \left| \text{Low} - \text{Previous Close} \right|)
137
- ''')
138
- st.markdown("""
139
- 2. **Compute Exponential Moving Average (EMA) of True Range:**
140
- - Calculate the EMA of the True Range over a specified period (e.g., 14 days).
141
- 3. **Calculate Volatility Ratio:**
142
- - Use the formula:
143
- """)
144
- st.latex(r'''
145
- \text{Volatility Ratio} = \frac{\text{True Range}}{\text{EMA of True Range}}
146
- ''')
147
- st.markdown("""
148
- 4. **Identify Signals:**
149
- - **High Volatility:** Occurs when the Volatility Ratio exceeds a specified threshold (e.g., 1.75).
150
- """)
151
-
152
- fig = calculate_volatility_ratio(data, n, ratio)
153
- st.plotly_chart(fig)
154
-
155
- elif selected == "Volume Ratio":
156
- st.markdown("### Volume Ratio with Dynamic Percentile")
157
-
158
- st.markdown("This method calculates the Volume Ratio and uses a dynamic percentile threshold to identify high volume periods. A volume ratio above the specified percentile indicates high trading activity.")
159
-
160
- with st.expander("How it Works", expanded=False):
161
- st.markdown("""
162
- **How Volume Ratio Works:**
163
- 1. **Calculate Volume Moving Average:**
164
- - Compute the 20-day moving average of the volume.
165
- 2. **Calculate Volume Ratio:**
166
- - Use the formula:
167
- """)
168
- st.latex(r'''
169
- \text{Volume Ratio} = \frac{\text{Volume}}{\text{20-day Moving Average of Volume}}
170
- ''')
171
- st.markdown("""
172
- 3. **Determine Dynamic Percentile Threshold:**
173
- - Calculate the specified percentile of the Volume Ratio distribution.
174
- 4. **Identify Signals:**
175
- - **High Volume:** Occurs when the Volume Ratio exceeds the dynamic percentile threshold.
176
- """)
177
 
178
- fig = calculate_volume_ratio(data, percentile_threshold)
179
- st.plotly_chart(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
  # Hide the default Streamlit menu and footer
182
  hide_streamlit_style = """
@@ -185,4 +194,4 @@ hide_streamlit_style = """
185
  footer {visibility: hidden;}
186
  </style>
187
  """
188
- st.markdown(hide_streamlit_style, unsafe_allow_html=True)
 
8
  # Helper function to fetch stock or crypto data
9
  def fetch_stock_data(ticker: str, start_date: str, end_date: str) -> pd.DataFrame:
10
  """Fetch stock or crypto data from Yahoo Finance."""
11
+ data = yf.download(ticker, start=start_date, end=end_date, auto_adjust=False)
12
+ if isinstance(data.columns, pd.MultiIndex):
13
+ data.columns = data.columns.get_level_values(0)
14
+ return data
15
 
16
  # True Range Volatility Ratio
17
  def calculate_volatility_ratio(data: pd.DataFrame, n: int = 14, ratio: float = 1.75) -> go.Figure:
 
41
  data['50_day_MA'] = data['Close'].rolling(window=50).mean()
42
  data['200_day_MA'] = data['Close'].rolling(window=200).mean()
43
  data['Volume_MA20'] = data['Volume'].rolling(window=20).mean()
44
+ # Ensure Volume_Ratio is a single-column Series with proper index alignment
45
+ volume_ratio = (data['Volume'] / data['Volume_MA20']).reindex(data.index, method='ffill')
46
+ data['Volume_Ratio'] = pd.Series(volume_ratio, index=data.index)
47
 
48
  dynamic_percentile = data['Volume_Ratio'].quantile(percentile_threshold)
49
  mask = data['Volume_Ratio'] > dynamic_percentile
 
78
  st.sidebar.title('Input Parameters')
79
 
80
  with st.sidebar.expander("Select Analysis", expanded=True):
 
81
  selected = st.radio("Select Analysis", ["Volatility Ratio", "Volume Ratio"])
82
 
83
  # Sidebar for "How to Use" instructions specific to the selected method
 
111
  fetch_data = st.button('Fetch Data') # Capture the button state
112
 
113
  # Fetch data
114
+ if 'data' not in st.session_state or fetch_data:
115
+ data = fetch_stock_data(ticker, start_date, end_date)
116
+ if data.empty:
117
+ st.error(f"No data returned for {ticker} from {start_date} to {end_date}")
118
+ else:
119
+ st.session_state.data = data
120
 
121
  # Parameters for each method inside an expander
122
  with st.sidebar.expander(f"Parameters for {selected}", expanded=True):
 
126
  elif selected == "Volume Ratio":
127
  percentile_threshold = st.slider('Percentile Threshold', min_value=0.5, max_value=1.0, value=0.97, step=0.01, help="Set the percentile threshold for identifying high volume periods.")
128
 
129
+ if 'data' in st.session_state and not st.session_state.data.empty:
130
+ data = st.session_state.data
131
 
132
+ # Display results based on the selected method
133
+ if selected == "Volatility Ratio":
134
+ st.markdown("### Volatility Ratio")
135
+
136
+ st.markdown("This method calculates the True Range Volatility Ratio, which helps identify periods of high volatility. A ratio above a specified threshold indicates high volatility.")
137
+
138
+ with st.expander("How it Works", expanded=False):
139
+ st.markdown("""
140
+ **How Volatility Ratio Works:**
141
+ 1. **Calculate True Range:**
142
+ - True Range is the maximum of the following:
143
+ """)
144
+ st.latex(r'''
145
+ \text{True Range} = \max(\text{High} - \text{Low}, \left| \text{High} - \text{Previous Close} \right|, \left| \text{Low} - \text{Previous Close} \right|)
146
+ ''')
147
+ st.markdown("""
148
+ 2. **Compute Exponential Moving Average (EMA) of True Range:**
149
+ - Calculate the EMA of the True Range over a specified period (e.g., 14 days).
150
+ 3. **Calculate Volatility Ratio:**
151
+ - Use the formula:
152
+ """)
153
+ st.latex(r'''
154
+ \text{Volatility Ratio} = \frac{\text{True Range}}{\text{EMA of True Range}}
155
+ ''')
156
+ st.markdown("""
157
+ 4. **Identify Signals:**
158
+ - **High Volatility:** Occurs when the Volatility Ratio exceeds a specified threshold (e.g., 1.75).
159
+ """)
160
+
161
+ fig = calculate_volatility_ratio(data, n, ratio)
162
+ st.plotly_chart(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
+ elif selected == "Volume Ratio":
165
+ st.markdown("### Volume Ratio with Dynamic Percentile")
166
+
167
+ st.markdown("This method calculates the Volume Ratio and uses a dynamic percentile threshold to identify high volume periods. A volume ratio above the specified percentile indicates high trading activity.")
168
+
169
+ with st.expander("How it Works", expanded=False):
170
+ st.markdown("""
171
+ **How Volume Ratio Works:**
172
+ 1. **Calculate Volume Moving Average:**
173
+ - Compute the 20-day moving average of the volume.
174
+ 2. **Calculate Volume Ratio:**
175
+ - Use the formula:
176
+ """)
177
+ st.latex(r'''
178
+ \text{Volume Ratio} = \frac{\text{Volume}}{\text{20-day Moving Average of Volume}}
179
+ ''')
180
+ st.markdown("""
181
+ 3. **Determine Dynamic Percentile Threshold:**
182
+ - Calculate the specified percentile of the Volume Ratio distribution.
183
+ 4. **Identify Signals:**
184
+ - **High Volume:** Occurs when the Volume Ratio exceeds the dynamic percentile threshold.
185
+ """)
186
+
187
+ fig = calculate_volume_ratio(data, percentile_threshold)
188
+ st.plotly_chart(fig)
189
 
190
  # Hide the default Streamlit menu and footer
191
  hide_streamlit_style = """
 
194
  footer {visibility: hidden;}
195
  </style>
196
  """
197
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)