Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,6 +8,7 @@ from scipy.spatial.distance import euclidean
|
|
| 8 |
import ta
|
| 9 |
from sklearn.decomposition import PCA
|
| 10 |
from sklearn.impute import SimpleImputer
|
|
|
|
| 11 |
|
| 12 |
# Function to normalize the time series
|
| 13 |
def normalize(ts):
|
|
@@ -104,20 +105,30 @@ def extract_and_reduce_features(data, n_components=3):
|
|
| 104 |
st.set_page_config(page_title="Pattern Recognition", layout="wide")
|
| 105 |
st.title('Pattern Recognition in Stock Prices')
|
| 106 |
|
| 107 |
-
|
| 108 |
# Sidebar for method selection
|
| 109 |
-
st.sidebar.
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
if 'data' not in st.session_state:
|
| 122 |
st.session_state.data = None
|
| 123 |
if 'price_data_pct_change' not in st.session_state:
|
|
@@ -294,11 +305,8 @@ if st.sidebar.button('Run'):
|
|
| 294 |
if selected == "DTW Pattern Recognition":
|
| 295 |
st.markdown("""
|
| 296 |
### DTW Pattern Recognition
|
| 297 |
-
|
| 298 |
Dynamic Time Warping (DTW) is a method that measures the similarity between two time series that may vary in time or speed. DTW aligns the time series by warping the time axis to minimize the distance between them. This method could potentially identify historical periods that have similar patterns to the current stock price pattern by comparing their shapes, regardless of possible distortions in the time axis.
|
| 299 |
-
|
| 300 |
The DTW distance \( D \) between two time series \( X \) and \( Y \) is calculated as:
|
| 301 |
-
|
| 302 |
""")
|
| 303 |
st.latex(r'''
|
| 304 |
D(i, j) = \text{dist}(X_i, Y_j) + \min \begin{cases}
|
|
@@ -308,13 +316,7 @@ if selected == "DTW Pattern Recognition":
|
|
| 308 |
\end{cases}
|
| 309 |
''')
|
| 310 |
st.markdown("""
|
| 311 |
-
where {dist}(
|
| 312 |
-
|
| 313 |
-
**How to use:**
|
| 314 |
-
1. Enter the stock ticker, start date, and end date.
|
| 315 |
-
2. Select the number of subsequent days to observe (forecast). This parameter determines how many days into the future you want to observe after identifying a similar historical pattern. For example, if you set it to 20, the app will show the stock price movements for 20 days following the identified pattern.
|
| 316 |
-
3. Select the number of days to compare and find patterns. Choose one or more time periods (in days) to compare against the current pattern. For instance, you might select 15, 20, and 40 days. The app will look for historical patterns of these lengths that match the current stock price pattern.
|
| 317 |
-
4. Click the 'Run' button.
|
| 318 |
|
| 319 |
**Results:**
|
| 320 |
The left chart shows the entire stock price data with the identified patterns highlighted. The right chart shows the reindexed price patterns for comparison.
|
|
@@ -330,11 +332,8 @@ if selected == "DTW Pattern Recognition":
|
|
| 330 |
elif selected == "Correlation Pattern Recognition":
|
| 331 |
st.markdown("""
|
| 332 |
### Correlation Pattern Recognition
|
| 333 |
-
|
| 334 |
This method calculates the correlation between the current stock price pattern and historical patterns. Correlation measures the degree to which two time series move together. A higher correlation value indicates that the patterns are more similar. This method helps identify historical periods where stock prices behaved similarly to the current pattern by looking at how closely the price movements align.
|
| 335 |
-
|
| 336 |
The correlation coefficient \( r \) is calculated as:
|
| 337 |
-
|
| 338 |
""")
|
| 339 |
st.latex(r'''
|
| 340 |
r = \frac{ \sum (X_i - \bar{X})(Y_i - \bar{Y}) }{ \sqrt{ \sum (X_i - \bar{X})^2 } \sqrt{ \sum (Y_i - \bar{Y})^2 } }
|
|
@@ -342,13 +341,6 @@ elif selected == "Correlation Pattern Recognition":
|
|
| 342 |
st.markdown("""
|
| 343 |
where \( X \) and \( Y \) are the two time series being compared.
|
| 344 |
|
| 345 |
-
**How to use:**
|
| 346 |
-
1. Enter the stock ticker, start date, and end date.
|
| 347 |
-
2. Select the number of subsequent days to observe (forecast). This parameter determines how many days into the future you want to observe after identifying a similar historical pattern. For example, if you set it to 20, the app will show the stock price movements for 20 days following the identified pattern.
|
| 348 |
-
3. Select the number of days to compare.
|
| 349 |
-
4. Select the number of days prior to the similar series. This parameter is used to set the number of days before the start of the similar pattern for additional context.
|
| 350 |
-
5. Click the 'Run' button.
|
| 351 |
-
|
| 352 |
**Results:**
|
| 353 |
The left chart shows the entire stock price data with the identified patterns highlighted. The right chart shows the reindexed price patterns for comparison.
|
| 354 |
""")
|
|
@@ -363,11 +355,8 @@ elif selected == "Correlation Pattern Recognition":
|
|
| 363 |
elif selected == "TA-Enhanced DTW Pattern Recognition":
|
| 364 |
st.markdown("""
|
| 365 |
### TA-Enhanced DTW Pattern Recognition
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
Additionally, Principal Component Analysis (PCA) is used to reduce the dimensionality of the TA features. PCA transforms the TA indicators into a smaller set of uncorrelated components, capturing the most significant information with fewer variables. This reduction helps in efficiently processing the data and improving the accuracy of pattern recognition.
|
| 370 |
-
|
| 371 |
The method uses a weighted mechanism to combine the DTW distance of the price changes and the TA features. The formula is:
|
| 372 |
""")
|
| 373 |
st.latex(r'''
|
|
@@ -376,12 +365,6 @@ elif selected == "TA-Enhanced DTW Pattern Recognition":
|
|
| 376 |
st.markdown("""
|
| 377 |
where \( w \) is a weight factor that balances the contribution of price changes and TA features.
|
| 378 |
|
| 379 |
-
**How to use:**
|
| 380 |
-
1. Enter the stock ticker, start date, and end date.
|
| 381 |
-
2. Select the number of subsequent days to observe (forecast). This parameter determines how many days into the future you want to observe after identifying a similar historical pattern. For example, if you set it to 20, the app will show the stock price movements for 20 days following the identified pattern.
|
| 382 |
-
3. Select the number of days to compare. Choose one or more time periods (in days) to compare against the current pattern. For instance, you might select 15, 20, and 40 days. The app will look for historical patterns of these lengths that match the current stock price pattern.
|
| 383 |
-
4. Click the 'Run' button.
|
| 384 |
-
|
| 385 |
**Results:**
|
| 386 |
The left chart shows the entire stock price data with the identified patterns highlighted. The right chart shows the reindexed price patterns for comparison.
|
| 387 |
""")
|
|
@@ -393,10 +376,11 @@ elif selected == "TA-Enhanced DTW Pattern Recognition":
|
|
| 393 |
with col2:
|
| 394 |
st.plotly_chart(fig2)
|
| 395 |
|
|
|
|
| 396 |
hide_streamlit_style = """
|
| 397 |
<style>
|
| 398 |
#MainMenu {visibility: hidden;}
|
| 399 |
footer {visibility: hidden;}
|
| 400 |
</style>
|
| 401 |
"""
|
| 402 |
-
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|
|
|
|
| 8 |
import ta
|
| 9 |
from sklearn.decomposition import PCA
|
| 10 |
from sklearn.impute import SimpleImputer
|
| 11 |
+
from datetime import datetime, timedelta
|
| 12 |
|
| 13 |
# Function to normalize the time series
|
| 14 |
def normalize(ts):
|
|
|
|
| 105 |
st.set_page_config(page_title="Pattern Recognition", layout="wide")
|
| 106 |
st.title('Pattern Recognition in Stock Prices')
|
| 107 |
|
|
|
|
| 108 |
# Sidebar for method selection
|
| 109 |
+
st.sidebar.title("Input Parameters")
|
| 110 |
+
st.sidebar.subheader("How to Use")
|
| 111 |
+
st.sidebar.markdown("""
|
| 112 |
+
1. Select the pattern recognition method you want to use.
|
| 113 |
+
2. Set the stock ticker, date range, and other parameters.
|
| 114 |
+
3. Click 'Run' to perform the analysis.
|
| 115 |
+
""")
|
| 116 |
+
|
| 117 |
+
# Grouping and expanding sidebar options with tooltips
|
| 118 |
+
with st.sidebar.expander("Pattern Recognition Methods", expanded=True):
|
| 119 |
+
selected = st.radio("Choose a method:",
|
| 120 |
+
["DTW Pattern Recognition", "Correlation Pattern Recognition", "TA-Enhanced DTW Pattern Recognition"],
|
| 121 |
+
help="Select the pattern recognition method you want to use.")
|
| 122 |
+
|
| 123 |
+
with st.sidebar.expander("Input Parameters", expanded=True):
|
| 124 |
+
ticker = st.text_input('Enter Stock Ticker', 'ASML.AS', help="Input the stock ticker (e.g., AAPL, TSLA).")
|
| 125 |
+
start_date = st.date_input('Start Date', pd.to_datetime('2000-01-01'), help="Select the start date for the analysis.")
|
| 126 |
+
end_date = st.date_input('End Date', datetime.now() + timedelta(days=1), help="Select the end date for the analysis.")
|
| 127 |
+
subsequent_days = st.slider('Subsequent Days to Forecast', min_value=5, max_value=60, value=20, step=5, help="Number of days to forecast after identifying similar patterns.")
|
| 128 |
+
n_days_options = st.multiselect('Days to Compare', options=[15, 20, 30, 40, 50], default=[15, 20, 40], help="Select the days to compare against the current pattern.")
|
| 129 |
+
pre_days = st.slider('Days Prior to Similar Series', min_value=10, max_value=100, value=60, step=10, help="Number of days prior to the similar series for additional context.")
|
| 130 |
+
|
| 131 |
+
# Initialize session state variables
|
| 132 |
if 'data' not in st.session_state:
|
| 133 |
st.session_state.data = None
|
| 134 |
if 'price_data_pct_change' not in st.session_state:
|
|
|
|
| 305 |
if selected == "DTW Pattern Recognition":
|
| 306 |
st.markdown("""
|
| 307 |
### DTW Pattern Recognition
|
|
|
|
| 308 |
Dynamic Time Warping (DTW) is a method that measures the similarity between two time series that may vary in time or speed. DTW aligns the time series by warping the time axis to minimize the distance between them. This method could potentially identify historical periods that have similar patterns to the current stock price pattern by comparing their shapes, regardless of possible distortions in the time axis.
|
|
|
|
| 309 |
The DTW distance \( D \) between two time series \( X \) and \( Y \) is calculated as:
|
|
|
|
| 310 |
""")
|
| 311 |
st.latex(r'''
|
| 312 |
D(i, j) = \text{dist}(X_i, Y_j) + \min \begin{cases}
|
|
|
|
| 316 |
\end{cases}
|
| 317 |
''')
|
| 318 |
st.markdown("""
|
| 319 |
+
where {dist}(Xi, Yj) is the distance between points (Xi) and (Yj), and D(i, j) is the accumulated cost.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
|
| 321 |
**Results:**
|
| 322 |
The left chart shows the entire stock price data with the identified patterns highlighted. The right chart shows the reindexed price patterns for comparison.
|
|
|
|
| 332 |
elif selected == "Correlation Pattern Recognition":
|
| 333 |
st.markdown("""
|
| 334 |
### Correlation Pattern Recognition
|
|
|
|
| 335 |
This method calculates the correlation between the current stock price pattern and historical patterns. Correlation measures the degree to which two time series move together. A higher correlation value indicates that the patterns are more similar. This method helps identify historical periods where stock prices behaved similarly to the current pattern by looking at how closely the price movements align.
|
|
|
|
| 336 |
The correlation coefficient \( r \) is calculated as:
|
|
|
|
| 337 |
""")
|
| 338 |
st.latex(r'''
|
| 339 |
r = \frac{ \sum (X_i - \bar{X})(Y_i - \bar{Y}) }{ \sqrt{ \sum (X_i - \bar{X})^2 } \sqrt{ \sum (Y_i - \bar{Y})^2 } }
|
|
|
|
| 341 |
st.markdown("""
|
| 342 |
where \( X \) and \( Y \) are the two time series being compared.
|
| 343 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
**Results:**
|
| 345 |
The left chart shows the entire stock price data with the identified patterns highlighted. The right chart shows the reindexed price patterns for comparison.
|
| 346 |
""")
|
|
|
|
| 355 |
elif selected == "TA-Enhanced DTW Pattern Recognition":
|
| 356 |
st.markdown("""
|
| 357 |
### TA-Enhanced DTW Pattern Recognition
|
| 358 |
+
This method combines technical analysis features with Dynamic Time Warping to enhance pattern recognition. It integrates various indicators such as moving averages, momentum indicators, and volatility measures into the time series data. These indicators provide additional context to the price movements.
|
| 359 |
+
Additionally, Principal Component Analysis (PCA) is used to reduce the dimensionality of the features. PCA transforms the indicators into a smaller set of uncorrelated components, capturing the most significant information with fewer variables.
|
|
|
|
|
|
|
|
|
|
| 360 |
The method uses a weighted mechanism to combine the DTW distance of the price changes and the TA features. The formula is:
|
| 361 |
""")
|
| 362 |
st.latex(r'''
|
|
|
|
| 365 |
st.markdown("""
|
| 366 |
where \( w \) is a weight factor that balances the contribution of price changes and TA features.
|
| 367 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
**Results:**
|
| 369 |
The left chart shows the entire stock price data with the identified patterns highlighted. The right chart shows the reindexed price patterns for comparison.
|
| 370 |
""")
|
|
|
|
| 376 |
with col2:
|
| 377 |
st.plotly_chart(fig2)
|
| 378 |
|
| 379 |
+
# Hide Streamlit style
|
| 380 |
hide_streamlit_style = """
|
| 381 |
<style>
|
| 382 |
#MainMenu {visibility: hidden;}
|
| 383 |
footer {visibility: hidden;}
|
| 384 |
</style>
|
| 385 |
"""
|
| 386 |
+
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
|