Created
January 5, 2023 20:38
-
-
Save 18182324/1c07e8ee348178ba8db25bbc60ef94ee to your computer and use it in GitHub Desktop.
Tactical Asset Allocation ETFs
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 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