QuantumLearner commited on
Commit
999cbda
·
verified ·
1 Parent(s): 9fee7b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +244 -294
app.py CHANGED
@@ -8,316 +8,266 @@ from scipy.signal import argrelextrema
8
  from sklearn.cluster import KMeans
9
  import matplotlib.pyplot as plt
10
 
11
- # Streamlit app
12
-
13
  st.set_page_config(page_title="Identifying Key Support and Resistance In Price Levels", layout="wide")
14
  st.title('Key Support and Resistance In Price Levels')
15
 
16
  st.markdown("""
17
- This tool aims to identify key support and resistance price levels in stocks using various algorithmic methods. Each method is detailed below:
18
- 1. **Pivot Points**: Short-term trend indicators used to determine potential support and resistance levels based on the high, low, and close prices of previous trading sessions.
19
- 2. **Support and Resistance Levels using Rolling Midpoint Range**: Key price points where the stock's price tends to halt its upward or downward trajectory, identified using a rolling window to calculate dynamic support and resistance levels.
20
- 3. **Swing Highs and Lows**: Local maxima and minima used to identify trends and potential reversal points by pinpointing key inflection points on a stock's chart.
21
- 4. **Fibonacci Retracement Levels**: Horizontal lines indicating potential support and resistance levels based on Fibonacci numbers, helping to identify prospective market reversal points.
22
- 5. **Trendlines**: Straight lines drawn to connect two or more price points, helping identify the market trend direction and potential areas of support and resistance.
23
- 6. **Volume Profile**: A charting tool that shows the amount of volume traded at different price levels over a specified period, helping identify areas of high trading activity which can act as support or resistance.
24
- 7. **KMeans Clustering**: A machine learning algorithm used to partition the dataset into clusters, identifying patterns and grouping similar price movements together to highlight significant price levels.
25
  """)
26
 
27
- # Sidebar: How to use and Input Parameters
28
  st.sidebar.title('Input Parameters')
29
 
30
- st.sidebar.subheader('How to use:')
31
-
32
- st.sidebar.markdown("""
33
- 1. **Enter Ticker**: Specify a stock ticker or crypto pair.
34
- 2. **Set Dates**: Choose the date range for analysis.
35
- 3. **Adjust Parameters**: Modify methodology parameters as needed.
36
- 4. **Run Analysis**: Click 'Run' to generate results.
37
- """)
38
-
39
- # Expander for ticker and date settings
40
- with st.sidebar.expander("Ticker and Date Settings", expanded=True):
41
- st.write("Specify the ticker and date range for analysis.")
42
- ticker = st.text_input('Stock Ticker or Crypto Pair', 'AAPL', help="Enter stock ticker (e.g., AAPL) or crypto pair (e.g., BTC-USD).")
43
- start_date = st.date_input('Start Date', pd.to_datetime('2023-01-01'))
44
- end_date = st.date_input('End Date', datetime.now() + timedelta(days=1))
45
-
46
- # Expander for methodology-specific parameters
47
- with st.sidebar.expander("Pivot Points and Levels", expanded=True):
48
- window_period = st.slider('Window Period for Pivot Points and Levels', min_value=10, max_value=60, value=30, help="Set the window period for calculating pivot points and support/resistance levels.")
49
-
50
- with st.sidebar.expander("Trendlines and Fibonacci Levels", expanded=True):
51
- lookback_period = st.slider('Lookback Period for Trendlines and Fibonacci', min_value=10, max_value=60, value=30, help="Set the lookback period for calculating trendlines and Fibonacci retracement levels.")
52
-
53
- with st.sidebar.expander("Volume Profile and KMeans", expanded=True):
54
- n_days = st.slider('Lookback Period for Volume Profile and KMeans (Days)', min_value=30, max_value=365, value=60, help="Set the number of days for calculating volume profile and KMeans clustering.")
55
- num_clusters = st.slider('Number of Clusters for KMeans', min_value=2, max_value=10, value=3, help="Set the number of clusters for KMeans analysis.")
56
-
57
- # Define functions for different analyses
58
- def calculate_pivot_points(df, window):
59
- df['Pivot'] = df['Close'].rolling(window=window).mean()
60
- df['R1'] = 2 * df['Pivot'] - df['Low'].rolling(window=window).min()
61
- df['S1'] = 2 * df['Pivot'] - df['High'].rolling(window=window).max()
62
- df['R2'] = df['Pivot'] + (df['High'].rolling(window=window).max() - df['Low'].rolling(window=window).min())
63
- df['S2'] = df['Pivot'] - (df['High'].rolling(window=window).max() - df['Low'].rolling(window=window).min())
64
- return df
65
-
66
- def find_levels(data, window):
67
- resistance = data['High'].rolling(window=window).max()
68
- support = data['Low'].rolling(window=window).min()
69
- return support, resistance
70
-
71
- def check_significant_break(data, support, resistance):
72
- breaks_above_resistance = (data['Close'] > resistance.shift(1)) & (data['Volume'] > data['Volume'].rolling(window=30).mean())
73
- breaks_below_support = (data['Close'] < support.shift(1)) & (data['Volume'] > data['Volume'].rolling(window=30).mean())
74
- return breaks_above_resistance, breaks_below_support
75
-
76
- def prepare_data_for_trendlines(data, lookback_period):
77
- data['Swing_High'] = data['High'][argrelextrema(data['High'].values, np.greater_equal, order=lookback_period)[0]]
78
- data['Swing_Low'] = data['Low'][argrelextrema(data['Low'].values, np.less_equal, order=lookback_period)[0]]
79
  return data
80
 
81
- def calculate_fibonacci_levels(data, lookback_period):
82
- high_prices = data["High"].rolling(window=lookback_period).max()
83
- low_prices = data["Low"].rolling(window=lookback_period).min()
84
- price_diff = high_prices - low_prices
85
- levels = np.array([0, 0.236, 0.382, 0.5, 0.618, 0.786, 1])
86
- fib_levels = low_prices.values.reshape(-1, 1) + price_diff.values.reshape(-1, 1) * levels
87
- return fib_levels, levels
88
-
89
- def calculate_volume_profile(data, n_days):
90
- filtered_data = data[-n_days:]
91
- price_bins = np.linspace(filtered_data['Low'].min(), filtered_data['High'].max(), 100)
92
- volume_profile = [filtered_data['Volume'][(filtered_data['Close'] > price_bins[i]) & (filtered_data['Close'] <= price_bins[i+1])].sum() for i in range(len(price_bins)-1)]
93
- return price_bins, volume_profile
94
-
95
- def calculate_kmeans_clusters(data, n_days, num_clusters):
96
- filtered_data = data[-n_days:]
97
- X_time = np.linspace(0, 1, len(filtered_data)).reshape(-1, 1)
98
- X_price = (filtered_data['Close'].values - np.min(filtered_data['Close'])) / (np.max(filtered_data['Close']) - np.min(filtered_data['Close']))
99
- X_cluster = np.column_stack((X_time, X_price))
100
- kmeans = KMeans(n_clusters=num_clusters)
101
- kmeans.fit(X_cluster)
102
- cluster_centers = kmeans.cluster_centers_[:, 1] * (np.max(filtered_data['Close']) - np.min(filtered_data['Close'])) + np.min(filtered_data['Close'])
103
- return cluster_centers
104
-
105
- # Run the analysis
106
  if st.sidebar.button('Run Analysis'):
107
- data = yf.download(ticker, start=start_date, end=end_date)
108
 
109
  if not data.empty:
110
- # Calculate Pivot Points
111
- df_pivot = calculate_pivot_points(data.copy(), window_period)
112
- df_pivot = df_pivot.dropna()
113
-
114
- # Calculate Support and Resistance Levels
115
- support, resistance = find_levels(data.copy(), window_period)
116
- breaks_above_resistance, breaks_below_support = check_significant_break(data.copy(), support, resistance)
117
-
118
- # Calculate Swing Highs and Lows
119
- data_with_trendlines = prepare_data_for_trendlines(data.copy(), lookback_period)
120
-
121
- # Calculate Fibonacci Retracement Levels
122
- fib_levels, levels = calculate_fibonacci_levels(data.copy(), lookback_period)
123
-
124
- # Calculate Volume Profile
125
- price_bins, volume_profile = calculate_volume_profile(data.copy(), n_days)
126
-
127
- # Calculate KMeans Clusters
128
- cluster_centers = calculate_kmeans_clusters(data.copy(), n_days, num_clusters)
129
-
130
- # Plot Pivot Points
131
- st.write("### Pivot Points")
132
- st.markdown("""
133
- **Pivot Points** are short-term trend indicators used to determine potential support and resistance levels. The central pivot point, as well as derived support and resistance levels, are calculated using the high, low, and close prices of a previous period (usually the previous day for day trading).
134
- - **Pivot Point (P)**: The average of the high, low, and close of the previous trading period.
135
- - **First Resistance (R1)**: Calculated by doubling the pivot point and then subtracting the previous low.
136
- - **First Support (S1)**: Derived by doubling the pivot point and then subtracting the previous high.
137
- - **Second Resistance (R2)**: Obtained by adding the difference of high and low (the range) to the pivot point.
138
- - **Second Support (S2)**: Found by subtracting the range from the pivot point.
139
- """)
140
-
141
- fig1 = go.Figure()
142
- fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['Close'], mode='lines', name='Close Price'))
143
- fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['Pivot'], mode='lines', name='Pivot', line=dict(dash='dash', color='black')))
144
- fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['R1'], mode='lines', name='Resistance 1', line=dict(dash='dash', color='red')))
145
- fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['S1'], mode='lines', name='Support 1', line=dict(dash='dash', color='green')))
146
- fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['R2'], mode='lines', name='Resistance 2', line=dict(dash='dash', color='orange')))
147
- fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['S2'], mode='lines', name='Support 2', line=dict(dash='dash', color='blue')))
148
- fig1.update_layout(
149
- title=f'{ticker} Price with Pivot Points and Support/Resistance Levels',
150
- xaxis_title='Date',
151
- yaxis_title='Price',
152
- legend_title='Legend',
153
- width=1200, # Set desired width
154
- height=600 # Set desired height
155
- )
156
- st.plotly_chart(fig1, use_container_width=True)
157
-
158
- # Plot Support and Resistance Levels using Rolling Midpoint Range
159
- st.write("### Rolling Midpoint Range")
160
- st.markdown("""
161
- **Support and Resistance Levels** This method uses a rolling window to identify these levels. This provides a dynamic approach to pinpointing key price levels.
162
- - **Support Level**: Calculated as the rolling minimum price over the specified window period. It acts as a floor where buying interest is strong enough to prevent further price declines.
163
- - **Resistance Level**: Calculated as the rolling maximum price over the specified window period. It acts as a ceiling where selling interest prevents the price from rising further.
164
- In this analysis, the support and resistance levels are determined using a rolling window approach. Significant breaks above resistance and below support are highlighted, especially when accompanied by higher-than-average trading volumes, which could indicate potential breakout or breakdown scenarios.
165
- """)
166
-
167
- fig2 = go.Figure()
168
- fig2.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Stock Price'))
169
- fig2.add_trace(go.Scatter(x=data.index, y=support, mode='lines', name='Support', line=dict(dash='dash', color='green')))
170
- fig2.add_trace(go.Scatter(x=data.index, y=resistance, mode='lines', name='Resistance', line=dict(dash='dash', color='red')))
171
- fig2.add_trace(go.Scatter(x=data[breaks_above_resistance].index, y=data['Close'][breaks_above_resistance], mode='markers', name='Break Above Resistance', marker=dict(color='blue')))
172
- fig2.add_trace(go.Scatter(x=data[breaks_below_support].index, y=data['Close'][breaks_below_support], mode='markers', name='Break Below Support', marker=dict(color='purple')))
173
- fig2.update_layout(
174
- title=f'{ticker} Price with Support and Resistance Levels',
175
- xaxis_title='Date',
176
- yaxis_title='Price',
177
- legend_title='Legend',
178
- width=1200, # Set desired width
179
- height=600 # Set desired height
180
- )
181
- st.plotly_chart(fig2, use_container_width=True)
182
-
183
- # Plot Swing Highs and Lows
184
- st.write("### Swing Highs and Lows")
185
- st.markdown("""
186
- **Swing Highs and Lows** are the highest and lowest points in the price action over a specified period.
187
- - **Swing High**: A peak where the price is higher than the surrounding prices.
188
- - **Swing Low**: A trough where the price is lower than the surrounding prices.
189
- """)
190
-
191
- fig3 = go.Figure()
192
- fig3.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Close'], mode='lines', name='Close Price'))
193
- fig3.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Swing_High'], mode='markers', name='Swing Highs', marker=dict(color='red')))
194
- fig3.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Swing_Low'], mode='markers', name='Swing Lows', marker=dict(color='green')))
195
- fig3.update_layout(
196
- title=f'{ticker} with Swing Highs & Lows',
197
- xaxis_title='Date',
198
- yaxis_title='Price',
199
- legend_title='Legend',
200
- width=1200, # Set desired width
201
- height=600 # Set desired height
202
- )
203
- st.plotly_chart(fig3, use_container_width=True)
204
-
205
- # Plot Fibonacci Retracement Levels
206
- st.write("### Fibonacci Retracement Levels")
207
- st.markdown("""
208
- **Fibonacci Retracement Levels** are horizontal lines that indicate where support and resistance are likely to occur. They are based on Fibonacci numbers and are used to predict the future movement of asset prices.
209
- - **Levels**: 23.6%, 38.2%, 50%, 61.8%, and 78.6% represent key points where the price could potentially reverse.
210
- """)
211
-
212
- fig4 = go.Figure()
213
- fig4.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Stock Price'))
214
- color_list = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
215
- for i, (level, color) in enumerate(zip(levels, color_list)):
216
- fig4.add_trace(go.Scatter(x=data.index, y=fib_levels[:, i], mode='lines', name=f'Fib {level:.3f}', line=dict(color=color)))
217
- fig4.update_layout(
218
- title=f'{ticker} with Fibonacci Retracement Levels',
219
- xaxis_title='Date',
220
- yaxis_title='Price',
221
- legend_title='Legend',
222
- width=1200, # Set desired width
223
- height=600 # Set desired height
224
- )
225
- st.plotly_chart(fig4, use_container_width=True)
226
-
227
- # Plot Trendlines
228
- st.write("### Trendlines with Regression Analysis")
229
- st.markdown("""
230
- **Trendlines** are straight lines drawn on a price chart to connect two or more price points. They help identify the direction of the market trend and potential areas of support and resistance. In this analysis, trendlines are determined using regression analysis to fit the lines through swing highs and lows.
231
- - **Upper Trendline**: Connects higher highs using linear regression to fit a line through these points. This line acts as a resistance level.
232
- - **Lower Trendline**: Connects lower lows using linear regression to fit a line through these points. This line acts as a support level.
233
- 1. **Swing Highs and Lows Identification**: First, local maxima (swing highs) and minima (swing lows) are identified using a specified lookback period.
234
- 2. **Linear Regression**: A linear regression is then applied to the swing highs to form the upper trendline and to the swing lows to form the lower trendline.
235
- 3. **Visualization**: The trendlines are plotted along with the stock's closing prices to represent of potential resistance and support levels.
236
- """)
237
-
238
- fig5 = go.Figure()
239
- fig5.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Close'], mode='lines', name='Close Price'))
240
-
241
- swing_highs = data_with_trendlines['Swing_High'].dropna()
242
- swing_lows = data_with_trendlines['Swing_Low'].dropna()
243
-
244
- if len(swing_highs) > 1 and len(swing_lows) > 1:
245
- upper_m, upper_b = np.polyfit(swing_highs.index.map(pd.Timestamp.toordinal), swing_highs.values, 1)
246
- lower_m, lower_b = np.polyfit(swing_lows.index.map(pd.Timestamp.toordinal), swing_lows.values, 1)
247
- data_with_trendlines['Upper_Trendline'] = upper_m * data_with_trendlines.index.map(pd.Timestamp.toordinal) + upper_b
248
- data_with_trendlines['Lower_Trendline'] = lower_m * data_with_trendlines.index.map(pd.Timestamp.toordinal) + lower_b
249
- fig5.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Upper_Trendline'], mode='lines', name='Upper Trendline', line=dict(color='orange')))
250
- fig5.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Lower_Trendline'], mode='lines', name='Lower Trendline', line=dict(color='blue')))
251
-
252
- fig5.update_layout(
253
- title=f'{ticker} with Trendlines',
254
- xaxis_title='Date',
255
- yaxis_title='Price',
256
- legend_title='Legend',
257
- width=1200, # Set desired width
258
- height=600 # Set desired height
259
- )
260
- st.plotly_chart(fig5, use_container_width=True)
261
-
262
- # Plot Volume Profile
263
- st.write("### Volume Profile")
264
- st.markdown("""
265
- **Volume Profile** is a charting tool that shows the amount of volume traded at different price levels over a specified period. It helps identify areas of high trading activity, which can act as support or resistance.
266
- - **High Volume Areas**: Indicate significant trading activity and can act as strong support or resistance levels.
267
- """)
268
-
269
- fig6, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(20, 5), gridspec_kw={'width_ratios': [3, 1]})
270
- ax1.plot(data['Close'], label="Close Price")
271
- current_price = data['Close'].iloc[-1]
272
- support_idx = np.argmax(volume_profile[:np.digitize(current_price, price_bins)])
273
- resistance_idx = np.argmax(volume_profile[np.digitize(current_price, price_bins):]) + np.digitize(current_price, price_bins)
274
- support_price = price_bins[support_idx]
275
- resistance_price = price_bins[resistance_idx]
276
- ax1.axhline(y=support_price, color='g', linestyle='--', label='Support')
277
- ax1.axhline(y=resistance_price, color='r', linestyle='--', label='Resistance')
278
- ax1.annotate(f'Support: {support_price:.2f}',
279
- xy=(data.index[-1], support_price),
280
- xytext=(data.index[-1], support_price - 5),
281
- arrowprops=dict(facecolor='green', arrowstyle='->'),
282
- color='green', fontsize=12)
283
- ax1.annotate(f'Resistance: {resistance_price:.2f}',
284
- xy=(data.index[-1], resistance_price),
285
- xytext=(data.index[-1], resistance_price + 5),
286
- arrowprops=dict(facecolor='red', arrowstyle='->'),
287
- color='red', fontsize=12)
288
- ax1.legend()
289
- ax1.set_title(f'{ticker} Price Data')
290
- ax2.barh(price_bins[:-1], volume_profile, height=(price_bins[1] - price_bins[0]), color='blue', edgecolor='none')
291
- ax2.set_title('Volume Profile')
292
- st.pyplot(fig6, use_container_width=True)
293
-
294
- # Plot KMeans Clusters
295
- st.write("### KMeans Clusters")
296
- st.markdown("""
297
- **KMeans Clustering** is a machine learning algorithm used to partition a dataset into clusters. In the context of stock prices, it helps identify patterns and group similar price movements together.
298
- - **Clusters**: Represent different regimes or phases in the stock price movements.
299
- """)
300
-
301
- fig7 = go.Figure()
302
- fig7.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close Price'))
303
- for center in cluster_centers:
304
- fig7.add_trace(go.Scatter(x=[data.index[-1]], y=[center], mode='markers+text', name=f'Cluster Center: {center:.2f}', text=[f'{center:.2f}'], textposition='top center'))
305
- fig7.add_shape(type="line",
306
- x0=data.index[0], x1=data.index[-1], y0=center, y1=center,
307
- line=dict(color='Red', dash="dash"))
308
- fig7.update_layout(
309
- title=f'{ticker} with KMeans Clustering (Last {n_days} Days)',
310
- xaxis_title='Date',
311
- yaxis_title='Price',
312
- legend_title='Legend',
313
- width=1200, # Set desired width
314
- height=600 # Set desired height
315
- )
316
- st.plotly_chart(fig7, use_container_width=True)
317
-
318
  else:
319
  st.write("No data found for the given ticker and date range.")
320
 
 
321
  hide_streamlit_style = """
322
  <style>
323
  #MainMenu {visibility: hidden;}
 
8
  from sklearn.cluster import KMeans
9
  import matplotlib.pyplot as plt
10
 
11
+ # Streamlit app setup
 
12
  st.set_page_config(page_title="Identifying Key Support and Resistance In Price Levels", layout="wide")
13
  st.title('Key Support and Resistance In Price Levels')
14
 
15
  st.markdown("""
16
+ This tool aims to identify key support and resistance price levels in stocks using various algorithmic methods. Select the method from the dropdown menu to view the corresponding analysis.
 
 
 
 
 
 
 
17
  """)
18
 
19
+ # Sidebar for input parameters
20
  st.sidebar.title('Input Parameters')
21
 
22
+ with st.sidebar:
23
+ st.header("How to use:")
24
+ st.markdown("""
25
+ 1. **Enter Ticker**: Specify a stock ticker or crypto pair.
26
+ 2. **Set Dates**: Choose the date range for analysis.
27
+ 3. **Adjust Parameters**: Modify methodology parameters as needed.
28
+ 4. **Select Analysis**: Choose the analysis type to display results.
29
+ """)
30
+
31
+ # Expander for ticker and date settings
32
+ with st.expander("Ticker and Date Settings", expanded=True):
33
+ ticker = st.text_input('Stock Ticker or Crypto Pair', 'AAPL', help="Enter stock ticker (e.g., AAPL) or crypto pair (e.g., BTC-USD).")
34
+ start_date = st.date_input('Start Date', pd.to_datetime('2023-01-01'))
35
+ end_date = st.date_input('End Date', datetime.now() + timedelta(days=1))
36
+
37
+ # Expander for methodology-specific parameters
38
+ with st.expander("Pivot Points and Levels", expanded=True):
39
+ window_period = st.slider('Window Period for Pivot Points and Levels', min_value=10, max_value=60, value=30, help="Set the window period for calculating pivot points and support/resistance levels.")
40
+
41
+ with st.expander("Trendlines and Fibonacci Levels", expanded=True):
42
+ lookback_period = st.slider('Lookback Period for Trendlines and Fibonacci', min_value=10, max_value=60, value=30, help="Set the lookback period for calculating trendlines and Fibonacci retracement levels.")
43
+
44
+ with st.expander("Volume Profile and KMeans", expanded=True):
45
+ n_days = st.slider('Lookback Period for Volume Profile and KMeans (Days)', min_value=30, max_value=365, value=60, help="Set the number of days for calculating volume profile and KMeans clustering.")
46
+ num_clusters = st.slider('Number of Clusters for KMeans', min_value=2, max_value=10, value=3, help="Set the number of clusters for KMeans analysis.")
47
+
48
+ # Select analysis type
49
+ analysis_type = st.selectbox("Select Analysis", ["Pivot Points", "Support and Resistance", "Swing Highs and Lows", "Fibonacci Retracement Levels", "Trendlines", "Volume Profile", "KMeans Clustering"])
50
+
51
+ # Function to fetch and cache data
52
+ @st.cache_data
53
+ def get_data(ticker, start_date, end_date):
54
+ data = yf.download(ticker, start=start_date, end=end_date)
55
+ if data.empty:
56
+ st.error("No data found for the given ticker and date range.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  return data
58
 
59
+ # Run analysis only if the user clicks the "Run Analysis" button
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  if st.sidebar.button('Run Analysis'):
61
+ data = get_data(ticker, start_date, end_date)
62
 
63
  if not data.empty:
64
+ if analysis_type == "Pivot Points":
65
+ df_pivot = calculate_pivot_points(data.copy(), window_period)
66
+ df_pivot = df_pivot.dropna()
67
+
68
+ st.write("### Pivot Points")
69
+ st.markdown("""
70
+ **Pivot Points** are short-term trend indicators used to determine potential support and resistance levels. The central pivot point, as well as derived support and resistance levels, are calculated using the high, low, and close prices of a previous period (usually the previous day for day trading).
71
+ - **Pivot Point (P)**: The average of the high, low, and close of the previous trading period.
72
+ - **First Resistance (R1)**: Calculated by doubling the pivot point and then subtracting the previous low.
73
+ - **First Support (S1)**: Derived by doubling the pivot point and then subtracting the previous high.
74
+ - **Second Resistance (R2)**: Obtained by adding the difference of high and low (the range) to the pivot point.
75
+ - **Second Support (S2)**: Found by subtracting the range from the pivot point.
76
+ """)
77
+
78
+ fig1 = go.Figure()
79
+ fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['Close'], mode='lines', name='Close Price'))
80
+ fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['Pivot'], mode='lines', name='Pivot', line=dict(dash='dash', color='black')))
81
+ fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['R1'], mode='lines', name='Resistance 1', line=dict(dash='dash', color='red')))
82
+ fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['S1'], mode='lines', name='Support 1', line=dict(dash='dash', color='green')))
83
+ fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['R2'], mode='lines', name='Resistance 2', line=dict(dash='dash', color='orange')))
84
+ fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['S2'], mode='lines', name='Support 2', line=dict(dash='dash', color='blue')))
85
+ fig1.update_layout(
86
+ title=f'{ticker} Price with Pivot Points and Support/Resistance Levels',
87
+ xaxis_title='Date',
88
+ yaxis_title='Price',
89
+ legend_title='Legend',
90
+ width=1200,
91
+ height=600
92
+ )
93
+ st.plotly_chart(fig1, use_container_width=True)
94
+
95
+ elif analysis_type == "Support and Resistance":
96
+ support, resistance = find_levels(data.copy(), window_period)
97
+ breaks_above_resistance, breaks_below_support = check_significant_break(data.copy(), support, resistance)
98
+
99
+ st.write("### Rolling Midpoint Range")
100
+ st.markdown("""
101
+ **Support and Resistance Levels** This method uses a rolling window to identify these levels. This provides a dynamic approach to pinpointing key price levels.
102
+ - **Support Level**: Calculated as the rolling minimum price over the specified window period. It acts as a floor where buying interest is strong enough to prevent further price declines.
103
+ - **Resistance Level**: Calculated as the rolling maximum price over the specified window period. It acts as a ceiling where selling interest prevents the price from rising further.
104
+ In this analysis, the support and resistance levels are determined using a rolling window approach. Significant breaks above resistance and below support are highlighted, especially when accompanied by higher-than-average trading volumes, which could indicate potential breakout or breakdown scenarios.
105
+ """)
106
+
107
+ fig2 = go.Figure()
108
+ fig2.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Stock Price'))
109
+ fig2.add_trace(go.Scatter(x=data.index, y=support, mode='lines', name='Support', line=dict(dash='dash', color='green')))
110
+ fig2.add_trace(go.Scatter(x=data.index, y=resistance, mode='lines', name='Resistance', line=dict(dash='dash', color='red')))
111
+ fig2.add_trace(go.Scatter(x=data[breaks_above_resistance].index, y=data['Close'][breaks_above_resistance], mode='markers', name='Break Above Resistance', marker=dict(color='blue')))
112
+ fig2.add_trace(go.Scatter(x=data[breaks_below_support].index, y=data['Close'][breaks_below_support], mode='markers', name='Break Below Support', marker=dict(color='purple')))
113
+ fig2.update_layout(
114
+ title=f'{ticker} Price with Support and Resistance Levels',
115
+ xaxis_title='Date',
116
+ yaxis_title='Price',
117
+ legend_title='Legend',
118
+ width=1200,
119
+ height=600
120
+ )
121
+ st.plotly_chart(fig2, use_container_width=True)
122
+
123
+ elif analysis_type == "Swing Highs and Lows":
124
+ data_with_trendlines = prepare_data_for_trendlines(data.copy(), lookback_period)
125
+
126
+ st.write("### Swing Highs and Lows")
127
+ st.markdown("""
128
+ **Swing Highs and Lows** are the highest and lowest points in the price action over a specified period.
129
+ - **Swing High**: A peak where the price is higher than the surrounding prices.
130
+ - **Swing Low**: A trough where the price is lower than the surrounding prices.
131
+ """)
132
+
133
+ fig3 = go.Figure()
134
+ fig3.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Close'], mode='lines', name='Close Price'))
135
+ fig3.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Swing_High'], mode='markers', name='Swing Highs', marker=dict(color='red')))
136
+ fig3.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Swing_Low'], mode='markers', name='Swing Lows', marker=dict(color='green')))
137
+ fig3.update_layout(
138
+ title=f'{ticker} with Swing Highs & Lows',
139
+ xaxis_title='Date',
140
+ yaxis_title='Price',
141
+ legend_title='Legend',
142
+ width=1200,
143
+ height=600
144
+ )
145
+ st.plotly_chart(fig3, use_container_width=True)
146
+
147
+ elif analysis_type == "Fibonacci Retracement Levels":
148
+ fib_levels, levels = calculate_fibonacci_levels(data.copy(), lookback_period)
149
+
150
+ st.write("### Fibonacci Retracement Levels")
151
+ st.markdown("""
152
+ **Fibonacci Retracement Levels** are horizontal lines that indicate where support and resistance are likely to occur. They are based on Fibonacci numbers and are used to predict the future movement of asset prices.
153
+ - **Levels**: 23.6%, 38.2%, 50%, 61.8%, and 78.6% represent key points where the price could potentially reverse.
154
+ """)
155
+
156
+ fig4 = go.Figure()
157
+ fig4.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Stock Price'))
158
+ color_list = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
159
+ for i, (level, color) in enumerate(zip(levels, color_list)):
160
+ fig4.add_trace(go.Scatter(x=data.index, y=fib_levels[:, i], mode='lines', name=f'Fib {level:.3f}', line=dict(color=color)))
161
+ fig4.update_layout(
162
+ title=f'{ticker} with Fibonacci Retracement Levels',
163
+ xaxis_title='Date',
164
+ yaxis_title='Price',
165
+ legend_title='Legend',
166
+ width=1200,
167
+ height=600
168
+ )
169
+ st.plotly_chart(fig4, use_container_width=True)
170
+
171
+ elif analysis_type == "Trendlines":
172
+ data_with_trendlines = prepare_data_for_trendlines(data.copy(), lookback_period)
173
+
174
+ st.write("### Trendlines with Regression Analysis")
175
+ st.markdown("""
176
+ **Trendlines** are straight lines drawn on a price chart to connect two or more price points. They help identify the direction of the market trend and potential areas of support and resistance. In this analysis, trendlines are determined using regression analysis to fit the lines through swing highs and lows.
177
+ - **Upper Trendline**: Connects higher highs using linear regression to fit a line through these points. This line acts as a resistance level.
178
+ - **Lower Trendline**: Connects lower lows using linear regression to fit a line through these points. This line acts as a support level.
179
+ 1. **Swing Highs and Lows Identification**: First, local maxima (swing highs) and minima (swing lows) are identified using a specified lookback period.
180
+ 2. **Linear Regression**: A linear regression is then applied to the swing highs to form the upper trendline and to the swing lows to form the lower trendline.
181
+ 3. **Visualization**: The trendlines are plotted along with the stock's closing prices to represent of potential resistance and support levels.
182
+ """)
183
+
184
+ fig5 = go.Figure()
185
+ fig5.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Close'], mode='lines', name='Close Price'))
186
+
187
+ swing_highs = data_with_trendlines['Swing_High'].dropna()
188
+ swing_lows = data_with_trendlines['Swing_Low'].dropna()
189
+
190
+ if len(swing_highs) > 1 and len(swing_lows) > 1:
191
+ upper_m, upper_b = np.polyfit(swing_highs.index.map(pd.Timestamp.toordinal), swing_highs.values, 1)
192
+ lower_m, lower_b = np.polyfit(swing_lows.index.map(pd.Timestamp.toordinal), swing_lows.values, 1)
193
+ data_with_trendlines['Upper_Trendline'] = upper_m * data_with_trendlines.index.map(pd.Timestamp.toordinal) + upper_b
194
+ data_with_trendlines['Lower_Trendline'] = lower_m * data_with_trendlines.index.map(pd.Timestamp.toordinal) + lower_b
195
+ fig5.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Upper_Trendline'], mode='lines', name='Upper Trendline', line=dict(color='orange')))
196
+ fig5.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Lower_Trendline'], mode='lines', name='Lower Trendline', line=dict(color='blue')))
197
+
198
+ fig5.update_layout(
199
+ title=f'{ticker} with Trendlines',
200
+ xaxis_title='Date',
201
+ yaxis_title='Price',
202
+ legend_title='Legend',
203
+ width=1200,
204
+ height=600
205
+ )
206
+ st.plotly_chart(fig5, use_container_width=True)
207
+
208
+ elif analysis_type == "Volume Profile":
209
+ price_bins, volume_profile = calculate_volume_profile(data.copy(), n_days)
210
+
211
+ st.write("### Volume Profile")
212
+ st.markdown("""
213
+ **Volume Profile** is a charting tool that shows the amount of volume traded at different price levels over a specified period. It helps identify areas of high trading activity, which can act as support or resistance.
214
+ - **High Volume Areas**: Indicate significant trading activity and can act as strong support or resistance levels.
215
+ """)
216
+
217
+ fig6, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(20, 5), gridspec_kw={'width_ratios': [3, 1]})
218
+ ax1.plot(data['Close'], label="Close Price")
219
+ current_price = data['Close'].iloc[-1]
220
+ support_idx = np.argmax(volume_profile[:np.digitize(current_price, price_bins)])
221
+ resistance_idx = np.argmax(volume_profile[np.digitize(current_price, price_bins):]) + np.digitize(current_price, price_bins)
222
+ support_price = price_bins[support_idx]
223
+ resistance_price = price_bins[resistance_idx]
224
+ ax1.axhline(y=support_price, color='g', linestyle='--', label='Support')
225
+ ax1.axhline(y=resistance_price, color='r', linestyle='--', label='Resistance')
226
+ ax1.annotate(f'Support: {support_price:.2f}',
227
+ xy=(data.index[-1], support_price),
228
+ xytext=(data.index[-1], support_price - 5),
229
+ arrowprops=dict(facecolor='green', arrowstyle='->'),
230
+ color='green', fontsize=12)
231
+ ax1.annotate(f'Resistance: {resistance_price:.2f}',
232
+ xy=(data.index[-1], resistance_price),
233
+ xytext=(data.index[-1], resistance_price + 5),
234
+ arrowprops=dict(facecolor='red', arrowstyle='->'),
235
+ color='red', fontsize=12)
236
+ ax1.legend()
237
+ ax1.set_title(f'{ticker} Price Data')
238
+ ax2.barh(price_bins[:-1], volume_profile, height=(price_bins[1] - price_bins[0]), color='blue', edgecolor='none')
239
+ ax2.set_title('Volume Profile')
240
+ st.pyplot(fig6, use_container_width=True)
241
+
242
+ elif analysis_type == "KMeans Clustering":
243
+ cluster_centers = calculate_kmeans_clusters(data.copy(), n_days, num_clusters)
244
+
245
+ st.write("### KMeans Clusters")
246
+ st.markdown("""
247
+ **KMeans Clustering** is a machine learning algorithm used to partition a dataset into clusters. In the context of stock prices, it helps identify patterns and group similar price movements together.
248
+ - **Clusters**: Represent different regimes or phases in the stock price movements.
249
+ """)
250
+
251
+ fig7 = go.Figure()
252
+ fig7.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close Price'))
253
+ for center in cluster_centers:
254
+ fig7.add_trace(go.Scatter(x=[data.index[-1]], y=[center], mode='markers+text', name=f'Cluster Center: {center:.2f}', text=[f'{center:.2f}'], textposition='top center'))
255
+ fig7.add_shape(type="line",
256
+ x0=data.index[0], x1=data.index[-1], y0=center, y1=center,
257
+ line=dict(color='Red', dash="dash"))
258
+ fig7.update_layout(
259
+ title=f'{ticker} with KMeans Clustering (Last {n_days} Days)',
260
+ xaxis_title='Date',
261
+ yaxis_title='Price',
262
+ legend_title='Legend',
263
+ width=1200,
264
+ height=600
265
+ )
266
+ st.plotly_chart(fig7, use_container_width=True)
 
 
 
 
 
267
  else:
268
  st.write("No data found for the given ticker and date range.")
269
 
270
+ # Hide Streamlit style
271
  hide_streamlit_style = """
272
  <style>
273
  #MainMenu {visibility: hidden;}