Module contents
Lesson 2 of 30Core 90 min

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 E[u(W)]E[u(W)] under the model’s axioms and when the expectation exists. An increasing affine transformation of uu 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

A(w)=−u′′(w)u′(w),R(w)=−wu′′(w)u′(w).A(w)=-\frac{u''(w)}{u'(w)},\qquad R(w)=-w\frac{u''(w)}{u'(w)}.

Concavity u′′<0u''<0 corresponds to local risk aversion. AA measures curvature with respect to absolute changes in wealth; RR expresses it with respect to proportional changes. Both are invariant under increasing affine transformations of utility.

With exponential utility u(w)=−e−awu(w)=-e^{-aw} for a>0a>0, absolute risk aversion is constant, A(w)=aA(w)=a, and relative risk aversion is R(w)=awR(w)=aw. With power utility

u(w)=w1−γ1−γ(γ>0, γ≠1),u(w)=log⁡w(γ=1),u(w)=\frac{w^{1-\gamma}}{1-\gamma}\quad(\gamma>0,\ \gamma\ne1), \qquad u(w)=\log w\quad(\gamma=1),

the domain is w>0w>0, relative risk aversion is constant at R(w)=γR(w)=\gamma, and absolute risk aversion is A(w)=γ/wA(w)=\gamma/w. These families express different assumptions about how attitudes to risk change with wealth.

Certainty equivalent and risk premium

The certainty equivalent CECE of uncertain wealth WW satisfies u(CE)=E[u(W)]u(CE)=E[u(W)], provided both sides are defined and the inverse exists. The risk premium in units of wealth is E[W]−CEE[W]-CE. For concave utility, Jensen’s inequality implies CE≤E[W]CE\le E[W].

For a small lottery around ww with a zero-mean perturbation of variance vv, Pratt’s local expansion gives

prima⁡≈12A(w)v.\operatorname{prima}\approx\tfrac12 A(w)v.

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.

InteractiveCurvature and certainty equivalent

The lottery pays 60 or 140, each with probability ½. The chord joins their utilities and its midpoint gives expected utility. The certainty equivalent is the guaranteed wealth with the same utility.

50150Final wealth WRescaled utility
  • Utility
  • Lottery chord
  • Certainty equivalent

The exact risk premium is E[W]−CE. Pratt’s local approximation is A(E[W])·Var(W)/2, where A(w)=−U″(w)/U′(w). It comes from a small-risk expansion and can differ substantially from the exact premium when the prizes are far apart.

For CARA, U(w)=(1−exp(−αw))/α when α>0 and U(w)=w when α=0. Absolute risk aversion stays constant at A(w)=α. The plot uses a positive affine transformation of U centered at E[W], which preserves the certainty equivalent.

The risk premium is zero for equal prizes or linear utility. Risk aversion expresses preferences in the model. See Pratt (1964).

Utility family
60
140
0.010
E[W]100.00
Certainty equivalent92.20
Exact risk premium7.80
Pratt approximation8.00
A(E[W])0.0100
R(E[W])1.000
Var(W)1600.00
Change the utility and payoffs, and compare the exact premium with its local approximation.

If W∼N(m,s2)W\sim N(m,s^2) and u(W)=−e−aWu(W)=-e^{-aW}, the normal moment-generating function gives E[u(W)]=−e−am+a2s2/2E[u(W)]=-e^{-am+a^2s^2/2} and, exactly,

CE=m−12as2.CE=m-\tfrac12as^2.

Thus, for the same aa and normally distributed wealth, maximizing expected utility is equivalent to maximizing mean minus a/2a/2 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 Dt=Rt−Rf,tD_t=R_t-R_{f,t} is

S=E[Dt]sd⁡(Dt).S=\frac{E[D_t]}{\operatorname{sd}(D_t)}.

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 Rt−MARtR_t-MAR_t by the square root of the mean of min⁡(Rt−MARt,0)2\min(R_t-MAR_t,0)^2 across all periods. MARMAR is the period’s minimum acceptable return; other conventions exist and must be stated.
  • Information: divide the mean of Rt−BtR_t-B_t by the standard deviation of that active return, with an explicit benchmark BtB_t.
  • 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 W0,…,WTW_0,\ldots,W_T, the running maximum and drawdown are

Ht=max⁡0≤s≤tWs,Dt=1−WtHt,MDD=max⁡0≤t≤TDt.H_t=\max_{0\le s\le t}W_s,\qquad D_t=1-\frac{W_t}{H_t},\qquad MDD=\max_{0\le t\le T}D_t.

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.

InteractiveAnatomy of a drawdown

Start at wealth 1 and follow a GBM path. The running peak includes initial wealth. The plot shows the path up to the selected session and keeps the scale fixed within each horizon.

  • Wealth
  • Running peak
  • Selected session

Drawdown from the previous peak

Time goes from 0 to 3 years. The plotted drawdown axis runs from −0.4 to 0.04.

Drawdown D=1−W/peak is nonnegative. The lower chart plots −D in decimals. The current drawdown has lasted 602 sessions so far. Recovery occurs when wealth reaches or exceeds the previous peak. Duration counts periods strictly below the peak. An open drawdown shows the elapsed time.

Mean maximum drawdown across the same 160 paths

1 year
18.43 %
Monte Carlo SE 0.48 %
3 years
28.53 %
Monte Carlo SE 0.70 %
5 years
33.63 %
Monte Carlo SE 0.75 %

Each horizon extends the same path prefix, so maximum drawdown can stay flat or increase even if wealth recovers. The means describe these 160 simulations. Monte Carlo error measures variation from simulation sampling.

The model uses dW/W=μdt+σdB with annual μ=8%, σ=20%, zero costs, seed 280202, and 252 sessions per year. The annualized instantaneous population Sharpe ratio at r=2% is (μ−r)/σ=0.30 at every horizon. Sample Sharpe estimates can differ.

Path horizon
756
Current wealth1.063
Current drawdown16.09 %
Maximum drawdown so far35.80 %
Open drawdown duration602 sesiones
Longest observed duration602 sesiones
Follow the peak, decline and episodes that have recovered or remain open.

From Kelly to Merton

Consider a risky asset with constant total drift μ\mu and volatility σ>0\sigma>0, and a risk-free asset with constant continuous rate rr. A constant fraction π\pi of wealth is held in the risky asset, with continuous rebalancing and no costs or constraints. Under geometric Brownian motion and positive initial wealth,

dWtWt=[r+π(μ−r)]dt+πσ dBt.\frac{dW_t}{W_t}=[r+\pi(\mu-r)]dt+\pi\sigma\,dB_t.

For CRRA utility with parameter γ>0\gamma>0 and a fixed horizon, the Merton fraction maximizing expected utility in this model is

π⋆=μ−rγσ2.\pi^\star=\frac{\mu-r}{\gamma\sigma^2}.

If μ\mu already denotes the premium over the risk-free asset, the numerator is simply μ\mu. To derive the solution, integrate the wealth equation and apply the normal exponential moment. If γ≠1\gamma\ne1, expected utility is

E[u(WT)]=W01−γ1−γexp⁡ ⁣((1−γ)T[r+π(μ−r)−12γπ2σ2]).E[u(W_T)]=\frac{W_0^{1-\gamma}}{1-\gamma} \exp\!\left((1-\gamma)T\left[r+\pi(\mu-r)-\tfrac12\gamma\pi^2\sigma^2\right]\right).

Although the prefactor changes sign when γ>1\gamma>1, the expectation still increases as the expression in brackets increases. That expression is a strictly concave parabola in π\pi: its derivative is (μ−r)−γπσ2(\mu-r)-\gamma\pi\sigma^2, which is zero at the fraction above. For γ=1\gamma=1, apply E[log⁡WT]E[\log W_T] directly or take the limit. We obtain logarithmic Kelly, whose expected growth rate is

g(π)=r+π(μ−r)−12π2σ2,g(\pi)=r+\pi(\mu-r)-\tfrac12\pi^2\sigma^2,

a parabola with its maximum at πK=(μ−r)/σ2\pi_K=(\mu-r)/\sigma^2. Half Kelly uses πK/2\pi_K/2, 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 g(π)<0g(\pi)<0, median wealth decreases with the horizon. In this continuous GBM, wealth remains positive at every finite time for finite π\pi: 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.

InteractiveGrowth and leverage

A risky asset has instantaneous drift μ and volatility σ. The remaining wealth is borrowed or invested at a continuous rate of r=2% per year. Rebalancing keeps L constant. The curve uses decimals for log growth, so 0.05 is 5% per year.

  • g(L)
  • Kelly
  • Half Kelly
  • Selected L

Fraction L ranges from 0 to 5.0. Annual growth ranges from −0.15 to 0.10.

In this model, g(L)=r+L(μ−r)−L²σ²/2. The maximum is the Kelly fraction L*=(μ−r)/σ². Half Kelly allocates L*/2 of total wealth.

Simulated wealth: log(Wₜ/W₀)

  • 80 paths
  • Theoretical log median

Time ranges from 0 to 3 years and log wealth from −1.0 to 1.0.

The axis shows log(Wₜ/W₀). The 80 Brownian paths stay fixed when you change the controls. The model uses 24 exact increments per year and seed 280201. After three years, median wealth is 1.211 times initial wealth.

If g(L)<0, the median falls over time. Wealth remains strictly positive at finite times in this continuous GBM for finite L. The optimum assumes known μ and σ and ignores costs, credit constraints, and jumps.

8
18
1.00×
Log growth g(L)6.38 %
Kelly fraction1.85×
Half Kelly0.93×
Zero crossing g(L) = 04.01×
Compare Kelly, half Kelly and paths sharing the same Brownian motions.

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.

[ ]Drawdown and durationBrowser
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.

[ ]Sharpe, Sortino, information and Calmar ratiosBrowser
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.

[ ]Check analytical casesBrowser
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.

[ ]Scaling a Gaussian sumBrowser
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.

[ ]Prepare the generator from the previous lessonBrowser
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.

[ ]Simulate the first blockBrowser
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')
[ ]Simulate block 2Browser
bloques.append(simular_bloque(280212))
print('Bloques completados:',len(bloques))
[ ]Simulate block 3Browser
bloques.append(simular_bloque(280213))
print('Bloques completados:',len(bloques))
[ ]Simulate block 4Browser
bloques.append(simular_bloque(280214))
print('Bloques completados:',len(bloques))
[ ]Compare growth and drawdownBrowser
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

ProofMean and variance from utility
Prove: Let W∼N(m,s2)W\sim N(m,s^2) and u(W)=−e−aWu(W)=-e^{-aW} with a>0a>0. Prove that ordering lotteries by expected utility is equivalent to ordering them by m−as2/2m-as^2/2.
The proof will appear here as you work.

Step 1 of 3. What is the expected value of e raised to −aW?

NumericThe Kelly fraction
An asset has continuous total drift μ=7% per year, risk-free rate r=2% and volatility σ=18%. Calculate the unconstrained continuous Kelly fraction.
NumericKelly growth
For the same μ=7%, r=2% and σ=18%, calculate the annual log growth rate at the optimum, as a percentage.
NumericThe deepest drawdown
For wealth values 100, 120, 90, 110, 80 and 130, calculate maximum drawdown as a positive percentage.
CodeDrawdown in one pass
Implement max_drawdown(wealth) and drawdown_duration(wealth), both in O(n). Each receives a nonempty sequence of strictly positive, finite wealth values including initial wealth, and must reject invalid input with ValueError. max_drawdown returns the largest magnitude 1−W_t/max_{s≤t}W_s. drawdown_duration returns the maximum number of consecutive periods with wealth strictly below the running maximum; the last episode counts even if unrecovered. Exactly recovering the maximum resets duration. Do not modify the input.
def max_drawdown(wealth):
  raise NotImplementedError('Implementa la caída máxima')

def drawdown_duration(wealth):
  raise NotImplementedError('Implementa la duración')
Shift+Enter to run
QuizA high Sharpe with no observed crash
A strategy sells options far out of the money and has had a Sharpe ratio of 3 for five years without a major crash. Which conclusion is strongest?

After solving the numerical exercises, this cell checks their figures.

[ ]Check Kelly and drawdownBrowser
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'])