Risk analysis and portfolio optimization are key concepts in financial modeling. They help investors balance returns and risks to maximize portfolio performance. Python libraries like pandas, NumPy, scipy, and PyPortfolioOpt assist in this process.
Key Topics Covered
✔ Understanding financial risk
✔ Calculating risk metrics (VaR, Sharpe Ratio, Standard Deviation)
✔ Portfolio diversification
✔ Efficient Frontier and Markowitz Portfolio Optimization
✔ Using Python for portfolio allocation
1. Installing Required Libraries
pip install numpy pandas matplotlib scipy yfinance PyPortfolioOpt
2. Fetching Historical Stock Data
Using yfinance
to get stock data
import yfinance as yf
import pandas as pd
# List of stocks
stocks = ['AAPL', 'GOOGL', 'MSFT', 'AMZN']
# Download historical data
data = yf.download(stocks, start="2022-01-01", end="2023-01-01")['Adj Close']
print(data.head())
✔ Provides historical adjusted closing prices
3. Calculating Daily Returns & Risk Metrics
Computing returns, volatility, and correlation
import numpy as np
# Compute daily returns
returns = data.pct_change().dropna()
# Calculate mean and standard deviation (volatility)
mean_returns = returns.mean()
volatility = returns.std()
# Compute correlation matrix
correlation = returns.corr()
print("Mean Returns:\n", mean_returns)
print("Volatility:\n", volatility)
print("Correlation Matrix:\n", correlation)
✔ Essential for risk assessment and diversification
4. Value at Risk (VaR) Calculation
Using the Historical Method for VaR
confidence_level = 0.05 # 95% confidence interval
# Calculate VaR at 5% level
VaR = returns.quantile(confidence_level)
print("Value at Risk (VaR) at 95% confidence level:\n", VaR)
✔ VaR helps estimate potential losses in a given timeframe
5. Sharpe Ratio Calculation
Risk-adjusted return metric
risk_free_rate = 0.02 # Assumed annual risk-free rate
# Annualized Sharpe Ratio
sharpe_ratios = (mean_returns - risk_free_rate) / volatility
print("Sharpe Ratios:\n", sharpe_ratios)
✔ Higher Sharpe Ratio = Better risk-adjusted returns
6. Portfolio Optimization Using Markowitz Theory
Using PyPortfolioOpt to find the optimal portfolio allocation
from pypfopt.efficient_frontier import EfficientFrontier
from pypfopt.risk_models import CovarianceShrinkage
from pypfopt.expected_returns import mean_historical_return
# Calculate expected returns and covariance matrix
mu = mean_historical_return(data)
S = CovarianceShrinkage(data).ledoit_wolf()
# Optimize portfolio using Efficient Frontier
ef = EfficientFrontier(mu, S)
weights = ef.max_sharpe() # Maximize Sharpe Ratio
cleaned_weights = ef.clean_weights()
print("Optimized Portfolio Allocation:\n", cleaned_weights)
✔ Finds the best stock allocations for maximum returns
7. Visualizing the Efficient Frontier
Plot the Efficient Frontier of possible portfolios
import matplotlib.pyplot as plt
from pypfopt.plotting import plot_efficient_frontier
# Create Efficient Frontier plot
fig, ax = plt.subplots(figsize=(8,6))
plot_efficient_frontier(ef, ax=ax, show_assets=True)
plt.title("Efficient Frontier of Portfolio")
plt.show()
✔ Helps investors choose the best risk-return balance