Skip to content

Risk Model

FactorRiskModel is a fundamental-style multi-factor risk model. Each day it regresses the stocks' returns on their factor exposures, which are qex expressions, plus a market factor and, optionally, industry dummies. The regression coefficients are that day's factor returns. From them it estimates a factor covariance matrix and each stock's specific risk, and uses those to forecast a portfolio's risk and attribute it to the factors.

It needs the risk extra: pip install "qex[risk]" (statsmodels).

from qex import FactorRiskModel, PRICE_ONLY_FACTORS
import pandas as pd

model = FactorRiskModel(style_factors=PRICE_ONLY_FACTORS, include_industries=True, industry_column='sector')
model.fit(data, lookback=252)                     # returns the model

model.factor_returns          # dates x factors: each day's factor returns
model.factor_covariance       # factors x factors, annualized
model.specific_risk           # each stock's annualized specific (idiosyncratic) volatility

weights = pd.Series({'AAPL': 0.1, 'MSFT': -0.1, 'JPM': 0.05, 'BAC': -0.05})
total, factor, specific = model.portfolio_risk(weights)     # annualized volatilities
model.factor_attribution(weights)                            # each factor's contribution to variance

How it is estimated

  • Exposures are the style factors' expressions, evaluated on the data, plus 1 for every stock on the market factor and a 0/1 dummy per industry when include_industries is set.
  • Point in time. Day t's returns are regressed on the exposures known at the close of day t − 1, so a factor built from day t's own return (short-term reversal, volatility) can't explain that return with hindsight.
  • Returns follow qex's rule for gaps (Halts, Delistings and Gaps): a day with no price has no return and leaves that day's regression.
  • The last lookback days are fitted, one cross-sectional regression a day, over the stocks with every exposure and a return; a day with fewer than min_observations stocks (default 10) is skipped.
  • Covariances are exponentially weighted, with a half_life (default 63 days), and annualized (× 252). They are proper weighted covariances: with equal weights, the factor covariance is exactly that of the factor returns.
  • Forecasts use the exposures at the close of the last fitted day, so portfolio_risk forecasts the risk of a book held from that day on.

Factors

A factor is a FactorDefinition(name, expression, description): any qex expression that gives each stock a number each day. Two sets come with qex:

DEFAULT_STYLE_FACTORS (needs fundamental fields market_cap and book_to_price):

Factor Expression
size rank(field('market_cap'))
value rank(winsorize(field('book_to_price'), 0.05))
momentum rank(returns(252) - returns(21))
volatility rank(volatility(60))
liquidity rank(adv(20)): 20-day average dollar volume
short_term_reversal rank(-returns(5))

PRICE_ONLY_FACTORS (prices and volume only):

Factor Expression
momentum rank(returns(252) - returns(21))
volatility rank(volatility(60))
liquidity rank(adv(20))
short_term_reversal rank(-returns(5))
medium_term_reversal rank(-returns(20))

Your own:

from qex import FactorRiskModel, FactorDefinition

factors = [
    FactorDefinition('earnings_yield', "rank(field('earnings') / field('price'))", 'Earnings yield rank'),
    FactorDefinition('beta', "rank(ts_beta_shrunk(returns(1), returns(1, 'market'), 252))", 'Market beta rank'),
]
model = FactorRiskModel(style_factors=factors).fit(data)

style_factors=None uses DEFAULT_STYLE_FACTORS. A factor that can't be computed on the data (a missing field) is skipped with a warning.

For a statistical model instead, with factors found from the returns themselves, see pca_factor in the Operator Reference.

API reference

FactorRiskModel

Multi-factor risk model.

The model decomposes stock returns into

r_i = sum_k(X_ik * f_k) + epsilon_i

Where

r_i = return of stock i X_ik = exposure of stock i to factor k f_k = return of factor k epsilon_i = specific (idiosyncratic) return

Attributes:

Name Type Description
style_factors

List of style factor definitions

include_industries

Whether to include industry dummy factors

industry_column

Name of industry column in data

half_life

Half-life for exponential weighting (days)

factor_covariance property

factor_covariance: DataFrame

Get the fitted factor covariance matrix.

factor_returns property

factor_returns: DataFrame

Get the estimated factor returns time series.

specific_risk property

specific_risk: Series

Get specific risk (annualized std) for each stock.

fit

fit(data, lookback: int = 252, min_observations: int = 10) -> FactorRiskModel

Fit the risk model using cross-sectional regression.

Parameters:

Name Type Description Default
data

Data dict or LazyData with price and factor data

required
lookback int

Number of days to use for estimation

252
min_observations int

Minimum observations required per stock

10

Returns:

Type Description
FactorRiskModel

self (fitted model)

get_exposures

get_exposures(data, date: Optional[str] = None) -> pd.DataFrame

Get factor exposures for a specific date.

Parameters:

Name Type Description Default
data

Data dict or LazyData

required
date Optional[str]

Date string (default: most recent)

None

Returns:

Type Description
DataFrame

DataFrame with stocks as rows, factors as columns

portfolio_risk

portfolio_risk(weights: Series, exposures: Optional[DataFrame] = None) -> Tuple[float, float, float]

Compute portfolio risk decomposition.

Parameters:

Name Type Description Default
weights Series

Portfolio weights indexed by ticker

required
exposures Optional[DataFrame]

Factor exposures (default: use fitted exposures)

None

Returns:

Type Description
Tuple[float, float, float]

Tuple of (total_risk, factor_risk, specific_risk) as annualized std

factor_attribution

factor_attribution(weights: Series, exposures: Optional[DataFrame] = None) -> pd.Series

Compute risk attribution to each factor.

Parameters:

Name Type Description Default
weights Series

Portfolio weights

required
exposures Optional[DataFrame]

Factor exposures (default: use fitted)

None

Returns:

Type Description
Series

Series with variance contribution of each factor

FactorDefinition dataclass

Definition of a style factor.