QuantumLearner commited on
Commit
def0095
·
verified ·
1 Parent(s): bb690e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -66
app.py CHANGED
@@ -98,71 +98,80 @@ def interpret_rolling_window(window):
98
  return "A moderate rolling window balances recent trends with some degree of smoothing."
99
 
100
  if st.sidebar.button("Run Analysis"):
101
- df = yf.download(symbol, start=start_date, end=end_date)
102
-
103
- df['hurst_exponent'] = rolling_hurst(df['Close'], rolling_window)
104
- df.dropna(inplace=True)
105
-
106
- df['sma'] = df['Close'].rolling(window=sma_window).mean()
107
-
108
- hurst_95 = df['hurst_exponent'].quantile(quantile_high)
109
- hurst_05 = df['hurst_exponent'].quantile(quantile_low)
110
- current_hurst = df['hurst_exponent'].iloc[-1]
111
-
112
- significant_dates_95 = df[df['hurst_exponent'] >= hurst_95].index
113
- significant_dates_05 = df[df['hurst_exponent'] <= hurst_05].index
114
-
115
- fig = make_subplots(rows=3, cols=1, shared_xaxes=True,
116
- subplot_titles=(f"{symbol} Price and SMA", "Rolling Hurst Exponent", "Hurst Exponent Histogram"))
117
-
118
- # Plot price and SMA
119
- fig.add_trace(go.Scatter(x=df.index, y=df['Close'], name=f'{symbol} Price', line=dict(color='blue')), row=1, col=1)
120
- fig.add_trace(go.Scatter(x=df.index, y=df['sma'], name=f'{sma_window}-day SMA', line=dict(color='purple')), row=1, col=1)
121
-
122
- # Add shaded areas for significant dates
123
- for date in significant_dates_95:
124
- fig.add_vrect(
125
- x0=date,
126
- x1=date + pd.Timedelta(days=1), # Assuming you're shading a single day
127
- fillcolor="red",
128
- opacity=0.7, # Adjust the opacity here
129
- layer="below",
130
- line_width=0
131
- )
132
-
133
- for date in significant_dates_05:
134
- fig.add_vrect(
135
- x0=date,
136
- x1=date + pd.Timedelta(days=1),
137
- fillcolor="blue",
138
- opacity=0.7, # Adjust the opacity here
139
- layer="below",
140
- line_width=0
141
- )
142
-
143
- # Plot Hurst Exponent
144
- fig.add_trace(go.Scatter(x=df.index, y=df['hurst_exponent'], name='Rolling Hurst Exponent', line=dict(color='white', width=5)), row=2, col=1)
145
- fig.add_hline(y=hurst_95, line=dict(color='red', dash='dash', width=1), annotation_text=f'95th Percentile: {hurst_95:.2f}', row=2, col=1)
146
- fig.add_hline(y=hurst_05, line=dict(color='blue', dash='dash', width=1), annotation_text=f'5th Percentile: {hurst_05:.2f}', row=2, col=1)
147
- fig.add_hline(y=current_hurst, line=dict(color='orange', width=1), annotation_text=f'Current Hurst: {current_hurst:.2f}', row=2, col=1)
148
-
149
- # Hurst interpretation ranges
150
- fig.add_hline(y=0.5, line=dict(color='black', width=1), annotation_text='0.5: Random Walk', row=2, col=1)
151
- fig.add_trace(go.Scatter(x=df.index, y=[0.5] * len(df.index), name='0.5: Random Walk', mode='lines', line=dict(color='black', width=3)), row=2, col=1)
152
- fig.add_trace(go.Scatter(x=df.index, y=[0.0] * len(df.index), name='<0.5: Mean Reverting', fill='tonexty', mode='lines', line=dict(color='blue', width=0), opacity=0.01), row=2, col=1)
153
- fig.add_trace(go.Scatter(x=df.index, y=[1.0] * len(df.index), name='>0.5: Persistent Trend', fill='tonexty', mode='lines', line=dict(color='red', width=0), opacity=0.01), row=2, col=1)
154
-
155
- # Plot histogram of Hurst Exponent
156
- fig.add_trace(go.Histogram(x=df['hurst_exponent'], nbinsx=30, marker=dict(color='grey', line=dict(color='black', width=1)), name='Hurst Exponent Histogram'), row=3, col=1)
157
- fig.add_vline(x=current_hurst, line=dict(color='orange', width=1), annotation_text=f'Current Hurst: {current_hurst:.2f}', row=3, col=1)
158
-
159
- fig.update_layout(height=900, width=1200, title_text=f"Hurst Exponent Analysis for {symbol}")
160
- st.plotly_chart(fig)
161
-
162
- hurst_interpretation = interpret_hurst(current_hurst)
163
- window_interpretation = interpret_rolling_window(rolling_window)
164
- st.markdown(f"**Rolling window interpretation:** {window_interpretation}")
165
- st.markdown(f"**Hurst exponent interpretation:** {hurst_interpretation}")
 
 
 
 
 
 
 
 
 
166
 
167
  hide_streamlit_style = """
168
  <style>
@@ -170,4 +179,4 @@ hide_streamlit_style = """
170
  footer {visibility: hidden;}
171
  </style>
