QuantumLearner commited on
Commit
c097013
·
verified ·
1 Parent(s): 1aa4c7f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -25
app.py CHANGED
@@ -16,7 +16,7 @@ import plotly.express as px
16
 
17
  # Parameters
18
  START_DATE = '2021-01-01'
19
- END_DATE = '2023-09-30'
20
  P_VALUE_THRESHOLD = 0.05
21
  ROLLING_WINDOW_SIZE = 252
22
  CONSISTENT_COINTEGRATION_THRESHOLD = 0.8
@@ -183,16 +183,22 @@ if page == 'Pair Cointegration Identification':
183
  st.subheader("Cointegration Identification")
184
  st.write("""
185
  ### Description
186
- This tool method identifies cointegrated pairs using two methods: Engle-Granger and Johansen Cointegration tests.
 
187
  """)
188
 
189
  # Cointegration Method Selection
190
  method = st.sidebar.selectbox('Select Cointegration Method', ['Engle-Granger', 'Johansen Cointegration'])
191
 
192
- # Input fields for cointegration
193
- tickers_input = st.sidebar.text_input('Enter Stock Tickers (comma-separated)', ', '.join(default_tickers))
194
- start_date = st.sidebar.date_input('Start Date', pd.to_datetime(START_DATE))
195
- end_date = st.sidebar.date_input('End Date', pd.to_datetime(END_DATE))
 
 
 
 
 
196
 
197
  if st.sidebar.button('Run Cointegration Analysis'):
198
  tickers = [ticker.strip() for ticker in tickers_input.split(',')]
@@ -239,28 +245,39 @@ if page == 'Pair Cointegration Identification':
239
  yaxis=dict(autorange='reversed'))
240
  st.plotly_chart(fig_bar)
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  elif page == 'Pairs Trading Analysis':
243
  st.subheader("Pairs Trading Analysis")
244
 
245
  st.write("""
246
  ### Description
247
- This tool method analyzes stock prices, normalizes them, calculates rolling volatilities, tests for cointegration, and visualizes buy/sell signals based on z-scores.
248
- You can specify the stock tickers, the date range, and parameters for the analysis.
249
-
250
- **How to use:**
251
- 1. Enter the stock tickers, start date, and end date.
252
- 2. Set the number of days for the volatility window, and the buy/sell thresholds for the z-scores.
253
- 3. Click 'Run Analysis' to start the analysis.
254
  """)
255
 
256
- # Input fields
257
- ticker1 = st.sidebar.text_input('Enter First Stock Ticker', 'ASML.AS')
258
- ticker2 = st.sidebar.text_input('Enter Second Stock Ticker', 'ASML')
259
- start_date = st.sidebar.date_input('Start Date', pd.to_datetime('2022-01-01'))
260
- end_date = st.sidebar.date_input('End Date', pd.to_datetime('2023-09-30'))
261
- volatility_window = st.sidebar.number_input('Volatility Window (days)', min_value=1, max_value=365, value=30)
262
- buy_threshold = st.sidebar.number_input('Buy Z-Score Threshold', value=2.0)
263
- sell_threshold = st.sidebar.number_input('Sell Z-Score Threshold', value=-2.0)
 
 
 
 
264
 
265
  if st.sidebar.button('Run Analysis'):
266
  # Data collection
@@ -322,6 +339,24 @@ elif page == 'Pairs Trading Analysis':
322
  st.write(f"ADF Statistic for {ticker1}: {adf_result1[0]}, p-value: {adf_result1[1]}")
323
  st.write(f"ADF Statistic for {ticker2}: {adf_result2[0]}, p-value: {adf_result2[1]}")
324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
  st.markdown("#### Interpretation of ADF Results")
326
  st.latex(r'''
327
  H_0: \text{The series has a unit root (non-stationary)} \\
@@ -359,9 +394,9 @@ elif page == 'Pairs Trading Analysis':
359
  - The Johansen cointegration test is used to determine the cointegration rank between multiple time series.
360
  """)
361
  if coint_test_stat[0] > coint_critical_values[0, 1]:
362
- st.write(f"The two stocks {ticker1} and {ticker2} are cointegrated at the 95% confidence level.")
363
  else:
364
- st.write(f"The two stocks {ticker1} and {ticker2} are not cointegrated at the 95% confidence level.")
365
 
366
  st.markdown("#### Interpretation of VECM Residuals")
367
  st.write(f"ADF Statistic for VECM residuals of {ticker1}: {adf_residuals_1[0]}, p-value: {adf_residuals_1[1]}")
@@ -400,7 +435,7 @@ elif page == 'Pairs Trading Analysis':
400
  st.write(f"Highest correlation: {max_corr:.2f} at lag {max_lag}")
401
  st.write(f"Second highest correlation: {second_max_corr:.2f} at lag {second_max_lag}")
402
 
403
- interpretation = f"Highest correlation at lag {max_lag}: The high correlation at lag {max_lag} indicates that {ticker1} and {ticker2} move together without any significant lead or lag. In other words, any movements in {ticker1} are almost instantaneously reflected in {ticker2} and vice versa. This is typical for cross-listed stocks, where information and price changes are quickly reflected in both markets.\n"
404
 
405
  if second_max_lag < 0:
406
  leading_ticker = ticker2
@@ -499,10 +534,11 @@ elif page == 'Pairs Trading Analysis':
499
  - The cumulative profit shows the total profit from the trading strategy over the analyzed period.
500
  """)
501
 
 
502
  hide_streamlit_style = """
503
  <style>
504
  #MainMenu {visibility: hidden;}
505
  footer {visibility: hidden;}
506
  </style>
507
  """
508
- st.markdown(hide_streamlit_style, unsafe_allow_html=True)
 
16
 
17
  # Parameters
18
  START_DATE = '2021-01-01'
19
+ END_DATE = pd.to_datetime('today') + pd.Timedelta(days=1)
20
  P_VALUE_THRESHOLD = 0.05
21
  ROLLING_WINDOW_SIZE = 252
22
  CONSISTENT_COINTEGRATION_THRESHOLD = 0.8
 
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.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.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(',')]
 
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
 
264
  st.write("""
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.expander("Stock/Crypto Ticker and Date Selection", expanded=True):
271
+ ticker1 = st.text_input('Enter First Stock/Crypto Ticker', 'ASML.AS', help="Enter the ticker symbol for the first stock or cryptocurrency.")
272
+ ticker2 = st.text_input('Enter Second Stock/Crypto Ticker', 'ASML', help="Enter the ticker symbol for the second stock or cryptocurrency.")
273
+ start_date = st.date_input('Start Date', pd.to_datetime('2022-01-01'), help="Select the start date for the data range.")
274
+ end_date = st.date_input('End Date', pd.to_datetime(END_DATE), help="Select the end date for the data range.")
275
+
276
+ # Expander for parameters specific to each method
277
+ with st.expander("Method Parameters", expanded=True):
278
+ volatility_window = st.number_input('Volatility Window (days)', min_value=1, max_value=365, value=30, help="Set the number of days for the rolling volatility window.")
279
+ buy_threshold = st.number_input('Buy Z-Score Threshold', value=2.0, help="Set the z-score threshold to generate buy signals.")
280
+ sell_threshold = st.number_input('Sell Z-Score Threshold', value=-2.0, help="Set the z-score threshold to generate sell signals.")
281
 
282
  if st.sidebar.button('Run Analysis'):
283
  # Data collection
 
339
  st.write(f"ADF Statistic for {ticker1}: {adf_result1[0]}, p-value: {adf_result1[1]}")
340
  st.write(f"ADF Statistic for {ticker2}: {adf_result2[0]}, p-value: {adf_result2[1]}")
341
 
342
+ # Expander for "How it Works" inside the main body
343
+ with st.expander("How it Works", expanded=False):
344
+ st.markdown("""
345
+ **ADF Test:**
346
+ - The Augmented Dickey-Fuller (ADF) test checks whether a time series has a unit root, i.e., whether it is non-stationary.
347
+ - If the p-value is less than 0.05, we reject the null hypothesis that the series has a unit root, indicating that the series is stationary.
348
+
349
+ **Johansen Cointegration Test:**
350
+ - The Johansen test is used to determine the number of cointegrating relationships among multiple time series.
351
+ - If the test statistic is greater than the critical value, we reject the null hypothesis that there is no cointegration.
352
+
353
+ **VECM (Vector Error Correction Model):**
354
+ - A VECM is a special form of a VAR (Vector Autoregression) model used for cointegrated series. It corrects for disequilibrium in the short run while keeping the long-term relationship intact.
355
+
356
+ **Z-Score Trading Strategy:**
357
+ - Z-scores measure how many standard deviations an element is from the mean. In pairs trading, z-scores are used to identify overbought or oversold conditions, triggering buy or sell signals.
358
+ """)
359
+
360
  st.markdown("#### Interpretation of ADF Results")
361
  st.latex(r'''
362
  H_0: \text{The series has a unit root (non-stationary)} \\
 
394
  - The Johansen cointegration test is used to determine the cointegration rank between multiple time series.
395
  """)
396
  if coint_test_stat[0] > coint_critical_values[0, 1]:
397
+ st.write(f"The two assets {ticker1} and {ticker2} are cointegrated at the 95% confidence level.")
398
  else:
399
+ st.write(f"The two assets {ticker1} and {ticker2} are not cointegrated at the 95% confidence level.")
400
 
401
  st.markdown("#### Interpretation of VECM Residuals")
402
  st.write(f"ADF Statistic for VECM residuals of {ticker1}: {adf_residuals_1[0]}, p-value: {adf_residuals_1[1]}")
 
435
  st.write(f"Highest correlation: {max_corr:.2f} at lag {max_lag}")
436
  st.write(f"Second highest correlation: {second_max_corr:.2f} at lag {second_max_lag}")
437
 
438
+ interpretation = f"Highest correlation at lag {max_lag}: The high correlation at lag {max_lag} indicates that {ticker1} and {ticker2} move together without any significant lead or lag. In other words, any movements in {ticker1} are almost instantaneously reflected in {ticker2} and vice versa. This is typical for cross-listed assets, where information and price changes are quickly reflected in both markets.\n"
439
 
440
  if second_max_lag < 0:
441
  leading_ticker = ticker2
 
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>
540
  #MainMenu {visibility: hidden;}
541
  footer {visibility: hidden;}
542
  </style>
543
  """
544
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)