Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -179,85 +179,6 @@ st.title('Pairs Cointegration and Trading Analysis')
|
|
| 179 |
st.sidebar.header('Select Page')
|
| 180 |
page = st.sidebar.radio('Page:', ['Pair Cointegration Identification', 'Pairs Trading Analysis'])
|
| 181 |
|
| 182 |
-
if page == 'Pair Cointegration Identification':
|
| 183 |
-
st.subheader("Cointegration Identification")
|
| 184 |
-
st.write("""
|
| 185 |
-
### Description
|
| 186 |
-
This method identifies cointegrated pairs using two methods: Engle-Granger and Johansen Cointegration tests.
|
| 187 |
-
It works for both stocks and cryptocurrency pairs.
|
| 188 |
-
""")
|
| 189 |
-
|
| 190 |
-
# Cointegration Method Selection
|
| 191 |
-
method = st.sidebar.selectbox('Select Cointegration Method', ['Engle-Granger', 'Johansen Cointegration'])
|
| 192 |
-
|
| 193 |
-
# Expander for stock/crypto ticker and date selection
|
| 194 |
-
with st.sidebar.expander("Stock/Crypto Ticker and Date Selection", expanded=True):
|
| 195 |
-
tickers_input = st.text_input('Enter Stock or Crypto Tickers (comma-separated)', ', '.join(default_tickers), help="Enter the ticker symbols for stocks or cryptocurrencies you want to analyze.")
|
| 196 |
-
start_date = st.date_input('Start Date', pd.to_datetime(START_DATE), help="Select the start date for the data range.")
|
| 197 |
-
end_date = st.date_input('End Date', pd.to_datetime(END_DATE), help="Select the end date for the data range.")
|
| 198 |
-
|
| 199 |
-
# Expander for parameters specific to each method
|
| 200 |
-
with st.sidebar.expander("Method Parameters", expanded=True):
|
| 201 |
-
st.write("Set parameters for the selected method.")
|
| 202 |
-
|
| 203 |
-
if st.sidebar.button('Run Cointegration Analysis'):
|
| 204 |
-
tickers = [ticker.strip() for ticker in tickers_input.split(',')]
|
| 205 |
-
universe_tickers_ts_map = {ticker: load_ticker_ts_df(ticker, start_date, end_date) for ticker in tickers}
|
| 206 |
-
uts_sanitized = sanitize_data(universe_tickers_ts_map)
|
| 207 |
-
|
| 208 |
-
if method == 'Engle-Granger':
|
| 209 |
-
# Find cointegrated pairs using the Engle-Granger method
|
| 210 |
-
pvalues, pairs = find_cointegrated_pairs(uts_sanitized, P_VALUE_THRESHOLD)
|
| 211 |
-
# Mask values greater than P_VALUE_THRESHOLD
|
| 212 |
-
masked_pvalues = np.where(pvalues > P_VALUE_THRESHOLD, np.nan, pvalues)
|
| 213 |
-
# Plot heatmap of p-values
|
| 214 |
-
tickers_list = list(uts_sanitized.keys())
|
| 215 |
-
fig_heatmap = px.imshow(masked_pvalues, x=tickers_list, y=tickers_list,
|
| 216 |
-
color_continuous_scale='RdYlGn_r', title='Cointegration Heatmap (Engle-Granger)',
|
| 217 |
-
labels=dict(x='Tickers', y='Tickers', color='P-value'),
|
| 218 |
-
zmin=0, zmax=P_VALUE_THRESHOLD)
|
| 219 |
-
else:
|
| 220 |
-
# Find cointegrated pairs using the Johansen method with rolling windows
|
| 221 |
-
pvalues, pairs = find_cointegrated_pairs_rolling(uts_sanitized, P_VALUE_THRESHOLD, ROLLING_WINDOW_SIZE, CONSISTENT_COINTEGRATION_THRESHOLD)
|
| 222 |
-
# Mask values greater than P_VALUE_THRESHOLD
|
| 223 |
-
masked_pvalues = np.where(pvalues > P_VALUE_THRESHOLD, np.nan, pvalues)
|
| 224 |
-
# Plot heatmap of p-values
|
| 225 |
-
tickers_list = list(uts_sanitized.keys())
|
| 226 |
-
fig_heatmap = px.imshow(masked_pvalues, x=tickers_list, y=tickers_list,
|
| 227 |
-
color_continuous_scale='RdYlGn_r', title='Cointegration Heatmap (Johansen)',
|
| 228 |
-
labels=dict(x='Tickers', y='Tickers', color='P-value'),
|
| 229 |
-
zmin=0, zmax=P_VALUE_THRESHOLD)
|
| 230 |
-
|
| 231 |
-
st.plotly_chart(fig_heatmap)
|
| 232 |
-
|
| 233 |
-
# Sort pairs by p-value (ascending) and select the top 10
|
| 234 |
-
top_10_pairs = sorted(pairs, key=lambda x: x[2])[:10]
|
| 235 |
-
|
| 236 |
-
# Extract data for the bar plot
|
| 237 |
-
pair_labels = [f"{pair[0]} & {pair[1]}" for pair in top_10_pairs]
|
| 238 |
-
pair_values = [pair[2] for pair in top_10_pairs]
|
| 239 |
-
|
| 240 |
-
# Plot bar chart
|
| 241 |
-
fig_bar = go.Figure([go.Bar(x=pair_values, y=pair_labels, orientation='h')])
|
| 242 |
-
fig_bar.update_layout(title='Top 10 Most Cointegrated Pairs',
|
| 243 |
-
xaxis_title='P-value',
|
| 244 |
-
yaxis_title='Asset Pairs',
|
| 245 |
-
yaxis=dict(autorange='reversed'))
|
| 246 |
-
st.plotly_chart(fig_bar)
|
| 247 |
-
|
| 248 |
-
# Expander for "How it Works" inside the main body
|
| 249 |
-
with st.expander("How it Works", expanded=False):
|
| 250 |
-
st.markdown("""
|
| 251 |
-
**Cointegration Overview:**
|
| 252 |
-
- Cointegration is a statistical property of a collection of time series variables. Two or more series are cointegrated if they share a common stochastic drift.
|
| 253 |
-
|
| 254 |
-
**Engle-Granger Method:**
|
| 255 |
-
- This method involves estimating a long-term equilibrium relationship between two non-stationary series and testing whether the residuals from this relationship are stationary.
|
| 256 |
-
|
| 257 |
-
**Johansen Method:**
|
| 258 |
-
- The Johansen test is a more general procedure that allows for more than two series and can identify multiple cointegrating relationships.
|
| 259 |
-
""")
|
| 260 |
-
|
| 261 |
elif page == 'Pairs Trading Analysis':
|
| 262 |
st.subheader("Pairs Trading Analysis")
|
| 263 |
|
|
@@ -265,6 +186,12 @@ elif page == 'Pairs Trading Analysis':
|
|
| 265 |
### Description
|
| 266 |
This method analyzes stock and cryptocurrency prices, normalizes them, calculates rolling volatilities, tests for cointegration, and visualizes buy/sell signals based on z-scores.
|
| 267 |
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
# Expander for stock/crypto ticker and date selection
|
| 270 |
with st.sidebar.expander("Stock/Crypto Ticker and Date Selection", expanded=True):
|
|
@@ -534,6 +461,87 @@ elif page == 'Pairs Trading Analysis':
|
|
| 534 |
- The cumulative profit shows the total profit from the trading strategy over the analyzed period.
|
| 535 |
""")
|
| 536 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 537 |
# Hide the default Streamlit menu and footer
|
| 538 |
hide_streamlit_style = """
|
| 539 |
<style>
|
|
|
|
| 179 |
st.sidebar.header('Select Page')
|
| 180 |
page = st.sidebar.radio('Page:', ['Pair Cointegration Identification', 'Pairs Trading Analysis'])
|
| 181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
elif page == 'Pairs Trading Analysis':
|
| 183 |
st.subheader("Pairs Trading Analysis")
|
| 184 |
|
|
|
|
| 186 |
### Description
|
| 187 |
This method analyzes stock and cryptocurrency prices, normalizes them, calculates rolling volatilities, tests for cointegration, and visualizes buy/sell signals based on z-scores.
|
| 188 |
""")
|
| 189 |
+
with st.sidebar.expander("How to use:", expanded=False):
|
| 190 |
+
st.markdown("""**How to use:**
|
| 191 |
+
1. Enter the stock tickers, start date, and end date.
|
| 192 |
+
2. Set the number of days for the volatility window, and the buy/sell thresholds for the z-scores.
|
| 193 |
+
3. Click 'Run Analysis' to start the analysis.
|
| 194 |
+
""")
|
| 195 |
|
| 196 |
# Expander for stock/crypto ticker and date selection
|
| 197 |
with st.sidebar.expander("Stock/Crypto Ticker and Date Selection", expanded=True):
|
|
|
|
| 461 |
- The cumulative profit shows the total profit from the trading strategy over the analyzed period.
|
| 462 |
""")
|
| 463 |
|
| 464 |
+
elif page == 'Pair Cointegration Identification':
|
| 465 |
+
st.subheader("Cointegration Identification")
|
| 466 |
+
st.write("""
|
| 467 |
+
### Description
|
| 468 |
+
This method identifies cointegrated pairs using two methods: Engle-Granger and Johansen Cointegration tests.
|
| 469 |
+
It works for both stocks and cryptocurrency pairs.
|
| 470 |
+
""")
|
| 471 |
+
|
| 472 |
+
# Cointegration Method Selection
|
| 473 |
+
method = st.sidebar.selectbox('Select Cointegration Method', ['Engle-Granger', 'Johansen Cointegration'])
|
| 474 |
+
|
| 475 |
+
# Expander for stock/crypto ticker and date selection
|
| 476 |
+
with st.sidebar.expander("Stock/Crypto Ticker and Date Selection", expanded=True):
|
| 477 |
+
tickers_input = st.text_input('Enter Stock or Crypto Tickers (comma-separated)', ', '.join(default_tickers), help="Enter the ticker symbols for stocks or cryptocurrencies you want to analyze.")
|
| 478 |
+
start_date = st.date_input('Start Date', pd.to_datetime(START_DATE), help="Select the start date for the data range.")
|
| 479 |
+
end_date = st.date_input('End Date', pd.to_datetime(END_DATE), help="Select the end date for the data range.")
|
| 480 |
+
|
| 481 |
+
# Expander for parameters specific to each method
|
| 482 |
+
with st.sidebar.expander("Method Parameters", expanded=True):
|
| 483 |
+
st.write("Set parameters for the selected method.")
|
| 484 |
+
|
| 485 |
+
if st.sidebar.button('Run Cointegration Analysis'):
|
| 486 |
+
tickers = [ticker.strip() for ticker in tickers_input.split(',')]
|
| 487 |
+
universe_tickers_ts_map = {ticker: load_ticker_ts_df(ticker, start_date, end_date) for ticker in tickers}
|
| 488 |
+
uts_sanitized = sanitize_data(universe_tickers_ts_map)
|
| 489 |
+
|
| 490 |
+
if method == 'Engle-Granger':
|
| 491 |
+
# Find cointegrated pairs using the Engle-Granger method
|
| 492 |
+
pvalues, pairs = find_cointegrated_pairs(uts_sanitized, P_VALUE_THRESHOLD)
|
| 493 |
+
# Mask values greater than P_VALUE_THRESHOLD
|
| 494 |
+
masked_pvalues = np.where(pvalues > P_VALUE_THRESHOLD, np.nan, pvalues)
|
| 495 |
+
# Plot heatmap of p-values
|
| 496 |
+
tickers_list = list(uts_sanitized.keys())
|
| 497 |
+
fig_heatmap = px.imshow(masked_pvalues, x=tickers_list, y=tickers_list,
|
| 498 |
+
color_continuous_scale='RdYlGn_r', title='Cointegration Heatmap (Engle-Granger)',
|
| 499 |
+
labels=dict(x='Tickers', y='Tickers', color='P-value'),
|
| 500 |
+
zmin=0, zmax=P_VALUE_THRESHOLD)
|
| 501 |
+
else:
|
| 502 |
+
# Find cointegrated pairs using the Johansen method with rolling windows
|
| 503 |
+
pvalues, pairs = find_cointegrated_pairs_rolling(uts_sanitized, P_VALUE_THRESHOLD, ROLLING_WINDOW_SIZE, CONSISTENT_COINTEGRATION_THRESHOLD)
|
| 504 |
+
# Mask values greater than P_VALUE_THRESHOLD
|
| 505 |
+
masked_pvalues = np.where(pvalues > P_VALUE_THRESHOLD, np.nan, pvalues)
|
| 506 |
+
# Plot heatmap of p-values
|
| 507 |
+
tickers_list = list(uts_sanitized.keys())
|
| 508 |
+
fig_heatmap = px.imshow(masked_pvalues, x=tickers_list, y=tickers_list,
|
| 509 |
+
color_continuous_scale='RdYlGn_r', title='Cointegration Heatmap (Johansen)',
|
| 510 |
+
labels=dict(x='Tickers', y='Tickers', color='P-value'),
|
| 511 |
+
zmin=0, zmax=P_VALUE_THRESHOLD)
|
| 512 |
+
|
| 513 |
+
st.plotly_chart(fig_heatmap)
|
| 514 |
+
|
| 515 |
+
# Sort pairs by p-value (ascending) and select the top 10
|
| 516 |
+
top_10_pairs = sorted(pairs, key=lambda x: x[2])[:10]
|
| 517 |
+
|
| 518 |
+
# Extract data for the bar plot
|
| 519 |
+
pair_labels = [f"{pair[0]} & {pair[1]}" for pair in top_10_pairs]
|
| 520 |
+
pair_values = [pair[2] for pair in top_10_pairs]
|
| 521 |
+
|
| 522 |
+
# Plot bar chart
|
| 523 |
+
fig_bar = go.Figure([go.Bar(x=pair_values, y=pair_labels, orientation='h')])
|
| 524 |
+
fig_bar.update_layout(title='Top 10 Most Cointegrated Pairs',
|
| 525 |
+
xaxis_title='P-value',
|
| 526 |
+
yaxis_title='Asset Pairs',
|
| 527 |
+
yaxis=dict(autorange='reversed'))
|
| 528 |
+
st.plotly_chart(fig_bar)
|
| 529 |
+
|
| 530 |
+
# Expander for "How it Works" inside the main body
|
| 531 |
+
with st.expander("How it Works", expanded=False):
|
| 532 |
+
st.markdown("""
|
| 533 |
+
**Cointegration Overview:**
|
| 534 |
+
- Cointegration is a statistical property of a collection of time series variables. Two or more series are cointegrated if they share a common stochastic drift.
|
| 535 |
+
|
| 536 |
+
**Engle-Granger Method:**
|
| 537 |
+
- This method involves estimating a long-term equilibrium relationship between two non-stationary series and testing whether the residuals from this relationship are stationary.
|
| 538 |
+
|
| 539 |
+
**Johansen Method:**
|
| 540 |
+
- The Johansen test is a more general procedure that allows for more than two series and can identify multiple cointegrating relationships.
|
| 541 |
+
""")
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
|
| 545 |
# Hide the default Streamlit menu and footer
|
| 546 |
hide_streamlit_style = """
|
| 547 |
<style>
|