Scale Factor-Model Portfolio Risk to a Yearly Figure
Math & Bit ManipulationAuto-graded · 18 test casesLast updated
Compute a portfolio's one-period variance from a factor model (exposures, factor covariance, specific variances), then scale it by periods per year and take the square root.
Scale Factor-Model Portfolio Risk to a Yearly Figure
You hold a portfolio of several stocks. Risk is described by a linear factor model. Every stock loads on a set of common factors, the factors co-vary with each other, and every stock also carries its own stock-specific (idiosyncratic) variance. All inputs are measured over the same single return period, such as one day or one month.
Write a function that returns the portfolio's annualized volatility.
Inputs
exposures: a list ofnrows, one per stock, each a list ofknumbers.exposures[s][j]is the loading of stockson factorj(the matrixB).factor_cov: ak x kfactor covariance matrixF, given per single period. Index it exactly as given:factor_cov[i][j].specific_var: a list ofnnonnegative numbers. Entrysis the specific variance of stocksfor one period (the diagonal ofD).weights: a list ofnnumbersw, the portfolio weight of each stock.periods_per_year: a nonnegative integer, the number of return periods in a year (for example 252 for daily or 12 for monthly).
Model
Factor returns and stock-specific returns are uncorrelated. Specific returns of different stocks are also uncorrelated with each other. The one-period portfolio variance is therefore
V = (Bᵀw)ᵀ F (Bᵀw) + Σ_s w_s² · specific_var[s]
where (Bᵀw)[j] = Σ_s weights[s] · exposures[s][j], and the quadratic form is
Σ_i Σ_j (Bᵀw)[i] · factor_cov[i][j] · (Bᵀw)[j]
Task
- Compute the one-period variance
Vwith the formula above. - If
V < 0(floating-point error or an indefiniteF), replace it by0.0. - Multiply by
periods_per_yearto get the annual variance (variance grows linearly with time). - Return the square root of that annual variance as a float.
Do not take the square root before scaling, and do not multiply the volatility by periods_per_year.
Edge cases
- If there are no stocks, or the annual variance is zero (for example
periods_per_year = 0or every term is zero), return0.0. - Weights can be any real numbers, including negative values (short positions), and need not sum to 1.
factor_covis used as given. Do not assume you must symmetrize it. The quadratic form above is the definition.- The checker compares floats with a small tolerance, so do not round.
Constraints
exposureshasn >= 0rows of lengthk.factor_covisk x k, andspecific_varandweightseach have lengthn.- Every entry of
specific_varis>= 0. periods_per_year >= 0.- All inputs share the same universe, currency and return horizon, so no unit conversion is needed.
Examples
Example 1
Input: annualized_factor_risk([[1, 0.5], [0.2, 1]], [[0.04, 0.006], [0.006, 0.09]], [0.01, 0.0225], [0.6, 0.4], 252)
Output: 4.362111415358393
Example 2
Input: annualized_factor_risk([[1], [1], [0]], [[0.04]], [0.01, 0.01, 0.04], [0.5, 0.3, 0.2], 12)
Output: 0.6059702963017247
Example 3
Input: annualized_factor_risk([[0, 0], [1, -1]], [[0.01, 0], [0, 0.04]], [0, 0.0025], [0.25, 0.5], 252)
Output: 1.8186533479473213
Hints
Hint 1
Collapse the stock-level loadings first: the portfolio's exposure to factor j is the sum over stocks of weight times loading.
Hint 2
Factor variance is the quadratic form of that exposure vector with the factor covariance matrix. Specific variance adds w_s squared times its variance for each stock, since specific returns are uncorrelated.
Hint 3
Annualize at the variance level: clamp a negative one-period variance to zero, multiply by periods_per_year, and only then take the square root.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Under the model, the stock covariance matrix is B F Bᵀ + D, so the one-period portfolio variance is wᵀ B F Bᵀ w + wᵀ D w.
- Portfolio factor exposure. Compute
x = Bᵀ w, wherex[j] = Σ_s w_s · B[s][j]. This takes O(n·k) time and avoids building the n x n covariance matrix. - Factor variance. Evaluate the quadratic form
xᵀ F xwith two nested loops over the factors, usingF[i][j]exactly as given. - Specific variance. Because
Dis diagonal,wᵀ D w = Σ_s w_s² · specific_var[s]. - Combine and clamp. Add the two parts. If the sum is negative, use
0.0. - Annualize. Multiply the variance by
periods_per_year, then take the square root. With no stocks orperiods_per_year = 0, the result is0.0.
Why it is correct
Factor returns are uncorrelated with specific returns, so their variance contributions add. Specific returns are uncorrelated across stocks, so only the diagonal terms w_s² · d_s survive. Variance of independent per-period returns grows linearly with the number of periods, so annual variance is periods_per_year times the one-period variance, and volatility is its square root (the square-root-of-time rule). Scaling the volatility directly by periods_per_year, or mixing in an already annualized covariance, would give wrong results, which is why the horizon must be the same across all inputs.
Complexity
- Time: O(n·k + k²)
- Space: O(k)
Reference solution
import math
from typing import List
def annualized_factor_risk(exposures: List[List[float]], factor_cov: List[List[float]], specific_var: List[float], weights: List[float], periods_per_year: int) -> float:
# Portfolio-level factor exposure: B^T w
port_exposure = [0.0] * len(factor_cov)
for weight, loadings in zip(weights, exposures):
for j, loading in enumerate(loadings):
port_exposure[j] += weight * loading
# Factor risk: (B^T w)^T F (B^T w)
factor_part = 0.0
for i, xi in enumerate(port_exposure):
for j, xj in enumerate(port_exposure):
factor_part += xi * factor_cov[i][j] * xj
# Specific risk: sum of w_s^2 * specific variance
specific_part = sum(
weight * weight * var
for weight, var in zip(weights, specific_var)
)
period_variance = factor_part + specific_part
return math.sqrt(max(0.0, period_variance) * periods_per_year)