Portfolio optimization using Python
What´s portfolio optimization?
Optimization can be roughly defined as a quantitative approach for decision making, where we seek to determine a “best” decision from a “set” of possible decisions.
Goal
With this project my main objective was to find the optimal portfolio with my favorite companies in the stock market, namely Tesla, Amazon, Apple, Google, Nvidia, Qualcomm and Microsoft.
Tools
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
import yfinance as yf
Data
stocks = ["AAPL", "AMZ", "MSFT", "TSLA", "GOOGL", "QCOM", "NVDA"]
data = yf.download(stocks, start="2018-01-01")
data = data["Close"]
x = data.pct_change()
Then I precided to create empty lists for weights, returns, risk and for the sharp ratio.
Generate random portfolios
count = 10000
for k in range(0, count):
wts = np.random.uniform(size = len(x.columns))
wts = wts/np.sum(wts)
p_weights.append(wts)
Then I did the same process for the other parameters and preceded to find the max values for the sharp ratio and the weights to each stock in the portfolio, using np.argmax.
Optimal portfolio
1.4270321023413632 [0.3264971 0.01088931 0.01399479 0.22366134 0.03132052 0.020364 0.37327295]
Using the scatter() function with the volatility and return lists as parameters:
plt.scatter(p_risk, p_returns, c=p_sharpe, cmap="plasma") plt.colorbar(label="Sharpe Ratio") plt.scatter(p_risk[max_ind], p_returns[max_ind], color="r", marker="*", s=100) plt.show()