Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 18182324/154743bf2d39ca567a39ad6d663646c3 to your computer and use it in GitHub Desktop.
Save 18182324/154743bf2d39ca567a39ad6d663646c3 to your computer and use it in GitHub Desktop.
Tactical Asset Allocation
import pandas as pd
import yfinance as yf
# Download the ETF data from Yahoo Finance
etf_data = {}
for etf in ['ETF1', 'ETF2', 'ETF3', 'ETF4', 'ETF5', 'ETF6', 'ETF7', 'ETF8', 'ETF9', 'ETF10']:
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 tactical asset rotation strategy
def tactical_asset_rotation(returns, n_assets=3):
# Select the top performing assets based on returns
top_assets = returns.sort_values(ascending=False).index[:n_assets]
# Allocate the portfolio equally among the top assets
allocation = {asset: 1/n_assets for asset in top_assets}
return allocation
# Backtest the strategy over the 10-year period
allocations = []
for i in range(len(etf_returns['ETF1'])):
returns = pd.Series({etf: etf_returns[etf].iloc[i] for etf in etf_returns})
allocation = tactical_asset_rotation(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()
performance = pd.Series(portfolio_returns).subtract(pd.Series(stock_market_returns)).tolist()
# Print the combination of the 3 best performing ETFs
top_assets = [list(allocation.keys()) for allocation in allocations]
print(top_assets)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment