Created
September 18, 2024 02:30
-
-
Save Sinjhin/1dcbd6cb5574e63b69e04b762eb0c958 to your computer and use it in GitHub Desktop.
FFERvsBTCUSD
This file contains 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 requests | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
import yfinance as yf | |
# FRED API Key (you need to get your own from https://fred.stlouisfed.org/) | |
FRED_API_KEY = 'YOUR_KEY_HERE' | |
# Define the URL for FRED (Federal Funds Rate) | |
FRED_URL = f'https://api.stlouisfed.org/fred/series/observations?series_id=FEDFUNDS&api_key={FRED_API_KEY}&file_type=json' | |
# Function to fetch Federal Funds Effective Rate from FRED API | |
def get_fed_funds_rate(): | |
response = requests.get(FRED_URL) | |
data = response.json()['observations'] | |
# Convert the data into a pandas DataFrame | |
fed_data = pd.DataFrame(data) | |
fed_data['date'] = pd.to_datetime(fed_data['date']) | |
fed_data['value'] = pd.to_numeric(fed_data['value']) | |
fed_data = fed_data[['date', 'value']].rename(columns={'value': 'Fed_Funds_Rate'}) | |
return fed_data | |
# Function to fetch BTC/USD historical data using yfinance | |
def get_btc_usd(): | |
btc = yf.download('BTC-USD', start='2014-01-01', end='2024-09-01') | |
btc_data = btc[['Close']].reset_index() | |
btc_data.columns = ['date', 'BTC_USD'] | |
return btc_data | |
# Fetch data | |
fed_funds_rate_df = get_fed_funds_rate() | |
btc_usd_df = get_btc_usd() | |
# Merge the two DataFrames on 'date' | |
merged_df = pd.merge_asof(btc_usd_df.sort_values('date'), fed_funds_rate_df.sort_values('date'), on='date') | |
# Plotting the data | |
fig, ax1 = plt.subplots(figsize=(10,6)) | |
# Plot Fed Funds Rate on the left y-axis | |
ax1.set_xlabel('Date') | |
ax1.set_ylabel('Fed Funds Rate (%)', color='tab:blue') | |
ax1.plot(merged_df['date'], merged_df['Fed_Funds_Rate'], color='tab:blue', label="Fed Funds Rate (%)") | |
ax1.tick_params(axis='y', labelcolor='tab:blue') | |
# Create another y-axis for BTC/USD on the right | |
ax2 = ax1.twinx() | |
ax2.set_ylabel('BTC/USD', color='tab:green') | |
ax2.plot(merged_df['date'], merged_df['BTC_USD'], color='tab:green', label="BTC/USD") | |
ax2.tick_params(axis='y', labelcolor='tab:green') | |
# Titles and layout | |
plt.title("Federal Funds Effective Rates and BTC/USD (2014-2024)") | |
fig.tight_layout() | |
# Show the plot | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment