Advertisement
Guest User

cointegration

a guest
Nov 19th, 2023
455
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | Source Code | 0 0
  1. import yfinance as yf
  2. import datetime
  3. import matplotlib.pyplot as plt
  4. import pandas as pd
  5. import statsmodels.tsa.stattools as ts
  6. from scipy.stats import linregress
  7. import numpy as np
  8.  
  9. def download_data(stock, start, end):
  10. stock_data = {}
  11. ticker = yf.download(stock, start, end)
  12. stock_data['price'] = ticker['Adj Close']
  13. return pd.DataFrame(stock_data)
  14.  
  15.  
  16. def plot_pairs(data1, data2):
  17. fig, (ax1, ax2) = plt.subplots(2)
  18. fig.suptitle('Pair of Pairs')
  19. ax1.plot(data1)
  20. ax2.plot(data2)
  21. plt.show()
  22.  
  23. def scatter_plot(data1, data2):
  24. plt.scatter(data1.values, data2.values)
  25. plt.xlabel('XOM')
  26. plt.ylabel('CVX')
  27. plt.show()
  28.  
  29.  
  30. if __name__ == '__main__':
  31. start_date = datetime.datetime(2011, 4, 1)
  32. end_date = datetime.datetime(2020, 1, 1)
  33.  
  34. pair1 = download_data('XON', start_date, end_date)
  35. pair2 = download_data('CVX', start_date, end_date)
  36.  
  37. plot_pairs(pair1, pair2)
  38.  
  39. scatter_plot(pair1, pair2)
  40.  
  41. res = linregress(pair1.values[:, 0], pair2.values[:, 0])
  42.  
  43. residuals = pair1 - res.slope * pair2
  44.  
  45. adf = ts.adfuller(residuals)
  46. print(adf)
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement