Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import numpy as np
|
| 2 |
-
import pandas as pd
|
| 3 |
import yfinance as yf
|
|
|
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
import streamlit as st
|
| 6 |
from datetime import datetime, timedelta
|
|
@@ -9,7 +9,6 @@ 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 |
|
|
@@ -31,8 +30,6 @@ with st.expander("Click here to read the description of each method:", expanded=
|
|
| 31 |
# Sidebar: How to use and Input Parameters
|
| 32 |
st.sidebar.title('Input Parameters')
|
| 33 |
|
| 34 |
-
#st.sidebar.subheader('How to use:')
|
| 35 |
-
|
| 36 |
with st.sidebar.expander("How to use:", expanded=False):
|
| 37 |
st.markdown("""
|
| 38 |
1. **Enter Ticker**: Specify a stock ticker or crypto pair.
|
|
@@ -41,14 +38,12 @@ with st.sidebar.expander("How to use:", expanded=False):
|
|
| 41 |
4. **Run Analysis**: Click 'Run' to generate results.
|
| 42 |
""")
|
| 43 |
|
| 44 |
-
# Expander for ticker and date settings
|
| 45 |
with st.sidebar.expander("Ticker and Date Settings", expanded=True):
|
| 46 |
st.write("Specify the ticker and date range for analysis.")
|
| 47 |
ticker = st.text_input('Stock Ticker or Crypto Pair', 'AAPL', help="Enter stock ticker (e.g., AAPL) or crypto pair (e.g., BTC-USD).")
|
| 48 |
start_date = st.date_input('Start Date', pd.to_datetime('2023-01-01'))
|
| 49 |
end_date = st.date_input('End Date', datetime.now() + timedelta(days=1))
|
| 50 |
|
| 51 |
-
# Expander for methodology-specific parameters
|
| 52 |
with st.sidebar.expander("Pivot Points and Levels", expanded=True):
|
| 53 |
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.")
|
| 54 |
|
|
@@ -59,15 +54,24 @@ with st.sidebar.expander("Volume Profile and KMeans", expanded=True):
|
|
| 59 |
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.")
|
| 60 |
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.")
|
| 61 |
|
| 62 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
def calculate_pivot_points(df, window):
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
df['R2'] = (df['Pivot'] + (df['High'].rolling(window=window).max() - df['Low'].rolling(window=window).min())).squeeze()
|
| 69 |
-
df['S2'] = (df['Pivot'] - (df['High'].rolling(window=window).max() - df['Low'].rolling(window=window).min())).squeeze()
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
return df
|
| 72 |
|
| 73 |
def find_levels(data, window):
|
|
@@ -137,11 +141,11 @@ if st.sidebar.button('Run Analysis'):
|
|
| 137 |
# Plot Pivot Points
|
| 138 |
st.write("### Pivot Points")
|
| 139 |
st.markdown("""
|
| 140 |
-
**Pivot Points** are short-term trend indicators used to determine potential support and resistance levels
|
| 141 |
- **Pivot Point (P)**: The average of the high, low, and close of the previous trading period.
|
| 142 |
- **First Resistance (R1)**: Calculated by doubling the pivot point and then subtracting the previous low.
|
| 143 |
- **First Support (S1)**: Derived by doubling the pivot point and then subtracting the previous high.
|
| 144 |
-
- **Second Resistance (R2)**: Obtained by adding the
|
| 145 |
- **Second Support (S2)**: Found by subtracting the range from the pivot point.
|
| 146 |
""")
|
| 147 |
|
|
@@ -157,18 +161,15 @@ if st.sidebar.button('Run Analysis'):
|
|
| 157 |
xaxis_title='Date',
|
| 158 |
yaxis_title='Price',
|
| 159 |
legend_title='Legend',
|
| 160 |
-
width=1200,
|
| 161 |
-
height=600
|
| 162 |
)
|
| 163 |
st.plotly_chart(fig1, use_container_width=True)
|
| 164 |
|
| 165 |
# Plot Support and Resistance Levels using Rolling Midpoint Range
|
| 166 |
st.write("### Rolling Midpoint Range")
|
| 167 |
st.markdown("""
|
| 168 |
-
**Support and Resistance Levels**
|
| 169 |
-
- **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.
|
| 170 |
-
- **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.
|
| 171 |
-
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.
|
| 172 |
""")
|
| 173 |
|
| 174 |
fig2 = go.Figure()
|
|
@@ -182,8 +183,8 @@ if st.sidebar.button('Run Analysis'):
|
|
| 182 |
xaxis_title='Date',
|
| 183 |
yaxis_title='Price',
|
| 184 |
legend_title='Legend',
|
| 185 |
-
width=1200,
|
| 186 |
-
height=600
|
| 187 |
)
|
| 188 |
st.plotly_chart(fig2, use_container_width=True)
|
| 189 |
|
|
@@ -204,16 +205,15 @@ if st.sidebar.button('Run Analysis'):
|
|
| 204 |
xaxis_title='Date',
|
| 205 |
yaxis_title='Price',
|
| 206 |
legend_title='Legend',
|
| 207 |
-
width=1200,
|
| 208 |
-
height=600
|
| 209 |
)
|
| 210 |
st.plotly_chart(fig3, use_container_width=True)
|
| 211 |
|
| 212 |
# Plot Fibonacci Retracement Levels
|
| 213 |
st.write("### Fibonacci Retracement Levels")
|
| 214 |
st.markdown("""
|
| 215 |
-
**Fibonacci Retracement Levels** are horizontal lines
|
| 216 |
-
- **Levels**: 23.6%, 38.2%, 50%, 61.8%, and 78.6% represent key points where the price could potentially reverse.
|
| 217 |
""")
|
| 218 |
|
| 219 |
fig4 = go.Figure()
|
|
@@ -226,20 +226,15 @@ if st.sidebar.button('Run Analysis'):
|
|
| 226 |
xaxis_title='Date',
|
| 227 |
yaxis_title='Price',
|
| 228 |
legend_title='Legend',
|
| 229 |
-
width=1200,
|
| 230 |
-
height=600
|
| 231 |
)
|
| 232 |
st.plotly_chart(fig4, use_container_width=True)
|
| 233 |
|
| 234 |
# Plot Trendlines
|
| 235 |
st.write("### Trendlines with Regression Analysis")
|
| 236 |
st.markdown("""
|
| 237 |
-
**Trendlines** are
|
| 238 |
-
- **Upper Trendline**: Connects higher highs using linear regression to fit a line through these points. This line acts as a resistance level.
|
| 239 |
-
- **Lower Trendline**: Connects lower lows using linear regression to fit a line through these points. This line acts as a support level.
|
| 240 |
-
1. **Swing Highs and Lows Identification**: First, local maxima (swing highs) and minima (swing lows) are identified using a specified lookback period.
|
| 241 |
-
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.
|
| 242 |
-
3. **Visualization**: The trendlines are plotted along with the stock's closing prices to represent of potential resistance and support levels.
|
| 243 |
""")
|
| 244 |
|
| 245 |
fig5 = go.Figure()
|
|
@@ -261,16 +256,15 @@ if st.sidebar.button('Run Analysis'):
|
|
| 261 |
xaxis_title='Date',
|
| 262 |
yaxis_title='Price',
|
| 263 |
legend_title='Legend',
|
| 264 |
-
width=1200,
|
| 265 |
-
height=600
|
| 266 |
)
|
| 267 |
st.plotly_chart(fig5, use_container_width=True)
|
| 268 |
|
| 269 |
# Plot Volume Profile
|
| 270 |
st.write("### Volume Profile")
|
| 271 |
st.markdown("""
|
| 272 |
-
**Volume Profile**
|
| 273 |
-
- **High Volume Areas**: Indicate significant trading activity and can act as strong support or resistance levels.
|
| 274 |
""")
|
| 275 |
|
| 276 |
fig6, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(20, 5), gridspec_kw={'width_ratios': [3, 1]})
|
|
@@ -301,8 +295,7 @@ if st.sidebar.button('Run Analysis'):
|
|
| 301 |
# Plot KMeans Clusters
|
| 302 |
st.write("### KMeans Clusters")
|
| 303 |
st.markdown("""
|
| 304 |
-
**KMeans Clustering**
|
| 305 |
-
- **Clusters**: Represent different regimes or phases in the stock price movements.
|
| 306 |
""")
|
| 307 |
|
| 308 |
fig7 = go.Figure()
|
|
@@ -317,8 +310,8 @@ if st.sidebar.button('Run Analysis'):
|
|
| 317 |
xaxis_title='Date',
|
| 318 |
yaxis_title='Price',
|
| 319 |
legend_title='Legend',
|
| 320 |
-
width=1200,
|
| 321 |
-
height=600
|
| 322 |
)
|
| 323 |
st.plotly_chart(fig7, use_container_width=True)
|
| 324 |
|
|
@@ -331,4 +324,4 @@ hide_streamlit_style = """
|
|
| 331 |
footer {visibility: hidden;}
|
| 332 |
</style>
|
| 333 |
"""
|
| 334 |
-
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|
|
|
|
| 1 |
import numpy as np
|
|
|
|
| 2 |
import yfinance as yf
|
| 3 |
+
import pandas as pd
|
| 4 |
import plotly.graph_objects as go
|
| 5 |
import streamlit as st
|
| 6 |
from datetime import datetime, timedelta
|
|
|
|
| 9 |
import matplotlib.pyplot as plt
|
| 10 |
|
| 11 |
# Streamlit app
|
|
|
|
| 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 |
|
|
|
|
| 30 |
# Sidebar: How to use and Input Parameters
|
| 31 |
st.sidebar.title('Input Parameters')
|
| 32 |
|
|
|
|
|
|
|
| 33 |
with st.sidebar.expander("How to use:", expanded=False):
|
| 34 |
st.markdown("""
|
| 35 |
1. **Enter Ticker**: Specify a stock ticker or crypto pair.
|
|
|
|
| 38 |
4. **Run Analysis**: Click 'Run' to generate results.
|
| 39 |
""")
|
| 40 |
|
|
|
|
| 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 |
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 |
|
|
|
|
| 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 |
+
# --- Helper function to ensure a column is a Series ---
|
| 58 |
+
def get_series(col):
|
| 59 |
+
if isinstance(col, pd.DataFrame):
|
| 60 |
+
return col.iloc[:, 0]
|
| 61 |
+
return col
|
| 62 |
+
|
| 63 |
+
# Adjusted Pivot Points function
|
| 64 |
def calculate_pivot_points(df, window):
|
| 65 |
+
# Ensure each column is a Series
|
| 66 |
+
close = get_series(df['Close'])
|
| 67 |
+
low = get_series(df['Low'])
|
| 68 |
+
high = get_series(df['High'])
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
df['Pivot'] = close.rolling(window=window).mean()
|
| 71 |
+
df['R1'] = 2 * df['Pivot'] - low.rolling(window=window).min()
|
| 72 |
+
df['S1'] = 2 * df['Pivot'] - high.rolling(window=window).max()
|
| 73 |
+
df['R2'] = df['Pivot'] + (high.rolling(window=window).max() - low.rolling(window=window).min())
|
| 74 |
+
df['S2'] = df['Pivot'] - (high.rolling(window=window).max() - low.rolling(window=window).min())
|
| 75 |
return df
|
| 76 |
|
| 77 |
def find_levels(data, window):
|
|
|
|
| 141 |
# Plot Pivot Points
|
| 142 |
st.write("### Pivot Points")
|
| 143 |
st.markdown("""
|
| 144 |
+
**Pivot Points** are short-term trend indicators used to determine potential support and resistance levels based on the high, low, and close prices of previous periods.
|
| 145 |
- **Pivot Point (P)**: The average of the high, low, and close of the previous trading period.
|
| 146 |
- **First Resistance (R1)**: Calculated by doubling the pivot point and then subtracting the previous low.
|
| 147 |
- **First Support (S1)**: Derived by doubling the pivot point and then subtracting the previous high.
|
| 148 |
+
- **Second Resistance (R2)**: Obtained by adding the range (High - Low) to the pivot point.
|
| 149 |
- **Second Support (S2)**: Found by subtracting the range from the pivot point.
|
| 150 |
""")
|
| 151 |
|
|
|
|
| 161 |
xaxis_title='Date',
|
| 162 |
yaxis_title='Price',
|
| 163 |
legend_title='Legend',
|
| 164 |
+
width=1200,
|
| 165 |
+
height=600
|
| 166 |
)
|
| 167 |
st.plotly_chart(fig1, use_container_width=True)
|
| 168 |
|
| 169 |
# Plot Support and Resistance Levels using Rolling Midpoint Range
|
| 170 |
st.write("### Rolling Midpoint Range")
|
| 171 |
st.markdown("""
|
| 172 |
+
**Support and Resistance Levels** are determined using a rolling window approach to calculate the dynamic minimum (support) and maximum (resistance) prices over a given period.
|
|
|
|
|
|
|
|
|
|
| 173 |
""")
|
| 174 |
|
| 175 |
fig2 = go.Figure()
|
|
|
|
| 183 |
xaxis_title='Date',
|
| 184 |
yaxis_title='Price',
|
| 185 |
legend_title='Legend',
|
| 186 |
+
width=1200,
|
| 187 |
+
height=600
|
| 188 |
)
|
| 189 |
st.plotly_chart(fig2, use_container_width=True)
|
| 190 |
|
|
|
|
| 205 |
xaxis_title='Date',
|
| 206 |
yaxis_title='Price',
|
| 207 |
legend_title='Legend',
|
| 208 |
+
width=1200,
|
| 209 |
+
height=600
|
| 210 |
)
|
| 211 |
st.plotly_chart(fig3, use_container_width=True)
|
| 212 |
|
| 213 |
# Plot Fibonacci Retracement Levels
|
| 214 |
st.write("### Fibonacci Retracement Levels")
|
| 215 |
st.markdown("""
|
| 216 |
+
**Fibonacci Retracement Levels** are horizontal lines indicating potential support and resistance based on Fibonacci ratios.
|
|
|
|
| 217 |
""")
|
| 218 |
|
| 219 |
fig4 = go.Figure()
|
|
|
|
| 226 |
xaxis_title='Date',
|
| 227 |
yaxis_title='Price',
|
| 228 |
legend_title='Legend',
|
| 229 |
+
width=1200,
|
| 230 |
+
height=600
|
| 231 |
)
|
| 232 |
st.plotly_chart(fig4, use_container_width=True)
|
| 233 |
|
| 234 |
# Plot Trendlines
|
| 235 |
st.write("### Trendlines with Regression Analysis")
|
| 236 |
st.markdown("""
|
| 237 |
+
**Trendlines** are drawn using regression on swing highs and lows to indicate potential support and resistance.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
""")
|
| 239 |
|
| 240 |
fig5 = go.Figure()
|
|
|
|
| 256 |
xaxis_title='Date',
|
| 257 |
yaxis_title='Price',
|
| 258 |
legend_title='Legend',
|
| 259 |
+
width=1200,
|
| 260 |
+
height=600
|
| 261 |
)
|
| 262 |
st.plotly_chart(fig5, use_container_width=True)
|
| 263 |
|
| 264 |
# Plot Volume Profile
|
| 265 |
st.write("### Volume Profile")
|
| 266 |
st.markdown("""
|
| 267 |
+
**Volume Profile** shows the amount of volume traded at different price levels over a specified period.
|
|
|
|
| 268 |
""")
|
| 269 |
|
| 270 |
fig6, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(20, 5), gridspec_kw={'width_ratios': [3, 1]})
|
|
|
|
| 295 |
# Plot KMeans Clusters
|
| 296 |
st.write("### KMeans Clusters")
|
| 297 |
st.markdown("""
|
| 298 |
+
**KMeans Clustering** partitions the price data into clusters to identify significant price levels.
|
|
|
|
| 299 |
""")
|
| 300 |
|
| 301 |
fig7 = go.Figure()
|
|
|
|
| 310 |
xaxis_title='Date',
|
| 311 |
yaxis_title='Price',
|
| 312 |
legend_title='Legend',
|
| 313 |
+
width=1200,
|
| 314 |
+
height=600
|
| 315 |
)
|
| 316 |
st.plotly_chart(fig7, use_container_width=True)
|
| 317 |
|
|
|
|
| 324 |
footer {visibility: hidden;}
|
| 325 |
</style>
|
| 326 |
"""
|
| 327 |
+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|