== Listing 7.1: the market simulator ==
days=60000, assets=10, crisis share=0.140
mean run length: calm 97.5 days, crisis 15.9 days
calm   index: annual mean +0.119, annual vol 0.123, kurtosis 7.59, mean pairwise corr 0.321
crisis index: annual mean -0.174, annual vol 0.286, kurtosis 6.64, mean pairwise corr 0.588
all    index: kurtosis 12.72, lag-1 autocorrelation of r -0.003, of r^2 +0.071

== Listing 7.2: proper scores ==
pinball, truth t(4), tau=0.95: constant forecast q -> mean loss
  q=1.000  loss=0.2205
  q=1.500  loss=0.1749
  q=2.132  loss=0.1605  <- true quantile
  q=3.000  loss=0.1759
  q=4.000  loss=0.2128
grid minimiser of pinball: 2.125 (true quantile 2.132)
absolute error used on the same forecast: minimiser 0.000 (the median, so it rewards the wrong functional)
CRPS of Gaussian forecasts N(m, s^2), truth N(0,1):
  m=0.0 s=1.0  CRPS=0.5626
  m=0.3 s=1.0  CRPS=0.5881
  m=0.0 s=0.6  CRPS=0.5900
  m=0.0 s=1.6  CRPS=0.6016
  m=0.5 s=1.4  CRPS=0.6395
closed form vs ensemble CRPS for N(0.3,1.2^2) at y=0.5: 0.2937 vs 0.2964
twice the pinball loss averaged over tau (same forecast, y=0.5): 0.2937

== Listing 7.3: quantile forecaster, pinball loss ==
test pinball loss (units of 1e-4), mean over 200 simulated series
tau      unconditional   vol-scaled   change
0.05         11.672       11.375     -2.6%
0.25         28.205       28.203     -0.0%
0.50         33.665       33.678     +0.0%
0.75         27.656       27.974     +1.1%
0.95         11.138       11.112     -0.2%
mean over tau: 22.467 vs 22.468  (+0.0%)
coverage of the raw [0.05, 0.95] band (target 0.900), before any conformal step:
  unconditional quantiles: calm days 0.939, crisis days 0.660
  vol-scaled quantiles:    calm days 0.917, crisis days 0.788, all days 0.899

== Listing 7.4: conformalized intervals on a dependent series ==
-- calibration window as drawn (300 series, n_cal about 1000, target 0.900)
   coverage: all test days 0.900, calm days 0.918, crisis days 0.789, first 20 days of a crisis 0.833
   P(miss today | miss yesterday) = 0.119 (0.100 if misses were independent)
-- calibration on calm days only (300 series, n_cal about 1000, target 0.900)
   coverage: all test days 0.882, calm days 0.900, crisis days 0.772, first 20 days of a crisis 0.817
   P(miss today | miss yesterday) = 0.137 (0.100 if misses were independent)
mean crisis share of the test period: 0.143

== Listing 7.5: estimation error in mean-variance allocation ==
N=20 assets, monthly data, 1000 simulated histories per row; Sharpe ratios per month
  T   in-sample  realized   true-opt  equal-wt  median gross leverage
  60     0.743     0.046     0.185     0.100     12.06
 120     0.491     0.069     0.185     0.100      8.66
 240     0.355     0.096     0.185     0.100      6.54
known covariance, T=120: mean in-sample squared Sharpe 0.2007; theory 0.0341 + N/T = 0.2007

== Listing 7.6: covariance shrinkage ==
own shrinkage 0.060811, scikit-learn 0.060811, max abs difference of matrices 8.67e-19
out-of-sample variance of the minimum-variance portfolio, relative to the true optimum (1.000)
  T   sample cov   Ledoit-Wolf   mean shrinkage
  60      1.477        1.251        0.135
 120      1.189        1.145        0.070
 240      1.086        1.076        0.036

== Listing 7.7: standard error of the Sharpe ratio ==
payoff: +1 w.p. 0.95, -10 w.p. 0.05; true Sharpe 0.1877, skewness -4.13
  T   sd of estimate   mean SE gaussian   mean SE adjusted   CI coverage gaussian   adjusted
 120        0.1589            0.0933             0.1474                 0.818     0.961
 240        0.1002            0.0655             0.0958                 0.794     0.971
 480        0.0676            0.0462             0.0655                 0.805     0.964
simulated daily index: Sharpe 0.0167 per day, skew -0.34, kurtosis 15.29, SE ratio adjusted/gaussian 1.0033

== Listing 7.8: expected maximum Sharpe ratio ==
max of N iid N(0,1): Monte Carlo (20000 draws) vs extreme-value formula vs sqrt(2 ln N)
     N   simulated   formula   sqrt(2 ln N)
     2      0.574     0.520        1.177
    10      1.543     1.575        2.146
   100      2.503     2.531        3.035
  1000      3.238     3.255        3.717
 10000      3.840     3.861        4.292

== Listing 7.9: data snooping and the deflated Sharpe ratio ==
200 searches, each over 1000 random signals, 1000 daily returns, true Sharpe 0 for all
best annualized Sharpe: mean 1.619, min 1.277
expected maximum under the null (annualized): 1.645
naive PSR against 0: mean 0.9991; share of searches above 0.95: 1.000
deflated Sharpe ratio: mean 0.478; share above 0.95: 0.000
mean variance of trial Sharpe ratios 0.001017 (1/T = 0.001000)
first search: best Sharpe 1.932, PSR 0.9998, E[max] 1.722, DSR 0.652

== Listing 7.10: purged and embargoed cross-validation ==
n=1000, label horizon h=20, 25 folds; fold 0 has 40 test samples, 920 training samples remain after purging and a 20-day embargo
cross-validated R^2 of a 50-nearest-neighbour regressor; features are random walks
unrelated to returns, so the true R^2 is at most 0. 40 repetitions.
  shuffled    mean +0.404  sd 0.054
  contiguous  mean -0.136  sd 0.112
  purged      mean -0.262  sd 0.171

== Listing 7.11: look-ahead and survivorship bias ==
yesterday-sign momentum on 5000 simulated days (annualized Sharpe; audit = share of days whose
position changes when the returns from that day on are replaced)
  correct (lagged)  Sharpe   0.077   audit 0.000
  same-day (bug)    Sharpe  15.405   audit 0.485
  centred average   Sharpe   2.864   audit 0.365
universe: 500 zero-alpha assets, 1000 days, 19.6 percent delisted at a 70 percent loss
  full universe   equal-weight return   0.97 %/yr   contrarian return  -0.96 %/yr, Sharpe -0.148
  survivors only  equal-weight return   6.95 %/yr   contrarian return  12.12 %/yr, Sharpe  1.878

== Listing 7.12: optimal execution ==
sell 100000 shares over 5 days in 20 intervals; sigma=0.5 per sqrt(day); eta=5.00e-07, gamma=2.50e-07, eta-gamma*tau/2=4.687e-07
schedule   share sold in step 1   E[cost] formula / simulated   sd formula / simulated   U at 1e-6   95th pct
TWAP              0.050           2188 /     1919          62124 /    62244        6047      104527
3e-07             0.099           2364 /     2151          49654 /    49745        4830       84130
1e-06             0.167           2974 /     2820          37494 /    37555        4380       64636
3e-06             0.270           4179 /     4081          26689 /    26726        4891       47998
notional 5000000; TWAP expected cost = 4.38 bp; standard error of a simulated mean about 139
1000 random perturbations of the optimal schedule: 1000 have a higher objective

== Listing 7.13: structured extraction from synthetic filings ==
example: Revenue was $464.0 million in 2007 and $461.0 million in 2008. The company employed 6165 people at year end. Analysts expect competition to rise. There is substantial doubt about the company's ability to continue as a going concern.
gold   : {'revenue': 461.0, 'guidance': 'none', 'going_concern': True}
rules  : {'revenue': 464.0, 'guidance': 'none', 'going_concern': True}
600 documents; 95 percent bootstrap intervals over documents (2000 resamples)
field               precision               recall                  F1
revenue (exact)     0.823 [0.790, 0.855]   0.742 [0.708, 0.777]   0.780 [0.749, 0.811]
guidance=raise      1.000 [1.000, 1.000]   0.760 [0.696, 0.825]   0.864 [0.820, 0.904]
guidance=lower      0.613 [0.539, 0.686]   0.867 [0.803, 0.924]   0.718 [0.654, 0.776]
going concern       1.000 [1.000, 1.000]   0.731 [0.640, 0.820]   0.845 [0.780, 0.901]
going concern: 93 positives; the 130 negated mentions ('no substantial doubt') produce 0 false positives
misses are paraphrases without the key phrase: 25 of 93 positives

== Listing 7.14: failure modes ==
minimum-variance portfolio fitted on 750 calm days; forecast daily vol 0.00521
  realized vol on later calm days: 0.00532 (1.02 x forecast); equal-weight vol 0.00670
  realized vol on later crisis days: 0.01095 (2.10 x forecast); equal-weight vol 0.01485
signal with correlation 0.05 to the day's return: gross Sharpe 0.646, daily turnover 1.00 of capital, gross mean 3.74 bp/day
net Sharpe by cost per unit traded (flat cost):
  cost 0.0 bp: net Sharpe  0.646
  cost 0.5 bp: net Sharpe  0.560
  cost 1.0 bp: net Sharpe  0.474
  cost 2.0 bp: net Sharpe  0.301
  cost 3.0 bp: net Sharpe  0.128
  cost 5.0 bp: net Sharpe -0.217
capacity: cost per unit traded = 0.5 bp + AUM/100M bp (linear impact)
  AUM    10M: net Sharpe  0.543, expected profit    0.79M per year
  AUM    50M: net Sharpe  0.474, expected profit    3.45M per year
  AUM   100M: net Sharpe  0.387, expected profit    5.64M per year
  AUM   200M: net Sharpe  0.214, expected profit    6.25M per year
  AUM   300M: net Sharpe  0.042, expected profit    1.83M per year
  AUM   500M: net Sharpe -0.303, expected profit  -22.12M per year