172
  """
173
- st.markdown(hide_streamlit_style, unsafe_allow_html=True)
 
98
  return "A moderate rolling window balances recent trends with some degree of smoothing."
99
 
100
  if st.sidebar.button("Run Analysis"):
101
+ try:
102
+ df = yf.download(symbol, start=start_date, end=end_date, auto_adjust=False)
103
+ if isinstance(df.columns, pd.MultiIndex): # Flatten multi-index
104
+ df.columns = df.columns.get_level_values(0)
105
+ if df.empty:
106
+ raise ValueError(f"No data found for {symbol} from {start_date} to {end_date}")
107
+ if len(df) < rolling_window:
108
+ raise ValueError(f"Insufficient data points for {symbol}. Need at least {rolling_window} points.")
109
+
110
+ df['hurst_exponent'] = rolling_hurst(df['Close'], rolling_window)
111
+ df.dropna(inplace=True)
112
+
113
+ df['sma'] = df['Close'].rolling(window=sma_window).mean()
114
+
115
+ hurst_95 = df['hurst_exponent'].quantile(quantile_high)
116
+ hurst_05 = df['hurst_exponent'].quantile(quantile_low)
117
+ current_hurst = df['hurst_exponent'].iloc[-1]
118
+
119
+ significant_dates_95 = df[df['hurst_exponent'] >= hurst_95].index
120
+ significant_dates_05 = df[df['hurst_exponent'] <= hurst_05].index
121
+
122
+ fig = make_subplots(rows=3, cols=1, shared_xaxes=True,
123
+ subplot_titles=(f"{symbol} Price and SMA", "Rolling Hurst Exponent", "Hurst Exponent Histogram"))
124
+
125
+ # Plot price and SMA
126
+ fig.add_trace(go.Scatter(x=df.index, y=df['Close'], name=f'{symbol} Price', line=dict(color='blue')), row=1, col=1)
127
+ fig.add_trace(go.Scatter(x=df.index, y=df['sma'], name=f'{sma_window}-day SMA', line=dict(color='purple')), row=1, col=1)
128
+
129
+ # Add shaded areas for significant dates
130
+ for date in significant_dates_95:
131
+ fig.add_vrect(
132
+ x0=date,
133
+ x1=date + pd.Timedelta(days=1),
134
+ fillcolor="red",
135
+ opacity=0.7,
136
+ layer="below",
137
+ line_width=0
138
+ )
139
+
140
+ for date in significant_dates_05:
141
+ fig.add_vrect(
142
+ x0=date,
143
+ x1=date + pd.Timedelta(days=1),
144
+ fillcolor="blue",
145
+ opacity=0.7,
146
+ layer="below",
147
+ line_width=0
148
+ )
149
+
150
+ # Plot Hurst Exponent
151
+ fig.add_trace(go.Scatter(x=df.index, y=df['hurst_exponent'], name='Rolling Hurst Exponent', line=dict(color='white', width=5)), row=2, col=1)
152
+ fig.add_hline(y=hurst_95, line=dict(color='red', dash='dash', width=1), annotation_text=f'95th Percentile: {hurst_95:.2f}', row=2, col=1)
153
+ fig.add_hline(y=hurst_05, line=dict(color='blue', dash='dash', width=1), annotation_text=f'5th Percentile: {hurst_05:.2f}', row=2, col=1)
154
+ fig.add_hline(y=current_hurst, line=dict(color='orange', width=1), annotation_text=f'Current Hurst: {current_hurst:.2f}', row=2, col=1)
155
+
156
+ # Hurst interpretation ranges
157
+ fig.add_hline(y=0.5, line=dict(color='black', width=1), annotation_text='0.5: Random Walk', row=2, col=1)
158
+ fig.add_trace(go.Scatter(x=df.index, y=[0.5] * len(df.index), name='0.5: Random Walk', mode='lines', line=dict(color='black', width=3)), row=2, col=1)
159
+ fig.add_trace(go.Scatter(x=df.index, y=[0.0] * len(df.index), name='<0.5: Mean Reverting', fill='tonexty', mode='lines', line=dict(color='blue', width=0), opacity=0.01), row=2, col=1)
160
+ fig.add_trace(go.Scatter(x=df.index, y=[1.0] * len(df.index), name='>0.5: Persistent Trend', fill='tonexty', mode='lines', line=dict(color='red', width=0), opacity=0.01), row=2, col=1)
161
+
162
+ # Plot histogram of Hurst Exponent
163
+ fig.add_trace(go.Histogram(x=df['hurst_exponent'], nbinsx=30, marker=dict(color='grey', line=dict(color='black', width=1)), name='Hurst Exponent Histogram'), row=3, col=1)
164
+ fig.add_vline(x=current_hurst, line=dict(color='orange', width=1), annotation_text=f'Current Hurst: {current_hurst:.2f}', row=3, col=1)
165
+
166
+ fig.update_layout(height=900, width=1200, title_text=f"Hurst Exponent Analysis for {symbol}")
167
+ st.plotly_chart(fig)
168
+
169
+ hurst_interpretation = interpret_hurst(current_hurst)
170
+ window_interpretation = interpret_rolling_window(rolling_window)
171
+ st.markdown(f"**Rolling window interpretation:** {window_interpretation}")
172
+ st.markdown(f"**Hurst exponent interpretation:** {hurst_interpretation}")
173
+ except Exception as e:
174
+ st.error(f"Error: {str(e)}. Check ticker symbol, date range, or window size.")
175
 
176
  hide_streamlit_style = """
177
  <style>
 
179
  footer {visibility: hidden;}
180
  </style>
181
  """
182
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)