BONDS Working

Post Reply
admin
Site Admin
Posts: 38
Joined: Fri Jan 10, 2025 10:29 am

BONDS Working

Post by admin »

https://medium.com/@deepml1818/python-f ... 7d4c476c1e

import yfinance as yf
import pandas as pd
# Fetch U.S. Treasury yield data from yfinance
tickers = ['^IRX', '^FVX', '^TNX', '^TYX'] # 3-month, 5-year, 10-year, and 30-year Treasury yield indices
data = yf.download(tickers, auto_adjust=False, start='1980-01-01', end='2025-04-04')['Adj Close']
# Rename columns for clarity
data.columns = ['3M', '5Y', '10Y', '30Y']
# Display the first few rows of data
print(data.tail())

import matplotlib.pyplot as plt
# Plot the yield curve
plt.figure(figsize=(10, 6))
for date in ['2020-01-02', '2021-01-04', '2022-01-03','2023-01-04','2024-01-04','2025-04-03']:
plt.plot(['3M', '5Y', '10Y', '30Y'], data.loc[date], label=f'Yield Curve {date}')
plt.title('U.S. Treasury Yield Curve')
plt.xlabel('Maturity')
plt.ylabel('Yield (%)')
plt.legend()
plt.grid(True)
plt.show()
# Calculate yield spread (10Y - 3M)
data['10Y-3M Spread'] = data['10Y'] - data['3M']
# Plot the yield spread
plt.figure(figsize=(10, 6))
data['10Y-3M Spread'].plot()
plt.title('10Y-3M Yield Spread')
plt.xlabel('Date')
plt.ylabel('Spread (%)')
plt.grid(True)
plt.show()
# Define a simple strategy: Buy bonds when the spread is negative (inverted yield curve), sell when positive (normal curve)
data['Signal'] = 0
data.loc[data['10Y-3M Spread'] < 0, 'Signal'] = 1 # Buy when inverted
data.loc[data['10Y-3M Spread'] > 0, 'Signal'] = -1 # Sell when normal
# Display signals
print(data[['10Y-3M Spread', 'Signal']].tail())
# Plot the trading signals
plt.figure(figsize=(10, 6))
data['Signal'].plot()
plt.title('Trading Signals Based on Yield Spread')
plt.xlabel('Date')
plt.ylabel('Signal (1 = Buy, -1 = Sell)')
plt.grid(True)
plt.show()

import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# Fetch U.S. Treasury yield data from yfinance
tickers = ['^IRX', '^FVX', '^TNX', '^TYX'] # 3-month, 5-year, 10-year, and 30-year Treasury yield indices
data = yf.download(tickers,auto_adjust=False, start='2020-01-01', end='2025-04-01')['Adj Close']
data.columns = ['3M', '5Y', '10Y', '30Y']
# Remove timezone information from yield data
data.index = data.index.tz_localize(None)
# Calculate yield spread (10Y - 3M)
data['10Y-3M Spread'] = data['10Y'] - data['3M']
# Define a simple strategy: Buy bonds when the spread is negative (inverted yield curve), sell when positive (normal curve)
data['Signal'] = 0
data.loc[data['10Y-3M Spread'] < 0, 'Signal'] = 1 # Buy when inverted
data.loc[data['10Y-3M Spread'] > 0, 'Signal'] = -1 # Sell when normal
# Fetch TLT price data (20+ Year Treasury Bonds)
tlt_data = yf.download('TLT',auto_adjust=False, start='2020-01-01', end='2025-04-01')['Adj Close']
# Remove timezone information from TLT data
tlt_data.index = tlt_data.index.tz_localize(None)
# Calculate daily returns for TLT
tlt_data = pd.DataFrame(tlt_data) # Convert to DataFrame if needed
tlt_data['Returns'] = tlt_data.pct_change()
# Align signals with TLT data
strategy_returns = data['Signal'].shift(1).loc[tlt_data.index] * tlt_data['Returns']
# Calculate cumulative returns
cumulative_returns = (1 + strategy_returns).cumprod()
# Plot cumulative returns
plt.figure(figsize=(10, 6))
cumulative_returns.plot()
plt.title('Cumulative Returns of Yield Spread Strategy')
plt.xlabel('Date')
plt.ylabel('Cumulative Returns')
plt.grid(True)
plt.show()
Post Reply