Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,16 +5,55 @@ import plotly.graph_objects as go
|
|
| 5 |
import streamlit as st
|
| 6 |
from datetime import datetime, timedelta
|
| 7 |
from scipy.signal import argrelextrema
|
| 8 |
-
from sklearn.linear_model import LinearRegression
|
| 9 |
-
from sklearn.preprocessing import PolynomialFeatures
|
| 10 |
from sklearn.cluster import KMeans
|
| 11 |
import matplotlib.pyplot as plt
|
| 12 |
|
| 13 |
# Streamlit app
|
| 14 |
|
| 15 |
-
st.set_page_config(page_title
|
| 16 |
-
st.title('Identifying Key Support and Resistance Price Levels
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# Define functions for different analyses
|
| 20 |
def calculate_pivot_points(df, window):
|
|
@@ -64,34 +103,7 @@ def calculate_kmeans_clusters(data, n_days, num_clusters):
|
|
| 64 |
cluster_centers = kmeans.cluster_centers_[:, 1] * (np.max(filtered_data['Close']) - np.min(filtered_data['Close'])) + np.min(filtered_data['Close'])
|
| 65 |
return cluster_centers
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
# Sidebar inputs
|
| 71 |
-
st.sidebar.header('Input Parameters')
|
| 72 |
-
ticker = st.sidebar.text_input('Enter Stock Ticker', 'AAPL')
|
| 73 |
-
start_date = st.sidebar.date_input('Start Date', pd.to_datetime('2023-01-01'))
|
| 74 |
-
end_date = st.sidebar.date_input('End Date', pd.to_datetime('2024-12-31'))
|
| 75 |
-
window_period = st.sidebar.slider('Window Period for Pivot Points and Levels', min_value=10, max_value=60, value=30)
|
| 76 |
-
lookback_period = st.sidebar.slider('Lookback Period for Trendlines and Fibonacci', min_value=10, max_value=60, value=30)
|
| 77 |
-
n_days = st.sidebar.slider('Lookback Period for Volume Profile and KMeans (Days)', min_value=30, max_value=365, value=60)
|
| 78 |
-
num_clusters = st.sidebar.slider('Number of Clusters for KMeans', min_value=2, max_value=10, value=3)
|
| 79 |
-
|
| 80 |
-
st.markdown("""
|
| 81 |
-
This application aims to identify key support and resistance price levels in stocks using various algorithmic methods. Each method is detailed below, highlighting its significance and application in technical analysis. The following analyses are included:
|
| 82 |
-
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.
|
| 83 |
-
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.
|
| 84 |
-
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.
|
| 85 |
-
4. **Fibonacci Retracement Levels**: Horizontal lines indicating potential support and resistance levels based on Fibonacci numbers, helping to identify prospective market reversal points.
|
| 86 |
-
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.
|
| 87 |
-
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.
|
| 88 |
-
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.
|
| 89 |
-
#### How to Use This App
|
| 90 |
-
1. **Input Parameters**: Use the sidebar to enter the stock ticker, date range, and other parameters for the analyses.
|
| 91 |
-
2. **Run the Analysis**: Click the "Run" button to perform the analyses and visualize the results.
|
| 92 |
-
Each analysis is accompanied by a detailed explanation and visual representation, providing insights into the stock's price behavior and helping traders make informed decisions regarding support and resistance levels.
|
| 93 |
-
""")
|
| 94 |
-
|
| 95 |
if st.sidebar.button('Run'):
|
| 96 |
data = yf.download(ticker, start=start_date, end=end_date)
|
| 97 |
|
|
@@ -119,7 +131,7 @@ if st.sidebar.button('Run'):
|
|
| 119 |
# Plot Pivot Points
|
| 120 |
st.write("### Pivot Points")
|
| 121 |
st.markdown("""
|
| 122 |
-
**Pivot Points** are short-term trend indicators used
|
| 123 |
- **Pivot Point (P)**: The average of the high, low, and close of the previous trading period.
|
| 124 |
- **First Resistance (R1)**: Calculated by doubling the pivot point and then subtracting the previous low.
|
| 125 |
- **First Support (S1)**: Derived by doubling the pivot point and then subtracting the previous high.
|
|
@@ -134,7 +146,7 @@ if st.sidebar.button('Run'):
|
|
| 134 |
fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['S1'], mode='lines', name='Support 1', line=dict(dash='dash', color='green')))
|
| 135 |
fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['R2'], mode='lines', name='Resistance 2', line=dict(dash='dash', color='orange')))
|
| 136 |
fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['S2'], mode='lines', name='Support 2', line=dict(dash='dash', color='blue')))
|
| 137 |
-
fig1.update_layout(title=f'{ticker}
|
| 138 |
xaxis_title='Date',
|
| 139 |
yaxis_title='Price',
|
| 140 |
legend_title='Legend')
|
|
@@ -143,10 +155,10 @@ if st.sidebar.button('Run'):
|
|
| 143 |
# Plot Support and Resistance Levels using Rolling Midpoint Range
|
| 144 |
st.write("### Rolling Midpoint Range")
|
| 145 |
st.markdown("""
|
| 146 |
-
**Support and Resistance Levels**
|
| 147 |
- **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.
|
| 148 |
- **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.
|
| 149 |
-
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
|
| 150 |
""")
|
| 151 |
|
| 152 |
fig2 = go.Figure()
|
|
@@ -155,7 +167,7 @@ if st.sidebar.button('Run'):
|
|
| 155 |
fig2.add_trace(go.Scatter(x=data.index, y=resistance, mode='lines', name='Resistance', line=dict(dash='dash', color='red')))
|
| 156 |
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')))
|
| 157 |
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')))
|
| 158 |
-
fig2.update_layout(title=f'{ticker}
|
| 159 |
xaxis_title='Date',
|
| 160 |
yaxis_title='Price',
|
| 161 |
legend_title='Legend')
|
|
@@ -164,7 +176,7 @@ if st.sidebar.button('Run'):
|
|
| 164 |
# Plot Swing Highs and Lows
|
| 165 |
st.write("### Swing Highs and Lows")
|
| 166 |
st.markdown("""
|
| 167 |
-
**Swing Highs and Lows** are the highest and lowest points in the price action over a specified period.
|
| 168 |
- **Swing High**: A peak where the price is higher than the surrounding prices.
|
| 169 |
- **Swing Low**: A trough where the price is lower than the surrounding prices.
|
| 170 |
""")
|
|
@@ -204,13 +216,10 @@ if st.sidebar.button('Run'):
|
|
| 204 |
- **Upper Trendline**: Connects higher highs using linear regression to fit a line through these points. This line acts as a resistance level.
|
| 205 |
- **Lower Trendline**: Connects lower lows using linear regression to fit a line through these points. This line acts as a support level.
|
| 206 |
1. **Swing Highs and Lows Identification**: First, local maxima (swing highs) and minima (swing lows) are identified using a specified lookback period.
|
| 207 |
-
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.
|
| 208 |
-
3. **Visualization**: The trendlines are plotted along with the stock's closing prices
|
| 209 |
-
These trendlines help traders identify the overall trend direction and anticipate potential reversal points, enhancing their decision-making process.
|
| 210 |
""")
|
| 211 |
|
| 212 |
-
|
| 213 |
-
|
| 214 |
fig5 = go.Figure()
|
| 215 |
fig5.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Close'], mode='lines', name='Close Price'))
|
| 216 |
|
|
@@ -238,8 +247,6 @@ if st.sidebar.button('Run'):
|
|
| 238 |
- **High Volume Areas**: Indicate significant trading activity and can act as strong support or resistance levels.
|
| 239 |
""")
|
| 240 |
|
| 241 |
-
|
| 242 |
-
|
| 243 |
fig6, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(20, 5), gridspec_kw={'width_ratios': [3, 1]})
|
| 244 |
ax1.plot(data['Close'], label="Close Price")
|
| 245 |
current_price = data['Close'].iloc[-1]
|
|
@@ -272,8 +279,6 @@ if st.sidebar.button('Run'):
|
|
| 272 |
- **Clusters**: Represent different regimes or phases in the stock price movements.
|
| 273 |
""")
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
fig7 = go.Figure()
|
| 278 |
fig7.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close Price'))
|
| 279 |
for center in cluster_centers:
|
|
@@ -290,11 +295,10 @@ if st.sidebar.button('Run'):
|
|
| 290 |
else:
|
| 291 |
st.write("No data found for the given ticker and date range.")
|
| 292 |
|
| 293 |
-
|
| 294 |
hide_streamlit_style = """
|
| 295 |
<style>
|
| 296 |
#MainMenu {visibility: hidden;}
|
| 297 |
footer {visibility: hidden;}
|
| 298 |
</style>
|
| 299 |
"""
|
| 300 |
-
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|
|
|
|
| 5 |
import streamlit as st
|
| 6 |
from datetime import datetime, timedelta
|
| 7 |
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('Identifying 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 |
+
# More concise "How to Use" section in the sidebar
|
| 33 |
+
st.sidebar.markdown("""
|
| 34 |
+
1. **Enter Ticker**: Specify a stock ticker or crypto pair.
|
| 35 |
+
2. **Set Dates**: Choose the date range for analysis.
|
| 36 |
+
3. **Adjust Parameters**: Modify methodology parameters as needed.
|
| 37 |
+
4. **Run Analysis**: Click 'Run' to generate results.
|
| 38 |
+
""")
|
| 39 |
+
|
| 40 |
+
# Expander for ticker and date settings
|
| 41 |
+
with st.sidebar.expander("Ticker and Date Settings", expanded=True):
|
| 42 |
+
st.write("Specify the ticker and date range for analysis.")
|
| 43 |
+
ticker = st.text_input('Stock Ticker or Crypto Pair', 'AAPL', help="Enter stock ticker (e.g., AAPL) or crypto pair (e.g., BTC-USD).")
|
| 44 |
+
start_date = st.date_input('Start Date', pd.to_datetime('2023-01-01'))
|
| 45 |
+
end_date = st.date_input('End Date', datetime.now() + timedelta(days=1))
|
| 46 |
+
|
| 47 |
+
# Expander for methodology-specific parameters
|
| 48 |
+
with st.sidebar.expander("Pivot Points and Levels", expanded=True):
|
| 49 |
+
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.")
|
| 50 |
+
|
| 51 |
+
with st.sidebar.expander("Trendlines and Fibonacci Levels", expanded=True):
|
| 52 |
+
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.")
|
| 53 |
+
|
| 54 |
+
with st.sidebar.expander("Volume Profile and KMeans", expanded=True):
|
| 55 |
+
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.")
|
| 56 |
+
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.")
|
| 57 |
|
| 58 |
# Define functions for different analyses
|
| 59 |
def calculate_pivot_points(df, window):
|
|
|
|
| 103 |
cluster_centers = kmeans.cluster_centers_[:, 1] * (np.max(filtered_data['Close']) - np.min(filtered_data['Close'])) + np.min(filtered_data['Close'])
|
| 104 |
return cluster_centers
|
| 105 |
|
| 106 |
+
# Run the analysis
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
if st.sidebar.button('Run'):
|
| 108 |
data = yf.download(ticker, start=start_date, end=end_date)
|
| 109 |
|
|
|
|
| 131 |
# Plot Pivot Points
|
| 132 |
st.write("### Pivot Points")
|
| 133 |
st.markdown("""
|
| 134 |
+
**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).
|
| 135 |
- **Pivot Point (P)**: The average of the high, low, and close of the previous trading period.
|
| 136 |
- **First Resistance (R1)**: Calculated by doubling the pivot point and then subtracting the previous low.
|
| 137 |
- **First Support (S1)**: Derived by doubling the pivot point and then subtracting the previous high.
|
|
|
|
| 146 |
fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['S1'], mode='lines', name='Support 1', line=dict(dash='dash', color='green')))
|
| 147 |
fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['R2'], mode='lines', name='Resistance 2', line=dict(dash='dash', color='orange')))
|
| 148 |
fig1.add_trace(go.Scatter(x=df_pivot.index, y=df_pivot['S2'], mode='lines', name='Support 2', line=dict(dash='dash', color='blue')))
|
| 149 |
+
fig1.update_layout(title=f'{ticker} Price with Pivot Points and Support/Resistance Levels',
|
| 150 |
xaxis_title='Date',
|
| 151 |
yaxis_title='Price',
|
| 152 |
legend_title='Legend')
|
|
|
|
| 155 |
# Plot Support and Resistance Levels using Rolling Midpoint Range
|
| 156 |
st.write("### Rolling Midpoint Range")
|
| 157 |
st.markdown("""
|
| 158 |
+
**Support and Resistance Levels** This method uses a rolling window to identify these levels. This provides a dynamic approach to pinpointing key price levels.
|
| 159 |
- **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.
|
| 160 |
- **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.
|
| 161 |
+
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.
|
| 162 |
""")
|
| 163 |
|
| 164 |
fig2 = go.Figure()
|
|
|
|
| 167 |
fig2.add_trace(go.Scatter(x=data.index, y=resistance, mode='lines', name='Resistance', line=dict(dash='dash', color='red')))
|
| 168 |
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')))
|
| 169 |
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')))
|
| 170 |
+
fig2.update_layout(title=f'{ticker} Price with Support and Resistance Levels',
|
| 171 |
xaxis_title='Date',
|
| 172 |
yaxis_title='Price',
|
| 173 |
legend_title='Legend')
|
|
|
|
| 176 |
# Plot Swing Highs and Lows
|
| 177 |
st.write("### Swing Highs and Lows")
|
| 178 |
st.markdown("""
|
| 179 |
+
**Swing Highs and Lows** are the highest and lowest points in the price action over a specified period.
|
| 180 |
- **Swing High**: A peak where the price is higher than the surrounding prices.
|
| 181 |
- **Swing Low**: A trough where the price is lower than the surrounding prices.
|
| 182 |
""")
|
|
|
|
| 216 |
- **Upper Trendline**: Connects higher highs using linear regression to fit a line through these points. This line acts as a resistance level.
|
| 217 |
- **Lower Trendline**: Connects lower lows using linear regression to fit a line through these points. This line acts as a support level.
|
| 218 |
1. **Swing Highs and Lows Identification**: First, local maxima (swing highs) and minima (swing lows) are identified using a specified lookback period.
|
| 219 |
+
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.
|
| 220 |
+
3. **Visualization**: The trendlines are plotted along with the stock's closing prices to represent of potential resistance and support levels.
|
|
|
|
| 221 |
""")
|
| 222 |
|
|
|
|
|
|
|
| 223 |
fig5 = go.Figure()
|
| 224 |
fig5.add_trace(go.Scatter(x=data_with_trendlines.index, y=data_with_trendlines['Close'], mode='lines', name='Close Price'))
|
| 225 |
|
|
|
|
| 247 |
- **High Volume Areas**: Indicate significant trading activity and can act as strong support or resistance levels.
|
| 248 |
""")
|
| 249 |
|
|
|
|
|
|
|
| 250 |
fig6, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(20, 5), gridspec_kw={'width_ratios': [3, 1]})
|
| 251 |
ax1.plot(data['Close'], label="Close Price")
|
| 252 |
current_price = data['Close'].iloc[-1]
|
|
|
|
| 279 |
- **Clusters**: Represent different regimes or phases in the stock price movements.
|
| 280 |
""")
|
| 281 |
|
|
|
|
|
|
|
| 282 |
fig7 = go.Figure()
|
| 283 |
fig7.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close Price'))
|
| 284 |
for center in cluster_centers:
|
|
|
|
| 295 |
else:
|
| 296 |
st.write("No data found for the given ticker and date range.")
|
| 297 |
|
|
|
|
| 298 |
hide_streamlit_style = """
|
| 299 |
<style>
|
| 300 |
#MainMenu {visibility: hidden;}
|
| 301 |
footer {visibility: hidden;}
|
| 302 |
</style>
|
| 303 |
"""
|
| 304 |
+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|