Skip to content

Instantly share code, notes, and snippets.

@18182324
Created January 5, 2023 21:04
Show Gist options
  • Save 18182324/91c00b92acb413ece21a3bd3888ec31d to your computer and use it in GitHub Desktop.
Save 18182324/91c00b92acb413ece21a3bd3888ec31d to your computer and use it in GitHub Desktop.
Tactical Asset Allocation and Automatic Optimization
import numpy as np
import pandas as pd
import yfinance as yf
from scipy.optimize import minimize
# 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()
# Define the optimization function
def optimize_weights(weights, returns):
# Calculate the portfolio return
portfolio_return = np.sum(returns.mean() * weights) * 252
# Calculate the portfolio volatility
portfolio_volatility = np.sqrt(np.dot(weights.T, np.dot(returns.cov() * 252, weights)))
# Calculate the Sharpe ratio
sharpe_ratio = portfolio_return / portfolio_volatility
# Return the negative Sharpe ratio to minimize
return -sharpe_ratio
# Set the optimization constraints
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1},
{'type': 'ineq', 'fun': lambda x: x})
# Set the initial weights
initial_weights = np.array([0.2, 0.2, 0.2, 0.2, 0.2])
# Run the optimization
results = minimize(optimize_weights, initial_weights, args=(etf_returns), method='SLSQP', bounds=bounds, constraints=constraints)
# Print the optimized weights
print(results.x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment