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 is a wealth index that incorporates payments according to a stated rule, the simple return and the log return are
If all prices are positive, log returns add exactly over time:
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 summing to one and no intraperiod flows, the simple return is . Its log return is , not the weighted mean of . 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 and suitable moments, Jensen’s inequality gives
For small returns and a controlled Taylor approximation,
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 with constant coefficients, volatility drag is exact:
Median wealth is and expected wealth is . 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 rather than ; the median falls when .
Aggregating over time and annualizing risk
Let be a weakly stationary series with variance and autocovariance at lag . The variance of the sum of returns is
The square-root-of-time rule is therefore exact for the standard deviation of the sum when the relevant autocovariances are zero. With , the correction multiplies single-period volatility by
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 when the mean is constant; converting that to an average simple return requires more information about the distribution.
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.
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 and , and the relationship between and 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.
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:
Here is a Markov chain, is a sum of a Poisson number of jumps, and scales the innovation according to the regime. Setting recovers symmetric GARCH. If innovations are symmetric with unit variance, a common condition for the unconditional variance of the isolated GJR process is , with nonnegative parameters. The fourth-moment condition is stricter: among other conditions, it requires . A Student-t has finite variance if and finite fourth moment if .
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 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. is an excess over : add them and divide by 100 to reconstruct the market’s simple return. and 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.
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 , their sum has mean and standard deviation . 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.
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.
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.
"""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
Step 1 of 3. What happens to the median under the strictly increasing exponential function?
def informe_rendimientos(x, max_lag=20):
raise NotImplementedError('Implementa los diagnósticos')After solving the exercises, check the two calculations here. In the second, the first lag is the only nonzero autocorrelation.
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)