Utility, risk aversion and performance measures
Explore expected utility, risk aversion, certainty equivalents, performance ratios, drawdown and the relationship between Kelly and Merton portfolio allocation.
After this lesson you can
- Derive the Arrow-Pratt coefficients of absolute and relative risk aversion and classify CARA and CRRA utilities.
- Calculate certainty equivalents and risk premiums exactly and using Pratt's approximation.
- Show that CARA utility with normal returns is equivalent to maximizing mean minus weighted variance.
- Calculate Sharpe, Sortino, information and Calmar ratios and maximum drawdown, and explain what each measures.
- Derive the Merton fraction and relate it to continuous and fractional Kelly.
Before you start
The same mean need not lead to the same decision
Two strategies can earn the same average return and leave very different outcomes in the worst scenarios. To decide, specify which consequences matter, what financing opportunities are available and what information you know before investing. No performance ratio makes those decisions for you.
Utility and risk aversion
In von Neumann and Morgenstern’s expected-utility framework, lotteries are compared by under the model’s axioms and when the expectation exists. An increasing affine transformation of preserves the preference ordering. The framework is a normative description with assumptions, not a guarantee that every human decision satisfies those axioms: choices in the Allais paradox are a classic empirical challenge.
For a twice-differentiable, increasing utility function, the Arrow-Pratt coefficients are
Concavity corresponds to local risk aversion. measures curvature with respect to absolute changes in wealth; expresses it with respect to proportional changes. Both are invariant under increasing affine transformations of utility.
With exponential utility for , absolute risk aversion is constant, , and relative risk aversion is . With power utility
the domain is , relative risk aversion is constant at , and absolute risk aversion is . These families express different assumptions about how attitudes to risk change with wealth.
Certainty equivalent and risk premium
The certainty equivalent of uncertain wealth satisfies , provided both sides are defined and the inverse exists. The risk premium in units of wealth is . For concave utility, Jensen’s inequality implies .
For a small lottery around with a zero-mean perturbation of variance , Pratt’s local expansion gives
This is a local approximation: its quality also depends on higher-order terms. Do not extrapolate it without checking to large losses or lotteries with difficult tails.
If and , the normal moment-generating function gives and, exactly,
Thus, for the same and normally distributed wealth, maximizing expected utility is equivalent to maximizing mean minus times variance. Quadratic utility also leads to a mean-variance expression when those moments exist, but ceases to be increasing outside a certain domain: over an unbounded normal distribution it does not describe globally monotone preferences. Outside particular families, mean and variance do not determine skewness, tails or expected utility.
Performance measures
The Sharpe ratio of a differential return series is
The risk-free series must match the period and funding convention. Historical Sharpe uses estimates of the mean and standard deviation and is uncertain. Multiplying every differential by the same positive constant leaves the ratio unchanged; different borrowing rates, constraints and costs break that simple comparison. Square-root-of-time annualization requires the autocovariance assumptions discussed in the previous lesson. See Sharpe.
Other risk-adjusted measures change the reference or denominator:
- Sortino: divide the mean of by the square root of the mean of across all periods. is the period’s minimum acceptable return; other conventions exist and must be stated.
- Information: divide the mean of by the standard deviation of that active return, with an explicit benchmark .
- Calmar: divide annualized compounded growth by the magnitude of maximum drawdown over the period studied. It depends on the length and dates of the sample.
When the denominator is zero, the ratio is undefined in this implementation. These measures answer different questions and may miss an extreme episode absent from the sample. Comparing strategies also requires considering costs, leverage, liquidity and out-of-sample scenarios.
Anatomy of a drawdown
For a positive path , the running maximum and drawdown are
Maximum drawdown is nonnegative. Depth alone does not describe duration: here we count consecutive periods strictly below the previous maximum, including an episode that remains unrecovered at the end. Reaching the previous maximum again closes the episode. Along the same path, extending the window forward cannot reduce maximum drawdown; two different histories or processes need not have that ordering.
From Kelly to Merton
Consider a risky asset with constant total drift and volatility , and a risk-free asset with constant continuous rate . A constant fraction of wealth is held in the risky asset, with continuous rebalancing and no costs or constraints. Under geometric Brownian motion and positive initial wealth,
For CRRA utility with parameter and a fixed horizon, the Merton fraction maximizing expected utility in this model is
If already denotes the premium over the risk-free asset, the numerator is simply . To derive the solution, integrate the wealth equation and apply the normal exponential moment. If , expected utility is
Although the prefactor changes sign when , the expectation still increases as the expression in brackets increases. That expression is a strictly concave parabola in : its derivative is , which is zero at the fraction above. For , apply directly or take the limit. We obtain logarithmic Kelly, whose expected growth rate is
a parabola with its maximum at . Half Kelly uses , sacrificing some optimal growth under the model in exchange for lower exposure. The formula is sensitive to the estimated premium and does not itself incorporate costs, constraints or jumps. Merton studies a broader continuous problem; here we fix constant fractions and exclude consumption.
If , median wealth decreases with the horizon. In this continuous GBM, wealth remains positive at every finite time for finite : negative growth is not a point of ruin. With discrete rebalancing and leverage, however, a large enough loss can take wealth to zero or below; insolvency must be defined and the path stopped before taking logarithms.
Lab: metrics with explicit conventions
We implement the metrics from scratch. To avoid ambiguity, drawdown uses a path including initial wealth; an exact recovery to the previous maximum ends its duration. Ratios with zero denominators return nan rather than an artificial zero-performance signal.
import numpy as np
def trayectoria_drawdown(riqueza):
w=np.asarray(riqueza,dtype=float)
if w.ndim!=1 or len(w)==0 or not np.isfinite(w).all() or np.any(w<=0):
raise ValueError('Se requiere una trayectoria positiva y finita')
maximos=np.maximum.accumulate(w)
caida=1-w/maximos
duracion=np.zeros(len(w),dtype=int)
actual=0
for i in range(len(w)):
actual=actual+1 if w[i]<maximos[i] else 0
duracion[i]=actual
return {'drawdown':caida,'max_drawdown':float(caida.max()),
'duracion':duracion,'duracion_max':int(duracion.max())}
ejemplo=trayectoria_drawdown([100,125,100,110,90,140])
print('Drawdowns:',np.round(ejemplo['drawdown'],4))
print('Máximo:',ejemplo['max_drawdown'],'| duraciones:',ejemplo['duracion'])The next calculation annualizes means linearly and standard deviations by the square root of time, a convention that must be justified in view of temporal dependence. For Sortino we apply the same scaling to per-period downside; it is not a general identity for downside over a compounded year. The information ratio compares with the chosen benchmark and Calmar uses compounded wealth growth.
def metricas_desempeno(r, rf=0., benchmark=0., mar=0., periodos=252):
r=np.asarray(r,dtype=float)
if r.ndim!=1 or len(r)<2 or not np.isfinite(r).all() or np.any(r<=-1):
raise ValueError('Rendimientos simples finitos mayores que −1')
if not isinstance(periodos,(int,np.integer)) or periodos<=0:
raise ValueError('La frecuencia debe ser un entero positivo')
def igualar(valor):
arr=np.asarray(valor,dtype=float)
if arr.ndim==0:
arr=np.full(len(r),arr)
if arr.shape!=r.shape or not np.isfinite(arr).all():
raise ValueError('Referencia incompatible o no finita')
return arr
rf,benchmark,mar=(igualar(v) for v in (rf,benchmark,mar))
exceso=r-rf
activo=r-benchmark
downside=np.sqrt(np.mean(np.minimum(r-mar,0)**2))
def razon(numerador,denominador):
return float(numerador/denominador) if denominador>0 else np.nan
def desviacion_muestral(x):
return 0. if np.all(x==x[0]) else float(x.std(ddof=1))
sharpe=razon(exceso.mean()*periodos,desviacion_muestral(exceso)*np.sqrt(periodos))
sortino=razon((r-mar).mean()*periodos,downside*np.sqrt(periodos))
informacion=razon(activo.mean()*periodos,desviacion_muestral(activo)*np.sqrt(periodos))
riqueza=np.r_[1.,np.cumprod(1+r)]
dd=trayectoria_drawdown(riqueza)
crecimiento=np.expm1(np.log(riqueza[-1])*periodos/len(r))
return {'sharpe':sharpe,'sortino':sortino,'informacion':informacion,
'calmar':razon(crecimiento,dd['max_drawdown']),
'crecimiento_anual':float(crecimiento),**dd}Simple cases let us check conventions before analyzing historical data. A constant-return series has zero excess-return standard deviation; a continuously increasing path has zero maximum drawdown. Neither case permits replacing a zero denominator with an arbitrary finite number.
constante=metricas_desempeno(np.full(12,.01),periodos=12)
salto=metricas_desempeno(np.array([0.,-.25,1/3]),periodos=3)
print('Serie constante: Sharpe definido:',np.isfinite(constante['sharpe']),
'| Calmar definido:',np.isfinite(constante['calmar']))
print('Caída y recuperación: máximo',salto['max_drawdown'],
'| duración máxima',salto['duracion_max'])
print('Caída sin recuperar:',trayectoria_drawdown([1.,1.2,.9,.8])['duracion_max'])The square-root-of-time approximation can also be checked against GBM paths, where independent log increments make variance scaling exact. We use a sample standard deviation across many paths; this is a Monte Carlo check, not an exact theoretical value.
rng=np.random.default_rng(280201)
desviacion=.012
incrementos=rng.normal(0,desviacion,size=(5000,252))
vol_un_dia=incrementos[:,0].std(ddof=1)
vol_suma=incrementos.sum(axis=1).std(ddof=1)
print('Volatilidad diaria estimada:',round(float(vol_un_dia),5))
print('Volatilidad de la suma estimada:',round(float(vol_suma),5),
'| valor teórico:',round(float(desviacion*np.sqrt(252)),5))Discrete Kelly under heavy tails
We reuse the current generator from the previous lesson exactly. Rather than assume the GBM formula remains optimal, we choose several exposures using a hypothetical premium and volatility, then observe what happens under the other mechanism. The Student-t log-return model has no finite exponential expectation: sample mean wealth does not estimate a finite model expectation.
For each period we convert the asset’s log return to a simple return. The portfolio rebalances to the chosen fraction while wealth is positive and finances the remainder at the risk-free rate. If the wealth factor becomes non-positive, we define insolvency, set wealth to zero and stop that path. This is a simulation convention, not a description of actual margin rules.
import numpy as np
def mercado_sintetico(n, caminos=1, semilla=280101, burn=1000,
mu=.0002, var_base=.0001, alpha=.055,
beta=.75, gamma=.2, nu=8., intensidad=.01,
media_salto=0., escala_salto=.025):
"""Rendimientos logarítmicos con mecanismos explícitos y semillas fijas."""
if (not isinstance(n, int) or not isinstance(caminos, int)
or not isinstance(burn, int) or n < 1 or caminos < 1 or burn < 0):
raise ValueError('Dimensiones y burn deben ser enteros válidos')
valores = (mu,var_base,alpha,beta,gamma,nu,intensidad,media_salto,escala_salto)
if not np.isfinite(valores).all() or min(alpha,beta,gamma,intensidad,escala_salto)<0:
raise ValueError('Parámetros no finitos o negativos')
persistencia=alpha+beta+gamma/2
if var_base<=0 or nu<=2 or persistencia>=1:
raise ValueError('Se necesita varianza positiva, nu>2 y persistencia<1')
omega=var_base*(1-persistencia)
transicion=np.array([[.985,.015],[.05,.95]])
multiplicadores=np.array([.75,1.5])
rng=np.random.default_rng(semilla)
forma=(n+burn,caminos)
uniformes=rng.random(forma)
innovaciones=rng.standard_t(nu,size=forma)*np.sqrt((nu-2)/nu)
cuentas=rng.poisson(intensidad,size=forma)
saltos_generados=(cuentas*media_salto+
np.sqrt(cuentas)*escala_salto*rng.normal(size=forma))
varianza=np.full(caminos,var_base)
anterior=np.zeros(caminos)
estado=np.zeros(caminos,dtype=int)
rend=np.empty((n,caminos))
volatilidad=np.empty_like(rend)
regimen=np.empty((n,caminos),dtype=int)
saltos=np.empty_like(rend)
for instante in range(n+burn):
varianza=omega+(alpha+gamma*(anterior<0))*anterior**2+beta*varianza
estado=(uniformes[instante]<transicion[estado,1]).astype(int)
innovacion=np.sqrt(varianza)*innovaciones[instante]
salto=saltos_generados[instante]
if instante>=burn:
indice=instante-burn
rend[indice]=mu+multiplicadores[estado]*innovacion+salto
volatilidad[indice]=np.sqrt(varianza)
regimen[indice]=estado
saltos[indice]=salto
anterior=innovacion
return {'r':rend,'sigma_base':volatilidad,'regimen':regimen,
'salto':saltos,'transicion':transicion,'omega':omega,
'persistencia':persistencia,'nu':nu}To construct exposures, we assume total drift of 7%, a rate of 2% and volatility of 18% in a reference GBM. For sensitivity, fractions calculated with assumed drifts of 6% and 8% are also shown. Those numbers are not the true mean or volatility of the heavy-tailed generator.
def simular_bloque(semilla, caminos=2500, periodos=252):
mercado=mercado_sintetico(periodos,caminos=caminos,semilla=semilla,burn=200)
log_activo=mercado['r']
with np.errstate(over='ignore',invalid='ignore'):
activo=np.expm1(log_activo)
if not np.isfinite(activo).all():
raise ValueError('El retorno simple excede el rango numérico')
tasa_anual=.02
rf=np.expm1(tasa_anual/periodos)
volatilidad_supuesta=.18
kelly_central=(.07-tasa_anual)/volatilidad_supuesta**2
exposiciones=np.array([0.,kelly_central/2,
(.06-tasa_anual)/volatilidad_supuesta**2,
kelly_central,(.08-tasa_anual)/volatilidad_supuesta**2,
2*kelly_central])
riqueza=np.ones((len(exposiciones),caminos))
pico=np.ones_like(riqueza)
peor=np.zeros_like(riqueza)
insolvente=np.zeros_like(riqueza,dtype=bool)
for r in activo:
factor=1+rf+exposiciones[:,None]*(r[None,:]-rf)
quiebra=(factor<=0)&(~insolvente)
insolvente|=quiebra
riqueza=np.where(insolvente,0.,riqueza*np.maximum(factor,0.))
if not np.isfinite(riqueza).all():
raise ValueError('La riqueza excede el rango numérico')
pico=np.maximum(pico,riqueza)
peor=np.maximum(peor,1-riqueza/pico)
return {'exposiciones':exposiciones,'riqueza':riqueza,
'max_drawdown':peor,'insolvente':insolvente}
bloques=[]
bloques.append(simular_bloque(280211))
print('Primer bloque:',bloques[-1]['riqueza'].shape[1],'caminos')bloques.append(simular_bloque(280212))
print('Bloques completados:',len(bloques))bloques.append(simular_bloque(280213))
print('Bloques completados:',len(bloques))bloques.append(simular_bloque(280214))
print('Bloques completados:',len(bloques))riquezas=np.concatenate([b['riqueza'] for b in bloques],axis=1)
caidas=np.concatenate([b['max_drawdown'] for b in bloques],axis=1)
insolvencias=np.concatenate([b['insolvente'] for b in bloques],axis=1)
n=riquezas.shape[1]
etiquetas=('Sin activo','Medio Kelly','Kelly con deriva 6 %',
'Kelly con deriva 7 %','Kelly con deriva 8 %','Doble Kelly')
for i,nombre in enumerate(etiquetas):
mediana=float(np.median(riquezas[i]))
prob=float(np.mean(caidas[i]>.5))
error=np.sqrt(prob*(1-prob)/n)
quiebras=int(insolvencias[i].sum())
print(nombre,'| fracción',round(float(bloques[0]['exposiciones'][i]),3),
'| mediana riqueza',round(mediana,4),
'| P(drawdown>50%)',round(prob,4),'| EE Monte Carlo',round(float(error),4),
'| insolvencias',quiebras,'de',n)
print('Las probabilidades describen este mecanismo y horizonte, no garantizan resultados futuros.')Exercises
Step 1 of 3. What is the expected value of e raised to −aW?
def max_drawdown(wealth):
raise NotImplementedError('Implementa la caída máxima')
def drawdown_duration(wealth):
raise NotImplementedError('Implementa la duración')After solving the numerical exercises, this cell checks their figures.
mu,rf,sigma=.07,.02,.18
kelly=(mu-rf)/sigma**2
crecimiento=rf+kelly*(mu-rf)-.5*kelly**2*sigma**2
dd=trayectoria_drawdown([100,120,90,110,80,130])
print('Fracción Kelly:',kelly,'| crecimiento anual:',crecimiento)
print('Drawdown máximo:',dd['max_drawdown'],'| duración máxima:',dd['duracion_max'])