-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEfficientFrontier_py
More file actions
131 lines (110 loc) · 3.21 KB
/
Copy pathEfficientFrontier_py
File metadata and controls
131 lines (110 loc) · 3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
from scipy.optimize import minimize
# -----------------------------
# User inputs
# -----------------------------
tickers = ["VT", "AVUV", "AVDV"]
start_date = "2018-01-01"
end_date = None # None = today
risk_free_rate = 0.02 # annual risk-free rate
# -----------------------------
# Single yfinance call (NO looping)
# -----------------------------
prices = yf.download(
tickers,
start=start_date,
end=end_date,
auto_adjust=True,
threads=False,
group_by="ticker"
)
# Extract adjusted close
if isinstance(prices.columns, pd.MultiIndex):
prices = prices.loc[:, (slice(None), "Close")]
prices.columns = prices.columns.droplevel(1)
else:
prices = prices["Close"]
# -----------------------------
# Compute returns
# -----------------------------
returns = prices.pct_change().dropna()
mean_returns = returns.mean() * 252
cov_matrix = returns.cov() * 252
# -----------------------------
# Portfolio statistics
# -----------------------------
def portfolio_performance(weights, mean_returns, cov_matrix, rf):
ret = np.dot(weights, mean_returns)
vol = np.sqrt(weights.T @ cov_matrix @ weights)
sharpe = (ret - rf) / vol
return ret, vol, sharpe
# -----------------------------
# Tangency portfolio
# -----------------------------
def negative_sharpe(weights, mean_returns, cov_matrix, rf):
return -portfolio_performance(weights, mean_returns, cov_matrix, rf)[2]
num_assets = len(tickers)
init_weights = np.ones(num_assets) / num_assets
constraints = {"type": "eq", "fun": lambda w: np.sum(w) - 1}
bounds = tuple((0, 1) for _ in range(num_assets))
opt = minimize(
negative_sharpe,
init_weights,
args=(mean_returns, cov_matrix, risk_free_rate),
method="SLSQP",
bounds=bounds,
constraints=constraints
)
tangency_weights = opt.x
tangency_return, tangency_vol, tangency_sharpe = portfolio_performance(
tangency_weights, mean_returns, cov_matrix, risk_free_rate
)
# -----------------------------
# Efficient frontier simulation
# -----------------------------
num_ports = 50_000
results = np.zeros((3, num_ports))
for i in range(num_ports):
w = np.random.random(num_assets)
w /= w.sum()
ret, vol, sharpe = portfolio_performance(
w, mean_returns, cov_matrix, risk_free_rate
)
results[:, i] = [vol, ret, sharpe]
# -----------------------------
# Plot
# -----------------------------
plt.figure(figsize=(10, 7))
plt.scatter(
results[0],
results[1],
c=results[2],
cmap="viridis",
alpha=0.3
)
plt.colorbar(label="Sharpe Ratio")
plt.scatter(
tangency_vol,
tangency_return,
color="red",
marker="*",
s=300,
label="Tangency Portfolio"
)
plt.xlabel("Annualized Volatility")
plt.ylabel("Annualized Return")
plt.title("Efficient Frontier with Tangency Portfolio")
plt.legend()
plt.show()
# -----------------------------
# Output
# -----------------------------
weights = pd.Series(tangency_weights, index=tickers, name="Weight")
print("\nTangency Portfolio Weights")
print(weights.round(4))
print(f"\nExpected Return: {tangency_return:.2%}")
print(f"Volatility: {tangency_vol:.2%}")
print(f"Sharpe Ratio: {tangency_sharpe:.2f}")