Module contents
Lesson 1 of 30Review 80 min

Returns, prices and stylized facts of markets

A concise introduction to adjusted prices, simple and log returns, compounding, time aggregation, annualization, stylized facts, public data and a synthetic market with known dynamics.

After this lesson you can

  • Convert simple and log returns and aggregate them across time and assets.
  • Explain volatility drag and relate arithmetic mean, geometric mean and variance.
  • Annualize means and volatility and identify when autocorrelation invalidates square-root-of-time scaling.
  • Measure stylized facts using kurtosis, the ACF of returns and absolute returns, and return-volatility asymmetry.
  • Build a synthetic GARCH-t generator with jumps and regimes for use throughout this module.
  • Download and adjust public data from French, FRED and Stooq, accounting for dividends, splits and publication dates.

Before you start

What has an investment really earned?

A price of 200 does not tell you how much its owner has earned. You need the previous price, payments received and changes in the number of shares. The average return alone is not enough either: two paths with the same arithmetic mean can end with very different wealth.

This module’s basic language consists of returns, their distributions and the data that generate them. Frequency, adjustment and availability date are part of the statistical problem.

Simple and log returns

If Pt>0P_t>0 is a wealth index that incorporates payments according to a stated rule, the simple return and the log return are

Rt=PtPt−1−1,rt=log⁡(1+Rt),Rt=ert−1.R_t=\frac{P_t}{P_{t-1}}-1,\qquad r_t=\log(1+R_t),\qquad R_t=e^{r_t}-1.

If all prices are positive, log returns add exactly over time:

log⁡PTP0=∑t=1Trt,1+R0:T=∏t=1T(1+Rt).\log\frac{P_T}{P_0}=\sum_{t=1}^T r_t,\qquad 1+R_{0:T}=\prod_{t=1}^T(1+R_t).

Adding simple returns approximates the result only when cross products are small. A 100% loss takes wealth to zero and makes the logarithm non-finite; a position with non-positive wealth requires another definition.

For a portfolio with starting weights wiw_i summing to one and no intraperiod flows, the simple return is Rp=∑iwiRiR_p=\sum_i w_iR_i. Its log return is log⁡(1+∑iwiRi)\log(1+\sum_iw_iR_i), not the weighted mean of log⁡(1+Ri)\log(1+R_i). Weights change after price movements unless you rebalance. With short positions or leverage, also check that portfolio value and the argument of the logarithm remain positive.

Growth and volatility drag

The arithmetic mean describes average return per period; the geometric mean describes compounded growth along a path. For R>−1R>-1 and suitable moments, Jensen’s inequality gives

E[log⁡(1+R)]≤log⁡(1+E[R]).E[\log(1+R)]\leq\log(1+E[R]).

For small returns and a controlled Taylor approximation,

E[log⁡(1+R)]≈E[R]−12E[R2].E[\log(1+R)]\approx E[R]-\tfrac12E[R^2].

The difference is a consequence of multiplying variable returns. The approximation requires the omitted terms to be small; it is not an identity for every distribution or for losses close to 100%.

In the continuous model dPt/Pt=μ dt+σ dWtdP_t/P_t=\mu\,dt+\sigma\,dW_t with constant coefficients, volatility drag is exact:

log⁡(PT/P0)=(μ−12σ2)T+σWT.\log(P_T/P_0)=(\mu-\tfrac12\sigma^2)T+\sigma W_T.

Median wealth is P0e(μ−σ2/2)TP_0e^{(\mu-\sigma^2/2)T} and expected wealth is P0eμTP_0e^{\mu T}. The distribution’s mean and a typical path answer different questions. If the expected one-year simple return is fixed at 8%, then in this model μ=log⁡(1.08)\mu=\log(1.08) rather than 0.080.08; the median falls when σ2/2>μ\sigma^2/2>\mu.

InteractiveThe difference between mean and median

Start with one unit of wealth. The 1000 paths share the same Brownian motions when σ changes. Each line shows a possible path over three years. The vertical axis is logarithmic and the dashed line shows the theoretical median.

  • Simulated paths
  • Theoretical mean wealth
  • Theoretical median
0.371.002.720123Time in years

Across these 1000 paths, final sample mean and median are 1.242 and 1.134. A few very large terminal values can move the sample mean substantially.

The model is dS/S=μdt+σdW with μ=log(1.08), seed 280101, and 24 steps per year simulated with exact Brownian increments. At one year, E[S₁/S₀−1]=8%. At horizon t, E[Sₜ/S₀]=exp(μt) and the median is exp((μ−σ²/2)t).

Median log growth changes sign at σ=√(2 log(1.08))≈39.23 %. Above this value, the distribution's median falls even as mean wealth continues to grow.

25
Expected one-year simple return8.00%
Annual median log growth4.57 %
Theoretical mean at 3 years1.260
Theoretical median at 3 years1.147
Change volatility and observe 1000 paths with the same expected annual mean.

Aggregating over time and annualizing risk

Let rtr_t be a weakly stationary series with variance γ0\gamma_0 and autocovariance γk\gamma_k at lag kk. The variance of the sum of nn returns is

Var⁡(∑t=1nrt)=nγ0+2∑k=1n−1(n−k)γk.\operatorname{Var}\left(\sum_{t=1}^n r_t\right) =n\gamma_0+2\sum_{k=1}^{n-1}(n-k)\gamma_k.

The square-root-of-time rule is therefore exact for the standard deviation of the sum when the relevant autocovariances are zero. With ρk=γk/γ0\rho_k=\gamma_k/\gamma_0, the correction multiplies single-period volatility by

n+2∑k=1n−1(n−k)ρk.\sqrt{n+2\sum_{k=1}^{n-1}(n-k)\rho_k}.

If the weighted sum of autocovariances is positive, aggregate risk exceeds the naive rule; if it is negative, risk is lower. One positive lag alone does not determine the sign of the whole sum. The identity applies to sums of returns, particularly log returns. It is not an exact formula for compounded simple returns without further assumptions. The mean of the sum is nE[rt]nE[r_t] when the mean is constant; converting that to an average simple return requires more information about the distribution.

InteractiveWhen square-root-of-time scaling fails

Take increments Rₜ = ρRₜ₋₁ + √(1 − ρ²)εₜ with |ρ| < 1, independent standard-normal innovations, and an independent initial state drawn from the stationary distribution. Each increment has mean zero and standard deviation one. The sum of n increments has standard deviation √[n + 2∑ₖ₌₁ⁿ⁻¹(n − k)ρᵏ].

The square-root-of-time rule multiplies the one-period standard deviation by √n. The chart compares standard deviations in units of the one-period standard deviation.

  • Exact standard deviation / √n rule
  • Agreement with the rule
0.00.51.01.51.9163126189252Number of periods

Positive persistence adds positive covariances, so the rule underestimates the standard deviation of the sum. The readout compares standard deviations. The vertical axis rescales to keep the full curve visible.

The comparison uses a 252-period horizon for this stationary AR(1) example. Real returns can have other forms of dependence or time-varying volatility. The √n rule is exact when aggregate covariance is zero, which can occur even with dependence.

0.50
Exact standard deviation, 252 periods27.42
√252 rule15.87
Difference relative to the rule72.7 %
Change the autocorrelation of a stationary AR(1) and compare the standard deviations.

Using 252 sessions is a convention for stock-market examples, not a universal constant. Holidays, continuously traded assets, intraday data and different calendars change the aggregation. For the relationship between temporal dependence and annualization of risk-adjusted measures, see Lo, The Statistics of Sharpe Ratios.

Adjustments and payment distributions

A stock split can halve the price per share and double the number of shares without destroying half the owner’s wealth. Dividends are paid outside the price series; ignoring them makes price return different from total return. The adjusted price depends on the provider’s convention: find out which events it incorporates, when dividends are reinvested and whether taxes or costs apply.

An adjusted history can change retrospectively when new events occur. For a reproducible study, retain the source, download date, adjustment rules and, where relevant, the versions available on each historical date. A price series for companies that survive today does not by itself represent the tradable universe in the past.

InteractiveThe unadjusted-price trap

Start with one share at 100 currency units. Before events, its price grows by 0.04% per period. A dividend is paid in periods 63, 126, 189, and 252, at 0.50 per share before the split and 0.25 afterward. At period 126, the dividend comes first. The split turns each share into two and halves the price. Cash is reinvested at the post-event price without taxes or costs.

  • Raw price per share
  • Wealth with dividends reinvested
  • Dividend event
0306090120DDDD063126189252split 2:1Period

D marks a dividend payment. At the split date, the raw price halves and the share count doubles before reinvestment, preserving wealth at the split. The adjustment halves pre-split prices and then rescales the whole series to start at 100.

The 20-period momentum compares the displayed prices at periods 126 and 106. The raw series shows a mechanical drop from the split. Adjusting the price removes that jump, while total wealth also includes shares acquired with each dividend. Both curves come from the deterministic model.

Final raw price per share54.26
Final wealth with reinvestment110.60
Final share count2.0383
20-period momentum at the split−49.84 %
Compare the price per share, split adjustment and wealth with reinvested dividends.

Stylized facts and their limits

Financial series often exhibit heavier tails than a fitted normal distribution, volatility clustering and dependence in nonlinear functions of returns, even when linear return autocorrelation is small. The leverage effect describes an asymmetric relationship between negative movements and subsequent volatility in certain markets. As horizons are aggregated, some distributions approach a normal distribution, although the speed and shape depend on the series and period. Cont discusses these facts and their nuances.

Measure kurtosis, the proportion of extreme observations, the ACF of rtr_t and ∣rt∣|r_t|, and the relationship between rtr_t and ∣rt+1∣|r_{t+1}| separately. Lack of linear autocorrelation does not imply independence: a sequence with changing conditional volatility can have correlated squares or absolute values. Conclusions also depend on frequency, sample size, microstructure and multiple testing; an isolated result does not make a fact a universal law.

InteractiveStylized-facts detector

Generate 6000 daily log returns after discarding the first 1,000 steps. The diagnostics use consecutive non-overlapping blocks of 1 days. Longer horizons leave fewer blocks and greater uncertainty.

Standardized histogram: log₁₀ density

The line shows the standard normal density. The plot omits empty bars and 34 observations outside [−4, 4), though the readouts still include those observations.

Quantiles versus the normal distribution

Standardized empirical quantiles from the 2nd to 98th percentiles use linear interpolation. Proximity to the diagonal is a descriptive diagnostic.

  • Sample
  • Normal reference

Autocorrelation by block lag

  • r
  • |r|

Sample ACF divides centered lagged products by the total sum of squares and uses lags 1 to 20. The correlations and kurtosis are descriptive statistics. A negative correlation between rₜ and |rₜ₊₁| can suggest volatility asymmetry, whose cause requires further evidence.

Gaussian returns use r=0.01Z with iid standard-normal Z. In GJR-t, εₜ=√hₜ Zₜ and Z is t-distributed with 8 degrees of freedom, standardized to unit variance. The update is hₜ₊₁=ω+0.03εₜ²+0.10εₜ²·1(εₜ<0)+0.88hₜ, with ω=0.000004. The jumps option adds a Poisson(0.018) number of normal jumps with standard deviation 0.04 per day and switches ω between 0.000004 and 0.000016 using a two-state regime with switching probabilities 0.005 and 0.02. The variance update excludes jumps. Seed 280102.

The two t-models describe log returns. An untruncated t distribution has no finite positive exponential moment, so the theoretical mean price is not finite. Changing the seed changes the figures. These models illustrate selected market properties and aggregation diagnostics.

Return model
Non-overlapping aggregation
Observed blocks6000
Sample excess kurtosis8.71
ACF of r, lag 1−0.052
ACF of |r|, lag 10.292
Correlation of rₜ with |rₜ₊₁|−0.038
Compare three simulated mechanisms and change the aggregation horizon.

A synthetic market with known mechanisms

A generator lets us test a method when we know the mechanism producing the data. We will combine normalized Student-t innovations, GARCH-type conditional variance, jumps and a Markov regime. To introduce asymmetry explicitly, the lab includes a GJR extension:

zt=tν,t(ν−2)/ν,ϵt=σtzt,σt2=ω+(α+γ1{ϵt−1<0})ϵt−12+βσt−12,rt=μ+mStϵt+Jt.\begin{aligned} z_t&=t_{\nu,t}\sqrt{(\nu-2)/\nu},\qquad \epsilon_t=\sigma_tz_t,\\ \sigma_t^2&=\omega+ \left(\alpha+\gamma\mathbf1_{\{\epsilon_{t-1}<0\}}\right) \epsilon_{t-1}^2+\beta\sigma_{t-1}^2,\\ r_t&=\mu+m_{S_t}\epsilon_t+J_t. \end{aligned}

Here StS_t is a Markov chain, JtJ_t is a sum of a Poisson number of jumps, and mStm_{S_t} scales the innovation according to the regime. Setting γ=0\gamma=0 recovers symmetric GARCH. If innovations are symmetric with unit variance, a common condition for the unconditional variance of the isolated GJR process is α+β+γ/2<1\alpha+\beta+\gamma/2<1, with nonnegative parameters. The fourth-moment condition is stricter: among other conditions, it requires E ⁣[((α+γ1{z<0})z2+β)2]<1E\!\left[\left((\alpha+\gamma\mathbf1_{\{z<0\}})z^2+\beta\right)^2\right]<1. A Student-t has finite variance if ν>2\nu>2 and finite fourth moment if ν>4\nu>4.

Regimes and jumps alter the observed distribution; one realization does not guarantee that every diagnostic will be significant. In particular, combining symmetric GARCH with independent symmetric jumps and regimes does not automatically introduce leverage. Asymmetry must be present in the equations and checked.

There is a further limitation: an untruncated Student-t log return has no finite positive exponential moment. Thus, even though each simulated path has finite wealth, the theoretical expectation of erte^{r_t} may be infinite. Do not interpret this generator’s sample mean wealth as a stable estimate of a finite expectation; to study that quantity, use a model with appropriate exponential moments.

Public sources and data hygiene

The Kenneth French Data Library publishes daily factors in percent. Mkt−RFMkt-RF is an excess over RFRF: add them and divide by 100 to reconstruct the market’s simple return. SMBSMB and HMLHML are portfolio spreads, not asset prices to transform without considering their meaning.

The library reports a change in CRSP data format: the December 2024 release was the last based on FIZ, and releases from January 2025 use CIZ. The monthly dividend-reinvestment convention also changed. Record the version and download date when comparing historical results. Free access does not imply unrestricted permission to redistribute files.

FRED collects macroeconomic and financial series, but their units vary. For example, DGS3MO is an annualized rate expressed as a percentage, not an observed daily bond return. The date a value refers to is not necessarily its publication date or time, and it may be revised. ALFRED and real-time periods let you query historical versions available on a given date.

Stooq offers historical downloads, but check the adjustments and terms of use for each file: do not assume a closing price includes dividends or that you may redistribute it. For crypto, Coinbase Exchange candles are one possible source: its documentation warns about per-request limits and intervals without trades. State the platform, asset universe and time zone; a market trading every day does not automatically share an exchange calendar.

In a check on November 4, 2026, an automated Stooq request returned a verification page instead of a CSV; we do not have a verified automated download. If you download a file from its site, check that it contains dates and prices for the expected instrument, review its adjustment documentation and license, and keep a copy with the access date. Before correcting for splits or dividends, confirm whether the provider already incorporated them: applying an adjustment twice also distorts the series. The interactive example uses explicit synthetic events, while the lab below uses real excerpts from French and FRED.

Data hygiene also requires preserving missing values, avoiding filling with future information, aligning closes to the appropriate time zone and distinguishing observation date from publication date. Joining by calendar date without considering the time can introduce look-ahead.

Lab: a market with known ground truth

The generator returns log returns, base volatility, the regime and the contribution of jumps. Time recursion is necessary because variance depends on the past; paths are computed in parallel. The parameters are model values, not estimates from a real market.

[ ]GJR-t generator with jumps and regimesBrowser
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}

mercado=mercado_sintetico(12000)
r=mercado['r'][:,0]
print('Observaciones:',len(r),'| persistencia base:',mercado['persistencia'])
print('Omega:',mercado['omega'],'| grados de libertad:',mercado['nu'])
print('Fracción en régimen 1:',round(float(mercado['regimen'].mean()),4))

The sum of a Poisson number of normal jumps is generated using the fact that, conditional on the number NN, their sum has mean NμJN\mu_J and standard deviation N σJ\sqrt N\,\sigma_J. The displayed variance is that of the GJR innovation before scaling it by the regime and adding jumps. The synthetic generator does not attempt to reproduce the full structure of any asset.

[ ]Check moments and diagnosticsBrowser
from math import erfc, sqrt

def acf_muestral(x, max_lag):
    x=np.asarray(x,dtype=float)
    if x.ndim!=1 or len(x)<=max_lag or max_lag<0 or not np.isfinite(x).all():
        raise ValueError('Serie o retardos inválidos')
    centrada=x-x.mean()
    denominador=centrada @ centrada
    if denominador==0:
        raise ValueError('La serie debe tener variación')
    return np.array([float(centrada[k:] @ centrada[:len(x)-k]/denominador)
                     for k in range(max_lag+1)])

def hechos_estilizados(x, max_lag=20):
    x=np.asarray(x,dtype=float)
    centrada=x-x.mean()
    varianza=float(np.mean(centrada**2))
    if varianza<=0 or not np.isfinite(varianza):
        raise ValueError('La varianza debe ser positiva y finita')
    extremos=float(np.mean(np.abs(centrada)>4*np.sqrt(varianza)))
    return {'exceso_curtosis':float(np.mean(centrada**4)/varianza**2-3),
            'mas_de_4_sigma':extremos,
            'normal_mas_de_4_sigma':erfc(4/sqrt(2)),
            'acf_r':acf_muestral(x,max_lag),
            'acf_abs_r':acf_muestral(np.abs(x),max_lag),
            'correlacion_apalancamiento':float(np.corrcoef(x[:-1],np.abs(x[1:]))[0,1])}

