7.1 KiB
This code constructs and optimizes a financial portfolio using historical stock data. It uses the Riskfolio library to estimate asset returns and covariance. The code further optimizes the portfolio for risk parity and visualizes the resulting asset allocation and risk contributions. Additionally, it demonstrates the impact of adding a constraint on expected returns. This is useful for portfolio management and risk assessment in finance.
import yfinance as yf import riskfolio as rp import warnings warnings.filterwarnings("ignore")
Define a list of stock tickers to include in the portfolio
assets = ["JCI", "TGT", "CMCSA", "CPB", "MO", "APA", "MMC", "JPM", "ZION", "PSA", "BAX", "BMY", "LUV", "PCAR", "TXT", "TMO", "DE", "MSFT", "HPQ", "SEE", "VZ", "CNP", "NI", "T", "BA"]
Sort the list of tickers alphabetically
assets.sort()
Download historical stock data for the specified tickers from Yahoo Finance
data = yf.download(assets, start="2016-01-01", end="2019-12-30")
Calculate daily returns based on adjusted closing prices
returns = data['Adj Close'].pct_change().dropna()
Create a Portfolio object using the calculated returns
port = rp.Portfolio(returns=returns)
Estimate expected returns and covariance matrix using historical data
port.assets_stats(method_mu='hist', method_cov='hist', d=0.94)
Optimize the portfolio for risk parity using mean-variance optimization
w_rp = port.rp_optimization( model="Classic", # use historical rm="MV", # use mean-variance optimization hist=True, # use historical scenarios rf=0, # set risk free rate to 0 b=None # don't use constraints )
Plot the asset allocation of the optimized portfolio
ax = rp.plot_pie(w=w_rp)
Plot the risk contribution of each asset in the optimized portfolio
ax = rp.plot_risk_con( w_rp, cov=port.cov, returns=port.returns, rm="MV", rf=0, )
Set a constraint for the minimum level of expected returns for the portfolio
port.lowerret = 0.0008
Optimize the portfolio for risk parity with the added constraint on expected returns
w_rp_c = port.rp_optimization( model="Classic", # use historical rm="MV", # use mean-variance optimization hist=True, # use historical scenarios rf=0, # set risk free rate to 0 b=None # don't use constraints )
Plot the asset allocation of the constrained optimized portfolio
ax = rp.plot_pie(w=w_rp_c)
Plot the risk contribution of each asset in the constrained optimized portfolio
ax = rp.plot_risk_con( w_rp_c, cov=port.cov, returns=port.returns, rm="MV", rf=0, )
PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.
