portfolio_toolkit.math.get_var module
- portfolio_toolkit.math.get_var.get_covariance_matrix(returns_df: DataFrame) DataFrame [source]
Calculates the covariance matrix from a DataFrame of logarithmic returns.
This matrix is used for Value at Risk (VaR) calculations and portfolio optimization.
- Parameters:
returns_df (pd.DataFrame) – DataFrame where: - Rows are dates (datetime index) - Columns are ticker symbols - Values are logarithmic returns for each asset
- Returns:
- Symmetric covariance matrix where:
Rows and columns are ticker symbols
Diagonal elements are variances
Off-diagonal elements are covariances
- Return type:
pd.DataFrame
Example
>>> dates = pd.date_range('2023-01-01', periods=100, freq='D') >>> returns_df = pd.DataFrame({ ... 'AAPL': np.random.normal(0.001, 0.02, 100), ... 'MSFT': np.random.normal(0.0008, 0.018, 100), ... 'GOOGL': np.random.normal(0.0012, 0.025, 100) ... }, index=dates) >>> cov_matrix = get_covariance_matrix(returns_df) >>> print(cov_matrix)
Notes
Uses pandas .cov() method which calculates sample covariance
Automatically handles missing values (NaN) by pairwise deletion
Matrix is symmetric: cov(A,B) = cov(B,A)
Diagonal values are variances: cov(A,A) = var(A)
- portfolio_toolkit.math.get_var.get_correlation_matrix(returns_df: DataFrame) DataFrame [source]
Calculates the correlation matrix from a DataFrame of logarithmic returns.
- Parameters:
returns_df (pd.DataFrame) – DataFrame of returns (same format as get_covariance_matrix)
- Returns:
Correlation matrix with values between -1 and 1
- Return type:
pd.DataFrame
Example
>>> corr_matrix = get_correlation_matrix(returns_df)
- portfolio_toolkit.math.get_var.get_portfolio_variance(weights: ndarray | Series, covariance_matrix: DataFrame) float [source]
Calculates portfolio variance using weights and covariance matrix.
Formula: σ²_p = w^T * Σ * w Where:
w = vector of portfolio weights
Σ = covariance matrix
σ²_p = portfolio variance
- Parameters:
weights – Portfolio weights (must sum to 1)
covariance_matrix – Covariance matrix from get_covariance_matrix()
- Returns:
Portfolio variance
- Return type:
Example
>>> weights = np.array([0.4, 0.4, 0.2]) # 40% AAPL, 40% MSFT, 20% GOOGL >>> portfolio_var = get_portfolio_variance(weights, cov_matrix)
- portfolio_toolkit.math.get_var.get_portfolio_volatility(weights: ndarray | Series, covariance_matrix: DataFrame) float [source]
Calculates portfolio volatility (standard deviation).
- Parameters:
weights – Portfolio weights
covariance_matrix – Covariance matrix
- Returns:
Portfolio volatility (sqrt of variance)
- Return type:
- portfolio_toolkit.math.get_var.calculate_var(weights: ndarray | Series, covariance_matrix: DataFrame, portfolio_value: float = 1000000, confidence_level: float = 0.95, time_horizon: int = 1) float [source]
Calculates Value at Risk (VaR) for a portfolio using parametric method.
VaR represents the maximum expected loss over a given time horizon at a specified confidence level, assuming normal distribution of returns.
Formula: VaR = -z_α * σ_p * √t * V Where:
z_α = z-score for confidence level (e.g., -1.645 for 95%)
σ_p = portfolio volatility (daily)
t = time horizon in days
V = portfolio value
- Parameters:
weights – Portfolio weights (must sum to 1)
covariance_matrix – Covariance matrix of asset returns
portfolio_value – Total portfolio value in monetary units (default: 1,000,000)
confidence_level – Confidence level as decimal (default: 0.95 = 95%)
time_horizon – Time horizon in days (default: 1 day)
- Returns:
Value at Risk in monetary units (positive value represents potential loss)
- Return type:
Example
>>> weights = np.array([0.4, 0.4, 0.2]) >>> cov_matrix = get_covariance_matrix(returns_df) >>> var_95 = calculate_var(weights, cov_matrix, portfolio_value=1000000) >>> print(f"1-day VaR at 95% confidence: ${var_95:,.2f}")
>>> # 10-day VaR at 99% confidence >>> var_99_10d = calculate_var(weights, cov_matrix, ... portfolio_value=1000000, ... confidence_level=0.99, ... time_horizon=10)
Notes
Assumes normal distribution of returns (parametric VaR)
Uses daily volatility from covariance matrix
Higher confidence levels give higher VaR values
Longer time horizons give higher VaR values (scales with √time)
Returns positive value representing potential loss
- portfolio_toolkit.math.get_var.calculate_expected_shortfall(weights: ndarray | Series, covariance_matrix: DataFrame, portfolio_value: float = 1000000, confidence_level: float = 0.95, time_horizon: int = 1) float [source]
Calculates Expected Shortfall (ES) / Conditional Value at Risk (CVaR).
ES represents the expected loss given that the loss exceeds the VaR threshold. It provides information about tail risk beyond VaR.
- Parameters:
weights – Portfolio weights
covariance_matrix – Covariance matrix of asset returns
portfolio_value – Portfolio value in monetary units
confidence_level – Confidence level (default: 0.95)
time_horizon – Time horizon in days (default: 1)
- Returns:
Expected Shortfall in monetary units
- Return type:
Example
>>> es_95 = calculate_expected_shortfall(weights, cov_matrix) >>> print(f"Expected Shortfall at 95%: ${es_95:,.2f}")