Last active
August 16, 2024 08:44
-
-
Save dbose/931a168ef083faca2748697a1ab0cbb4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from pandas_datareader import data as pdr | |
from datetime import datetime | |
import quandl | |
# Define the time range for data collection | |
start = datetime(2010, 1, 1) | |
end = datetime(2024, 1, 1) | |
ndq = quandl.get("NASDAQOMX/COMP-NASDAQ", | |
trim_start=start.strftime("%Y-%m-%d"), | |
trim_end=end.strftime("%Y-%m-%d")) | |
nasdaq_monthly = ndq['Index Value'].resample('M').median().round().ffill() | |
nasdaq_monthly.index.names = ['DATE'] | |
# Fetch M2 Money Supply data | |
m2_money_supply = pdr.get_data_fred('M2SL', start=start, end=end) | |
# Resample to monthly data and calculate the percent change for M2 (inflation measure) | |
m2sl = m2_money_supply['M2SL'].resample('M').ffill() | |
# Combine the data into a single DataFrame | |
data = pd.DataFrame({'M2SL': m2sl, 'NASDAQ': nasdaq_monthly}).dropna() | |
# Calculate correlation | |
correlation = data.corr().iloc[0, 1] | |
# Plot the data | |
fig, ax1 = plt.subplots(figsize=(14, 8)) | |
ax1.plot(data.index, data['M2SL'], color='orange', label='M2SL') | |
ax1.set_xlabel('Date') | |
ax1.set_ylabel('M2SL', color='orange') | |
ax1.tick_params(axis='y', labelcolor='orange') | |
ax2 = ax1.twinx() | |
ax2.plot(data.index, data['NASDAQ'], color='blue', label='NASDAQ') | |
ax2.set_ylabel('NASDAQ Index', color='blue') | |
ax2.tick_params(axis='y', labelcolor='blue') | |
plt.title(f'Correlation between M2SL and NASDAQ: {correlation:.2f}') | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment