Skip to content

Instantly share code, notes, and snippets.

@quantra-go-algo
Created October 31, 2023 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quantra-go-algo/ad0a3b568f48c3096957378ffded7bb4 to your computer and use it in GitHub Desktop.
Save quantra-go-algo/ad0a3b568f48c3096957378ffded7bb4 to your computer and use it in GitHub Desktop.
yf.pdr_override()
# Set the stock pairs
stock_pairs = [('AAPL', 'AMZN'), ('MSFT', 'AAPL'), ('AMZN', 'MSFT')]
# Set the start date and the end date
start_date = '2010-01-01'
end_date = '2022-10-16'
# Download stock price data for all pairs
data = pdr.get_data_yahoo([pair[0] for pair in stock_pairs] + [pair[1] for pair in stock_pairs], start=start_date, end=end_date)['Adj Close']
# Perform the Johansen Cointegration Test for all pairs
coint_test_result = coint_johansen(data, det_order=0, k_ar_diff=1)
# Extract the eigenvalues and critical values
tracevalues = coint_test_result.lr1
critical_values = coint_test_result.cvt
# Interpret the results for each pair
for i, (stock1, stock2) in enumerate(stock_pairs):
if (tracevalues[i] > critical_values[:, 1]).all():
print(f"Pair {i + 1} ({stock1} and {stock2}) is cointegrated.")
else:
print(f"Pair {i + 1} ({stock1} and {stock2}) is not cointegrated.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment