Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 18182324/1c07e8ee348178ba8db25bbc60ef94ee to your computer and use it in GitHub Desktop.
Save 18182324/1c07e8ee348178ba8db25bbc60ef94ee to your computer and use it in GitHub Desktop.
Tactical Asset Allocation ETFs
import pandas as pd
import yfinance as yf
# Download the ETF data from Yahoo Finance
etf_data = {}
for etf in ['SPY', 'MDY', 'EFA', 'EEM', 'TLT']:
etf_data[etf] = yf.Ticker(etf).history(period="10y")
# Calculate the returns for each ETF
etf_returns = {}
for etf, data in etf_data.items():
etf_returns[etf] = data['Adj Close'].pct_change().dropna()
# Implement the trading strategy
def trading_strategy(returns):
# Select the best performing ETF based on returns over the trailing 3 months
top_asset = returns.sort_values(ascending=False).index[0]
# Allocate the portfolio to the top asset
allocation = {top_asset: 1}
return allocation
# Backtest the strategy over the 10-year period
allocations = []
for i in range(len(etf_returns['SPY'])):
# Only consider the last trading day of the month
if etf_data['SPY'].index[i].day == etf_data['SPY'].index[-1].day:
returns = pd.Series({etf: etf_returns[etf].iloc[i-62:i].mean() for etf in etf_returns})
allocation = trading_strategy(returns)
allocations.append(allocation)
# Calculate the portfolio returns based on the allocations
portfolio_returns = []
for allocation in allocations:
portfolio_return = sum([etf_returns[etf].iloc[i] * allocation[etf] for etf in allocation])
portfolio_returns.append(portfolio_return)
# Calculate the performance of the strategy compared to the stock market
stock_market_returns = etf_returns['SPY'].tolist()[63:]
performance = pd.Series(portfolio_returns).subtract(pd.Series(stock_market_returns)).tolist()
# Print the results
print(performance)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment