File size: 13,656 Bytes
7bb1003
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import streamlit as st
import yfinance as yf
import pandas as pd
import numpy as np
from plotly.subplots import make_subplots
import plotly.graph_objects as go

# Set Streamlit page configuration (wide layout)
st.set_page_config(
    page_title="High Frequency Price Reversals",
    layout="wide"
)

# App title
st.title("Price Reversals")

# Detailed purpose description
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.")

# Brief purpose description
with st.expander("Methodology",  expanded=False):
    st.markdown(r"""
##### What is a Price Reversal?

A **price reversal** is defined as a change in direction between consecutive candles.  
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.

##### Reversal Detection Logic

1. Label each candle as bullish or bearish:
$$
\text{IsBull} = \text{Close} > \text{Open}
$$

2. A reversal occurs when the current candle has a different direction than the previous one:
$$
\text{Reversal} = \text{IsBull}_t \neq \text{IsBull}_{t-1}
$$

##### Daily Reversal Counts

For each date:
- Count the number of reversals.
- Count the number of non-reversals.
- Calculate the daily reversal percentage:
$$
\text{ReversalPct} = \frac{\text{ReversalCount}}{\text{ReversalCount} + \text{NonReversalCount}}
$$

##### Reversal Magnitude

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:
$$
\text{ReversalMagnitude} = |\text{Close} - \text{Open}|
$$

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.

##### Time Between Reversals

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.
""", unsafe_allow_html=True)

# Sidebar user inputs
st.sidebar.header("User Inputs")
ticker_input = st.sidebar.text_input(
    label="Ticker",
    value="CVNA",
    help="Enter a valid ticker symbol or cryptopair (e.g. 'CVNA', 'BTC-USD', etc.)"
)
run_button = st.sidebar.button(
    label="Run Analysis",
    help="Click to generate plots for the selected ticker."
)

# Execute only when "Run Analysis" is clicked
if run_button:
    if not ticker_input.strip():
        st.error("Please enter a valid ticker.")
    else:
        with st.spinner("Running analysis..."):
            try:
                # Define ticker and interval settings
                ticker = ticker_input.strip().upper()
                period_mapping = {
                    "60m": "720d",
                    "5m": "60d",
                    "1m": "8d"
                }
                intervals = ["60m", "5m", "1m"]

                # Loop over each interval
                for freq in intervals:
                    st.markdown(f"## {freq} Interval Analysis - {ticker}")
                    if freq == "60m":
                        st.write("Analysis using 60-minute data. This interval provides a broader view of market trends.")
                    elif freq == "5m":
                        st.write("Analysis using 5-minute data. This interval provides a balance between overall trends and finer details.")
                    elif freq == "1m":
                        st.write("Analysis using 1-minute data. This interval reveals fine details in price reversals.")
                
                    period = period_mapping[freq]
                    df = yf.download(ticker, period=period, interval=freq)

                    # Flatten multi-level columns if needed
                    if isinstance(df.columns, pd.MultiIndex):
                        df.columns = df.columns.get_level_values(0)

                    df.dropna(inplace=True)
                    df.index.name = None

                    # Compute reversal indicator
                    df['IsBull'] = df['Close'] > df['Open']
                    df['Reversal'] = df['IsBull'] != df['IsBull'].shift(1)
                    df['Reversal'] = df['Reversal'].fillna(False)

                    # Prepare daily counts
                    df['Date'] = df.index.date
                    daily_counts = df.groupby('Date')['Reversal'].agg(
                        ReversalCount=lambda x: x.astype(int).sum(),
                        NonReversalCount=lambda x: (~x).astype(int).sum()
                    )
                    daily_counts['ReversalPct'] = daily_counts['ReversalCount'] / (
                        daily_counts['ReversalCount'] + daily_counts['NonReversalCount']
                    )
                    dates = pd.to_datetime(daily_counts.index)

                    # Reversal magnitude analysis
                    df['ReversalMagnitude'] = np.abs(df['Close'] - df['Open'])
                    rev_mags = df[df['Reversal']].copy()
                    rev_mags['Date'] = rev_mags.index.date
                    mag_stats = rev_mags.groupby('Date')['ReversalMagnitude'].agg(['min', 'median', 'max'])

                    # Time between reversals analysis
                    reversal_times = df.index[df['Reversal']].to_series()
                    reversal_time_diffs = reversal_times.diff().dropna().dt.total_seconds() / 60
                    reversal_time_df = pd.DataFrame({
                        'TimeBetween': reversal_time_diffs,
                        'Date': reversal_times.iloc[1:].dt.date
                    })
                    time_stats = reversal_time_df.groupby('Date')['TimeBetween'].agg(['min', 'median', 'max'])

                    # Create a figure with 4 rows (subplots)
                    fig = make_subplots(
                        rows=4, cols=1,
                        shared_xaxes=True,
                        subplot_titles=(
                            f"{ticker} Close Price with Reversal Points",
                            "Daily Reversal Counts & Reversal %",
                            "Daily Reversal Magnitude Summary",
                            "Daily Time Between Reversals (Minutes)"
                        ),
                        specs=[
                            [{}],
                            [{"secondary_y": True}],
                            [{}],
                            [{}]
                        ]
                    )

                    # Subplot 1: Price with reversal markers
                    fig.add_trace(
                        go.Scatter(
                            x=df.index,
                            y=df['Close'],
                            mode='lines',
                            name='Close Price',
                            line=dict(color='blue')
                        ),
                        row=1, col=1
                    )
                    reversal_points = df[df['Reversal']]
                    fig.add_trace(
                        go.Scatter(
                            x=reversal_points.index,
                            y=reversal_points['Close'],
                            mode='markers',
                            name='Reversal',
                            marker=dict(color='red', size=6, opacity=0.5)
                        ),
                        row=1, col=1
                    )
                    non_reversal_points = df[~df['Reversal']]
                    fig.add_trace(
                        go.Scatter(
                            x=non_reversal_points.index,
                            y=non_reversal_points['Close'],
                            mode='markers',
                            name='Not Reversal',
                            marker=dict(color='green', size=4, opacity=0.5)
                        ),
                        row=1, col=1
                    )

                    # Subplot 2: Daily reversal counts (stacked bar) and reversal percentage line
                    fig.add_trace(
                        go.Bar(
                            x=dates,
                            y=daily_counts['ReversalCount'],
                            name='Reversal',
                            marker_color='red'
                        ),
                        row=2, col=1, secondary_y=False
                    )
                    fig.add_trace(
                        go.Bar(
                            x=dates,
                            y=daily_counts['NonReversalCount'],
                            name='Not Reversal',
                            marker_color='green',
                            opacity=0.6
                        ),
                        row=2, col=1, secondary_y=False
                    )
                    fig.add_trace(
                        go.Scatter(
                            x=dates,
                            y=daily_counts['ReversalPct'],
                            mode='lines',
                            name='Reversal %',
                            line=dict(color='white')
                        ),
                        row=2, col=1, secondary_y=True
                    )

                    # Subplot 3: Reversal magnitude stats
                    fig.add_trace(
                        go.Scatter(
                            x=mag_stats.index,
                            y=mag_stats['median'],
                            mode='lines',
                            name='Median',
                            line=dict(color='orange')
                        ),
                        row=3, col=1
                    )
                    fig.add_trace(
                        go.Scatter(
                            x=mag_stats.index,
                            y=mag_stats['min'],
                            mode='lines',
                            name='Min',
                            line=dict(dash='dash', color='gray')
                        ),
                        row=3, col=1
                    )
                    fig.add_trace(
                        go.Scatter(
                            x=mag_stats.index,
                            y=mag_stats['max'],
                            mode='lines',
                            name='Max',
                            line=dict(dash='dash', color='white')
                        ),
                        row=3, col=1
                    )

                    # Subplot 4: Time between reversals stats
                    fig.add_trace(
                        go.Scatter(
                            x=time_stats.index,
                            y=time_stats['median'],
                            mode='lines',
                            name='Median',
                            line=dict(color='purple')
                        ),
                        row=4, col=1
                    )
                    fig.add_trace(
                        go.Scatter(
                            x=time_stats.index,
                            y=time_stats['min'],
                            mode='lines',
                            name='Min',
                            line=dict(dash='dash', color='gray')
                        ),
                        row=4, col=1
                    )
                    fig.add_trace(
                        go.Scatter(
                            x=time_stats.index,
                            y=time_stats['max'],
                            mode='lines',
                            name='Max',
                            line=dict(dash='dash', color='white')
                        ),
                        row=4, col=1
                    )

                    # Update layout with dark theme, white titles, and gridlines with alpha 0.2
                    fig.update_layout(
                        height=1800,
                        width=1700,
                        title_text=f"{ticker} Analysis ({freq} Data)",
                        title_font_color='white',
                        barmode='stack',
                        template='plotly_dark',
                        paper_bgcolor='#0e1117',
                        plot_bgcolor='#0e1117',
                        legend=dict(font=dict(color='white'))
                    )

                    # Update all axes to set white titles and gridlines with alpha 0.2
                    fig.update_xaxes(
                        title_font_color='white',
                        gridcolor='rgba(255, 255, 255, 0.2)'
                    )
                    fig.update_yaxes(
                        title_font_color='white',
                        gridcolor='rgba(255, 255, 255, 0.2)'
                    )
                    
                    fig.for_each_annotation(lambda a: a.update(font=dict(color='white')))

                    # Display the figure in Streamlit
                    st.plotly_chart(fig, use_container_width=True)

            except Exception:
                st.error("An error occurred. Please check your input and try again.")
                
# Hide default Streamlit style
st.markdown(
    """
    <style>
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    </style>
    """,
    unsafe_allow_html=True
)