informe=hechos_estilizados(r)
print('Exceso de curtosis:',round(informe['exceso_curtosis'],3))
print('Fracción más allá de 4 desviaciones:',round(informe['mas_de_4_sigma'],6),
      '| referencia normal:',round(informe['normal_mas_de_4_sigma'],6))
print('ACF retardos 1 a 5 de r:',np.round(informe['acf_r'][1:6],3))
print('ACF retardos 1 a 5 de |r|:',np.round(informe['acf_abs_r'][1:6],3))
print('Correlación r_t con |r_(t+1)|:',
      round(informe['correlacion_apalancamiento'],4))

An estimated autocorrelation or tail difference needs an uncertainty assessment to support a conclusion. Kurtosis can vary greatly across samples, and its interpretation depends on the corresponding moments existing.

[ ]Diagnose the base fourth momentBrowser
alpha,beta,gamma,nu=.055,.75,.2,8.
cuarto_z=3*(nu-2)/(nu-4)
factor_cuarto=(beta**2+2*beta*(alpha+gamma/2)
               +(alpha**2+alpha*gamma+gamma**2/2)*cuarto_z)
print('E[z^4]:',cuarto_z,'| factor del cuarto momento GJR:',round(factor_cuarto,6))
print('Condición del cuarto momento base satisfecha:',factor_cuarto<1)

Downloaded public data

This cell includes a literal excerpt of French daily factors and DGS3MO from January to April 2024, downloaded on November 2, 2026. The French download preamble identifies September 2026 CRSP data: this is a version accessed today, not a copy of the information available in 2024. The parsers also accept the full CSV text downloaded from the linked sources. The outer join preserves dates and missing data without looking ahead or filling values; matching dates do not prove that a rate was available at decision time.

The exercise compares one real window with an equally long window from the generator above. These are descriptive statistics for one window and one simulation; square-root annualization is an approximation whose zero-autocovariance assumption you should examine.

[ ]Align public factors and ratesBrowser
"""Extracto literal de French y FRED; ejecuta antes la celda del generador GJR."""
import csv
import io
import math
from datetime import date, datetime
from statistics import mean, stdev

# Fuente: F-F Research Data Factors Daily, archivo completo del repositorio
# de Kenneth French, filas literales del 2 de enero al 30 de abril de 2024.
FRENCH_CSV = ''',Mkt-RF,SMB,HML,RF
20240102,   -0.70,   -0.55,    0.79,    0.02
20240103,   -1.01,   -1.94,   -0.10,    0.02
20240104,   -0.33,    0.21,    0.09,    0.02
20240105,    0.15,   -0.81,    0.63,    0.02
20240108,    1.49,    0.90,   -1.27,    0.02
20240109,   -0.21,   -0.44,   -0.89,    0.02
20240110,    0.51,   -0.10,   -0.44,    0.02
20240111,   -0.14,   -0.45,   -0.51,    0.02
20240112,   -0.01,   -0.10,   -0.48,    0.02
20240116,   -0.47,   -0.76,   -0.61,    0.02
20240117,   -0.59,   -0.08,   -0.24,    0.02
20240118,    0.87,   -0.10,   -0.35,    0.02
20240119,    1.19,   -0.47,    0.67,    0.02
20240122,    0.38,    1.74,    0.58,    0.02
20240123,    0.22,   -0.65,   -0.55,    0.02
20240124,   -0.01,   -0.74,    0.06,    0.02
20240125,    0.46,    0.04,    0.57,    0.02
20240126,   -0.02,    0.41,   -0.28,    0.02
20240129,    0.85,    1.07,   -0.58,    0.02
20240130,   -0.12,   -1.27,    0.85,    0.02
20240131,   -1.74,   -0.92,   -0.29,    0.02
20240201,    1.22,    0.63,   -1.35,    0.02
20240202,    0.99,   -1.43,   -0.51,    0.02
20240205,   -0.42,   -0.73,   -0.66,    0.02
20240206,    0.27,    0.85,   -0.47,    0.02
20240207,    0.77,   -0.90,   -0.61,    0.02
20240208,    0.21,    1.49,    0.02,    0.02
20240209,    0.65,    1.00,   -0.42,    0.02
20240212,    0.04,    1.29,    1.11,    0.02
20240213,   -1.60,   -2.41,   -0.65,    0.02
20240214,    1.14,    1.57,   -0.22,    0.02
20240215,    0.67,    0.85,    1.04,    0.02
20240216,   -0.53,   -0.66,   -0.18,    0.02
20240220,   -0.73,   -0.87,    0.33,    0.02
20240221,   -0.02,   -0.82,    0.14,    0.02
20240222,    2.02,   -1.20,   -1.29,    0.02
20240223,    0.02,    0.28,    0.00,    0.02
20240226,   -0.26,    1.00,   -0.12,    0.02
20240227,    0.26,    1.20,   -0.44,    0.02
20240228,   -0.26,   -0.86,   -0.01,    0.02
20240229,    0.53,   -0.36,    0.98,    0.02
20240301,    0.76,    0.09,   -0.55,    0.02
20240304,   -0.18,   -0.79,    0.34,    0.02
20240305,   -1.07,   -0.32,    1.17,    0.02
20240306,    0.53,   -0.16,   -0.03,    0.02
20240307,    1.02,   -0.47,    0.03,    0.02
20240308,   -0.66,    0.50,    0.57,    0.02
20240311,   -0.20,   -0.72,    0.40,    0.02
20240312,    1.04,   -0.97,   -0.68,    0.02
20240313,   -0.14,    0.30,   -0.02,    0.02
20240314,   -0.42,   -1.31,   -1.04,    0.02
20240315,   -0.58,    0.75,    0.79,    0.02
20240318,    0.53,   -1.02,   -0.25,    0.02
20240319,    0.54,    0.53,   -0.27,    0.02
20240320,    1.02,    0.90,    1.01,    0.02
20240321,    0.42,    0.05,    0.95,    0.02
20240322,   -0.23,   -0.86,   -0.53,    0.02
20240325,   -0.27,   -0.24,    0.86,    0.02
20240326,   -0.26,    0.09,   -0.13,    0.02
20240327,    0.88,    1.04,    0.91,    0.02
20240328,    0.11,    0.29,    0.48,    0.02
20240401,   -0.26,   -0.89,   -0.28,    0.02
20240402,   -0.85,   -1.10,    0.04,    0.02
20240403,    0.17,    0.31,   -0.03,    0.02
20240404,   -1.22,    0.16,    0.15,    0.02
20240405,    1.06,   -0.32,   -0.68,    0.02
20240408,    0.01,    0.52,    0.14,    0.02
20240409,    0.13,    0.37,   -0.32,    0.02
20240410,   -1.00,   -1.37,   -1.04,    0.02
20240411,    0.73,    0.24,   -0.62,    0.02
20240412,   -1.53,   -0.33,    0.11,    0.02
20240415,   -1.29,   -0.48,    0.76,    0.02
20240416,   -0.23,   -0.03,   -0.82,    0.02
20240417,   -0.64,   -0.49,    0.56,    0.02
20240418,   -0.27,   -0.28,    0.87,    0.02
20240419,   -0.82,    0.82,    1.90,    0.02
20240422,    0.87,   -0.21,    0.54,    0.02
20240423,    1.27,    0.59,    0.00,    0.02
20240424,   -0.01,   -0.31,    0.28,    0.02
20240425,   -0.47,   -0.31,   -0.20,    0.02
20240426,    1.03,    0.46,   -1.07,    0.02
20240429,    0.33,    0.38,   -0.48,    0.02
20240430,   -1.67,   -0.19,   -0.25,    0.02'''

# Fuente: FRED DGS3MO, descarga actual; no incluye tiempos de publicación
# ni información de versiones históricas (vintage).
FRED_CSV = '''observation_date,DGS3MO
2024-01-02,5.46
2024-01-03,5.48
2024-01-04,5.48
2024-01-05,5.47
2024-01-08,5.49
2024-01-09,5.47
2024-01-10,5.46
2024-01-11,5.46
2024-01-12,5.45
2024-01-15,
2024-01-16,5.45
2024-01-17,5.47
2024-01-18,5.45
2024-01-19,5.45
2024-01-22,5.46
2024-01-23,5.45
2024-01-24,5.44
2024-01-25,5.44
2024-01-26,5.44
2024-01-29,5.42
2024-01-30,5.42
2024-01-31,5.42
2024-02-01,5.42
2024-02-02,5.43
2024-02-05,5.42
2024-02-06,5.44
2024-02-07,5.43
2024-02-08,5.44
2024-02-09,5.44
2024-02-12,5.43
2024-02-13,5.45
2024-02-14,5.43
2024-02-15,5.43
2024-02-16,5.44
2024-02-19,
2024-02-20,5.44
2024-02-21,5.44
2024-02-22,5.45
2024-02-23,5.46
2024-02-26,5.47
2024-02-27,5.45
2024-02-28,5.45
2024-02-29,5.45
2024-03-01,5.42
2024-03-04,5.48
2024-03-05,5.47
2024-03-06,5.47
2024-03-07,5.47
2024-03-08,5.46
2024-03-11,5.48
2024-03-12,5.48
2024-03-13,5.48
2024-03-14,5.48
2024-03-15,5.48
2024-03-18,5.48
2024-03-19,5.48
2024-03-20,5.47
2024-03-21,5.48
2024-03-22,5.46
2024-03-25,5.46
2024-03-26,5.46
2024-03-27,5.45
2024-03-28,5.46
2024-03-29,
2024-04-01,5.44
2024-04-02,5.42
2024-04-03,5.42
2024-04-04,5.41
2024-04-05,5.43
2024-04-08,5.43
2024-04-09,5.43
2024-04-10,5.45
2024-04-11,5.45
2024-04-12,5.45
2024-04-15,5.45
2024-04-16,5.45
2024-04-17,5.45
2024-04-18,5.46
2024-04-19,5.45
2024-04-22,5.42
2024-04-23,5.45
2024-04-24,5.46
2024-04-25,5.47
2024-04-26,5.46
2024-04-29,5.45
2024-04-30,5.46'''


def parse_num(texto, sentinelas=()):
    texto = texto.strip()
    if texto in ('', '.'):
        return None
    valor = float(texto)
    if not math.isfinite(valor):
        raise ValueError('Valor no finito')
    return None if valor in sentinelas else valor


def leer_french(contenido):
    """Acepta el CSV completo con preámbulo y pie o el extracto literal."""
    filas = csv.reader(io.StringIO(contenido))
    columnas = None
    datos = {}
    for fila in filas:
        if not fila:
            continue
        campos = [campo.strip() for campo in fila]
        if campos[:5] == ['', 'Mkt-RF', 'SMB', 'HML', 'RF']:
            columnas = {campo: indice for indice, campo in enumerate(campos)}
            continue
        fecha_bruta = campos[0]
        if not (len(fecha_bruta) == 8 and fecha_bruta.isdigit()):
            continue
        if columnas is None:
            raise ValueError('Falta la cabecera de factores de French')
        if len(campos) <= max(columnas['Mkt-RF'], columnas['RF']):
            raise ValueError('Fila de French incompleta')
        fecha = datetime.strptime(fecha_bruta, '%Y%m%d').date()
        if fecha in datos:
            raise ValueError(f'Fecha duplicada en French: {fecha}')
        exceso = parse_num(campos[columnas['Mkt-RF']], (-99.99, -999.0))
        libre = parse_num(campos[columnas['RF']], (-99.99, -999.0))
        mercado = None if exceso is None or libre is None else (exceso + libre) / 100
        datos[fecha] = {'mkt_rf_pct': exceso, 'rf_pct': libre, 'mercado_simple': mercado}
    if columnas is None:
        raise ValueError('No se encontró la cabecera de French')
    return datos


def leer_fred(contenido):
    """Lee el CSV completo de DGS3MO; conserva celdas vacías o puntos."""
    lector = csv.DictReader(io.StringIO(contenido))
    if lector.fieldnames is None or not {'observation_date', 'DGS3MO'} <= set(lector.fieldnames):
        raise ValueError('Falta la cabecera de FRED DGS3MO')
    datos = {}
    for fila in lector:
        if not fila['observation_date']:
            continue
        fecha = date.fromisoformat(fila['observation_date'].strip())
        if fecha in datos:
            raise ValueError(f'Fecha duplicada en FRED: {fecha}')
        datos[fecha] = parse_num(fila['DGS3MO'])
    return datos


def unir_por_fecha(factores, tipos):
    """Unión exterior exacta, sin rellenar ni desplazar observaciones."""
    return [{'fecha': fecha,
             'mercado_simple': factores.get(fecha, {}).get('mercado_simple'),
             'dgs3mo_pct_anual': tipos.get(fecha),
             'hay_fecha_french': fecha in factores,
             'hay_fecha_fred': fecha in tipos}
            for fecha in sorted(set(factores) | set(tipos))]


def resumen_log(serie):
    if len(serie) < 2 or not all(math.isfinite(v) for v in serie):
        raise ValueError('Se necesitan al menos dos rendimientos finitos')
    return mean(serie), stdev(serie), stdev(serie) * math.sqrt(252)


factores = leer_french(FRENCH_CSV)
tipos = leer_fred(FRED_CSV)
alineadas = unir_por_fecha(factores, tipos)
mercado_simple = [fila['mercado_simple'] for fila in alineadas if fila['mercado_simple'] is not None]
if any(valor <= -1 for valor in mercado_simple):
    raise ValueError('No se puede calcular log(1+r) para un rendimiento menor o igual a −1')
mercado_log = [math.log1p(valor) for valor in mercado_simple]
if 'r' not in globals() or len(r) < len(mercado_log):
    raise RuntimeError('Ejecuta antes la celda Generador GJR-t, saltos y regímenes')
sintetico_log = [float(valor) for valor in r[:len(mercado_log)]]
real_stats, sim_stats = resumen_log(mercado_log), resumen_log(sintetico_log)
tasas = [valor for valor in tipos.values() if valor is not None]
sin_tasa = [fila['fecha'].isoformat() for fila in alineadas
            if fila['mercado_simple'] is not None and fila['dgs3mo_pct_anual'] is None]

print('French:', len(factores), 'fechas; FRED:', len(tipos), 'fechas; unión:', len(alineadas))
print('Mercado válido:', len(mercado_log), '| DGS3MO válido:', len(tasas),
      '| fechas de mercado sin tasa:', sin_tasa)
print('Rendimiento log diario: media, desviación muestral, desviación × √252')
print('French:', *(round(valor, 6) for valor in real_stats))
print('GJR sintético, misma longitud:', *(round(valor, 6) for valor in sim_stats))
print('DGS3MO anual, porcentaje: mínimo', min(tasas), 'máximo', max(tasas))
print('Comparación descriptiva de una ventana y una simulación; √252 es una regla, no una identidad general.')
print('DGS3MO es tasa anualizada, no rendimiento diario; fechas de observación no son fechas de publicación.')
for nombre, serie in (('French',mercado_log),('GJR sintético',sintetico_log)):
    diagnostico=hechos_estilizados(serie,20)
    print(nombre,'| exceso curtosis:',round(diagnostico['exceso_curtosis'],3),
          '| fracción >4σ:',round(diagnostico['mas_de_4_sigma'],4),
          '| ACF₁(r), ACF₁(|r|):',round(diagnostico['acf_r'][1],3),
          round(diagnostico['acf_abs_r'][1],3),
          '| correlación rₜ,|rₜ₊₁|:',round(diagnostico['correlacion_apalancamiento'],3))
print('Una ventana de esta longitud tiene mucha incertidumbre, especialmente en colas.')

Exercises

NumericRise and fall by the same proportion
An asset rises by 50% and then falls by 50%. What is its total simple return, as a percentage?
NumericThe same movements as log returns
For the preceding +50% and −50% sequence, calculate the sum of the two log returns without expressing it as a percentage.
ProofOne distribution, two growth rates
Prove: If log⁡(PT/P0)∼N(μT,σ2T)\log(P_T/P_0)\sim N(\mu T,\sigma^2T), prove the formulas for median and expected wealth.
The proof will appear here as you work.

Step 1 of 3. What happens to the median under the strictly increasing exponential function?

NumericAnnual volatility with dependence
A stationary series has daily volatility of 1.2%, autocorrelation 0.2 at the first lag and zero at all other lags. Calculate the annual standard deviation, in percent, for the sum of 252 returns.
CodeDiagnose a series
Implement informe_rendimientos(x, max_lag=20). It receives a finite numerical vector of length greater than max_lag+1 and a nonnegative integer max_lag, and returns a dictionary with keys exceso_curtosis, mas_de_4_sigma, normal_mas_de_4_sigma, acf_r, acf_abs_r and correlacion_apalancamiento. Use centered moments with divisor n and compare |x-mean| against four standard deviations with divisor n. The normal reference is erfc(4/sqrt(2)). For each ACF use numerator Σ_{t=k}^{n-1}(x_t−mean)(x_{t-k}−mean) and denominator Σ_{t=0}^{n-1}(x_t−mean)², including lag zero. The last correlation is Pearson's correlation between x[:-1] and abs(x[1:]). Raise ValueError for invalid parameters, a required zero variance or undefined correlation.
def informe_rendimientos(x, max_lag=20):
  raise NotImplementedError('Implementa los diagnósticos')
Shift+Enter to run
QuizTwo assets, one portfolio
Why is a portfolio's log return generally not the weighted average of its assets' log returns?

After solving the exercises, check the two calculations here. In the second, the first lag is the only nonzero autocorrelation.

[ ]Check two return calculationsBrowser
import numpy as np
n=252
vol_diaria=.012
rho_1=.2
riqueza_final=1.5*.5
raiz_ingenua=vol_diaria*np.sqrt(n)
desviacion_corregida=vol_diaria*np.sqrt(n+2*(n-1)*rho_1)
print('Rendimiento compuesto:',riqueza_final-1,'| suma de logaritmos:',np.log(riqueza_final))
print('Volatilidad anual ingenua:',raiz_ingenua,
      '| con autocorrelación:',desviacion_corregida)