QuantumLearner commited on
Commit
7bb1003
·
verified ·
1 Parent(s): 9654b93

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +330 -0
app.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import numpy as np
5
+ from plotly.subplots import make_subplots
6
+ import plotly.graph_objects as go
7
+
8
+ # Set Streamlit page configuration (wide layout)
9
+ st.set_page_config(
10
+ page_title="High Frequency Price Reversals",
11
+ layout="wide"
12
+ )
13
+
14
+ # App title
15
+ st.title("Price Reversals")
16
+
17
+ # Detailed purpose description
18
+ st.write("This tool identifies and analyzes **high-frequency price reversals** for a given ticker or crypto pair. It calculates the number of reversals per day, their magnitude, and the time between each reversal. The analysis runs across three live intraday intervals: 60-minute, 5-minute, and 1-minute bars. Reversals help distinguish routine market noise from shifts driven by news or fundamental changes.")
19
+
20
+ # Brief purpose description
21
+ with st.expander("Methodology", expanded=False):
22
+ st.markdown(r"""
23
+ ##### What is a Price Reversal?
24
+
25
+ A **price reversal** is defined as a change in direction between consecutive candles.
26
+ For example, if a bullish candle (Close > Open) is followed by a bearish candle (Close < Open), that marks a reversal. The reverse scenario is treated the same way.
27
+
28
+ ##### Reversal Detection Logic
29
+
30
+ 1. Label each candle as bullish or bearish:
31
+ $$
32
+ \text{IsBull} = \text{Close} > \text{Open}
33
+ $$
34
+
35
+ 2. A reversal occurs when the current candle has a different direction than the previous one:
36
+ $$
37
+ \text{Reversal} = \text{IsBull}_t \neq \text{IsBull}_{t-1}
38
+ $$
39
+
40
+ ##### Daily Reversal Counts
41
+
42
+ For each date:
43
+ - Count the number of reversals.
44
+ - Count the number of non-reversals.
45
+ - Calculate the daily reversal percentage:
46
+ $$
47
+ \text{ReversalPct} = \frac{\text{ReversalCount}}{\text{ReversalCount} + \text{NonReversalCount}}
48
+ $$
49
+
50
+ ##### Reversal Magnitude
51
+
52
+ For each reversal, we measure how much the price changed during that candle. In other words, we calculate the absolute difference between the closing and opening prices:
53
+ $$
54
+ \text{ReversalMagnitude} = |\text{Close} - \text{Open}|
55
+ $$
56
+
57
+ Each day, we summarize these values by computing the smallest, median, and largest price changes. This helps us see the typical size of a reversal.
58
+
59
+ ##### Time Between Reversals
60
+
61
+ We also measure the duration (in minutes) between one reversal and the next. For every day, we calculate the shortest, median, and longest time gaps between reversals. This measure how long the market goes without a reversal.
62
+ """, unsafe_allow_html=True)
63
+
64
+ # Sidebar user inputs
65
+ st.sidebar.header("User Inputs")
66
+ ticker_input = st.sidebar.text_input(
67
+ label="Ticker",
68
+ value="CVNA",
69
+ help="Enter a valid ticker symbol or cryptopair (e.g. 'CVNA', 'BTC-USD', etc.)"
70
+ )
71
+ run_button = st.sidebar.button(
72
+ label="Run Analysis",
73
+ help="Click to generate plots for the selected ticker."
74
+ )
75
+
76
+ # Execute only when "Run Analysis" is clicked
77
+ if run_button:
78
+ if not ticker_input.strip():
79
+ st.error("Please enter a valid ticker.")
80
+ else:
81
+ with st.spinner("Running analysis..."):
82
+ try:
83
+ # Define ticker and interval settings
84
+ ticker = ticker_input.strip().upper()
85
+ period_mapping = {
86
+ "60m": "720d",
87
+ "5m": "60d",
88
+ "1m": "8d"
89
+ }
90
+ intervals = ["60m", "5m", "1m"]
91
+
92
+ # Loop over each interval
93
+ for freq in intervals:
94
+ st.markdown(f"## {freq} Interval Analysis - {ticker}")
95
+ if freq == "60m":
96
+ st.write("Analysis using 60-minute data. This interval provides a broader view of market trends.")
97
+ elif freq == "5m":
98
+ st.write("Analysis using 5-minute data. This interval provides a balance between overall trends and finer details.")
99
+ elif freq == "1m":
100
+ st.write("Analysis using 1-minute data. This interval reveals fine details in price reversals.")
101
+
102
+ period = period_mapping[freq]
103
+ df = yf.download(ticker, period=period, interval=freq)
104
+
105
+ # Flatten multi-level columns if needed
106
+ if isinstance(df.columns, pd.MultiIndex):
107
+ df.columns = df.columns.get_level_values(0)
108
+
109
+ df.dropna(inplace=True)
110
+ df.index.name = None
111
+
112
+ # Compute reversal indicator
113
+ df['IsBull'] = df['Close'] > df['Open']
114
+ df['Reversal'] = df['IsBull'] != df['IsBull'].shift(1)
115
+ df['Reversal'] = df['Reversal'].fillna(False)
116
+
117
+ # Prepare daily counts
118
+ df['Date'] = df.index.date
119
+ daily_counts = df.groupby('Date')['Reversal'].agg(
120
+ ReversalCount=lambda x: x.astype(int).sum(),
121
+ NonReversalCount=lambda x: (~x).astype(int).sum()
122
+ )
123
+ daily_counts['ReversalPct'] = daily_counts['ReversalCount'] / (
124
+ daily_counts['ReversalCount'] + daily_counts['NonReversalCount']
125
+ )
126
+ dates = pd.to_datetime(daily_counts.index)
127
+
128
+ # Reversal magnitude analysis
129
+ df['ReversalMagnitude'] = np.abs(df['Close'] - df['Open'])
130
+ rev_mags = df[df['Reversal']].copy()
131
+ rev_mags['Date'] = rev_mags.index.date
132
+ mag_stats = rev_mags.groupby('Date')['ReversalMagnitude'].agg(['min', 'median', 'max'])
133
+
134
+ # Time between reversals analysis
135
+ reversal_times = df.index[df['Reversal']].to_series()
136
+ reversal_time_diffs = reversal_times.diff().dropna().dt.total_seconds() / 60
137
+ reversal_time_df = pd.DataFrame({
138
+ 'TimeBetween': reversal_time_diffs,
139
+ 'Date': reversal_times.iloc[1:].dt.date
140
+ })
141
+ time_stats = reversal_time_df.groupby('Date')['TimeBetween'].agg(['min', 'median', 'max'])
142
+
143
+ # Create a figure with 4 rows (subplots)
144
+ fig = make_subplots(
145
+ rows=4, cols=1,
146
+ shared_xaxes=True,
147
+ subplot_titles=(
148
+ f"{ticker} Close Price with Reversal Points",
149
+ "Daily Reversal Counts & Reversal %",
150
+ "Daily Reversal Magnitude Summary",
151
+ "Daily Time Between Reversals (Minutes)"
152
+ ),
153
+ specs=[
154
+ [{}],
155
+ [{"secondary_y": True}],
156
+ [{}],
157
+ [{}]
158
+ ]
159
+ )
160
+
161
+ # Subplot 1: Price with reversal markers
162
+ fig.add_trace(
163
+ go.Scatter(
164
+ x=df.index,
165
+ y=df['Close'],
166
+ mode='lines',
167
+ name='Close Price',
168
+ line=dict(color='blue')
169
+ ),
170
+ row=1, col=1
171
+ )
172
+ reversal_points = df[df['Reversal']]
173
+ fig.add_trace(
174
+ go.Scatter(
175
+ x=reversal_points.index,
176
+ y=reversal_points['Close'],
177
+ mode='markers',
178
+ name='Reversal',
179
+ marker=dict(color='red', size=6, opacity=0.5)
180
+ ),
181
+ row=1, col=1
182
+ )
183
+ non_reversal_points = df[~df['Reversal']]
184
+ fig.add_trace(
185
+ go.Scatter(
186
+ x=non_reversal_points.index,
187
+ y=non_reversal_points['Close'],
188
+ mode='markers',
189
+ name='Not Reversal',
190
+ marker=dict(color='green', size=4, opacity=0.5)
191
+ ),
192
+ row=1, col=1
193
+ )
194
+
195
+ # Subplot 2: Daily reversal counts (stacked bar) and reversal percentage line
196
+ fig.add_trace(
197
+ go.Bar(
198
+ x=dates,
199
+ y=daily_counts['ReversalCount'],
200
+ name='Reversal',
201
+ marker_color='red'
202
+ ),
203
+ row=2, col=1, secondary_y=False
204
+ )
205
+ fig.add_trace(
206
+ go.Bar(
207
+ x=dates,
208
+ y=daily_counts['NonReversalCount'],
209
+ name='Not Reversal',
210
+ marker_color='green',
211
+ opacity=0.6
212
+ ),
213
+ row=2, col=1, secondary_y=False
214
+ )
215
+ fig.add_trace(
216
+ go.Scatter(
217
+ x=dates,
218
+ y=daily_counts['ReversalPct'],
219
+ mode='lines',
220
+ name='Reversal %',
221
+ line=dict(color='white')
222
+ ),
223
+ row=2, col=1, secondary_y=True
224
+ )
225
+
226
+ # Subplot 3: Reversal magnitude stats
227
+ fig.add_trace(
228
+ go.Scatter(
229
+ x=mag_stats.index,
230
+ y=mag_stats['median'],
231
+ mode='lines',
232
+ name='Median',
233
+ line=dict(color='orange')
234
+ ),
235
+ row=3, col=1
236
+ )
237
+ fig.add_trace(
238
+ go.Scatter(
239
+ x=mag_stats.index,
240
+ y=mag_stats['min'],
241
+ mode='lines',
242
+ name='Min',
243
+ line=dict(dash='dash', color='gray')
244
+ ),
245
+ row=3, col=1
246
+ )
247
+ fig.add_trace(
248
+ go.Scatter(
249
+ x=mag_stats.index,
250
+ y=mag_stats['max'],
251
+ mode='lines',
252
+ name='Max',
253
+ line=dict(dash='dash', color='white')
254
+ ),
255
+ row=3, col=1
256
+ )
257
+
258
+ # Subplot 4: Time between reversals stats
259
+ fig.add_trace(
260
+ go.Scatter(
261
+ x=time_stats.index,
262
+ y=time_stats['median'],
263
+ mode='lines',
264
+ name='Median',
265
+ line=dict(color='purple')
266
+ ),
267
+ row=4, col=1
268
+ )
269
+ fig.add_trace(
270
+ go.Scatter(
271
+ x=time_stats.index,
272
+ y=time_stats['min'],
273
+ mode='lines',
274
+ name='Min',
275
+ line=dict(dash='dash', color='gray')
276
+ ),
277
+ row=4, col=1
278
+ )
279
+ fig.add_trace(
280
+ go.Scatter(
281
+ x=time_stats.index,
282
+ y=time_stats['max'],
283
+ mode='lines',
284
+ name='Max',
285
+ line=dict(dash='dash', color='white')
286
+ ),
287
+ row=4, col=1
288
+ )
289
+
290
+ # Update layout with dark theme, white titles, and gridlines with alpha 0.2
291
+ fig.update_layout(
292
+ height=1800,
293
+ width=1700,
294
+ title_text=f"{ticker} Analysis ({freq} Data)",
295
+ title_font_color='white',
296
+ barmode='stack',
297
+ template='plotly_dark',
298
+ paper_bgcolor='#0e1117',
299
+ plot_bgcolor='#0e1117',
300
+ legend=dict(font=dict(color='white'))
301
+ )
302
+
303
+ # Update all axes to set white titles and gridlines with alpha 0.2
304
+ fig.update_xaxes(
305
+ title_font_color='white',
306
+ gridcolor='rgba(255, 255, 255, 0.2)'
307
+ )
308
+ fig.update_yaxes(
309
+ title_font_color='white',
310
+ gridcolor='rgba(255, 255, 255, 0.2)'
311
+ )
312
+
313
+ fig.for_each_annotation(lambda a: a.update(font=dict(color='white')))
314
+
315
+ # Display the figure in Streamlit
316
+ st.plotly_chart(fig, use_container_width=True)
317
+
318
+ except Exception:
319
+ st.error("An error occurred. Please check your input and try again.")
320
+
321
+ # Hide default Streamlit style
322
+ st.markdown(
323
+ """
324
+ <style>
325
+ #MainMenu {visibility: hidden;}
326
+ footer {visibility: hidden;}
327
+ </style>
328
+ """,
329
+ unsafe_allow_html=True
330
+ )