We will show how you can build a diversified portfolio that satisfies specific constraints. For this tutorial, we will build a portfolio that minimizes the risk.
So the first thing to do is to get the stock prices programmatically using Python.
We will work with the package where you can install it using pip install yfinance --upgrade --no-cache-dir
You will need to get the symbol of the stock. You can find the mapping between NASDAQ stocks and symbols in this csv file.
For this tutorial, we will assume that we are dealing with the following 10 stocks and we try to minimize the portfolio risk.
We will download the close prices for the last year.
import pandas as pd
import numpy as np
import yfinance as yf
from scipy.optimize import minimize
import matplotlib.pyplot as plt
%matplotlib inline
symbols = ['GOOGL', 'TSLA', 'FB', 'AMZN', 'AAPL', 'MSFT', 'VOD', 'ADBE', 'NVDA', 'CRM' ]
all_stocks = pd.DataFrame()
for symbol in symbols:
tmp_close = yf.download(symbol,
start='2019-11-07',
end='2020-11-07',
progress=False)['Close']
all_stocks = pd.concat([all_stocks, tmp_close], axis=1)
all_stocks.columns=symbols
all_stocks
We will use the log returns or continuously compounded return. Let’s calculate them in Python.
returns = np.log(all_stocks/all_stocks.shift(1)).dropna(how="any") returns
returns.plot(figsize=(12,10))
We can get the mean returns of every stock as well as the average of all of them.
## mean daily returns per stock
returns.mean()
GOOGL 0.001224
TSLA 0.007448
FB 0.001685
AMZN 0.002419
AAPL 0.002422
MSFT 0.001740
VOD -0.001583
ADBE 0.002146
NVDA 0.004077
CRM 0.001948
dtype: float64
## mean daily returns of all stocks
returns.mean().mean()
0.0023526909011353354
Our goal is to construct a portfolio from those 10 stocks with the following constraints:
Finally, our objective is to** minimize the variance (i.e. risk) of the portfolio**. You can find a nice explanation on this blog of how you can calculate the variance of the portfolio using matrix operations.
#python #scipy #data-science #developer #programming