"""Reproduce invented teaching examples. No market or private research inputs. Run: python reproduce_examples.py Optionally write the example CSV/JSON files: python reproduce_examples.py --output-dir ./examples Requires Python 3.9+ and only the standard library. No strategy simulation. """ import argparse import csv import json import math from pathlib import Path def require(condition, message): if not condition: raise ValueError(message) def holm(values): require(bool(values), 'A nonempty family is required') require(all(math.isfinite(p) and 0 <= p <= 1 for p in values), 'Invalid p-value') result = [0.0] * len(values) running = 0.0 for rank, index in enumerate(sorted(range(len(values)), key=values.__getitem__)): running = max(running, (len(values) - rank) * values[index]) result[index] = min(1.0, running) return result def drawdown(path): require(bool(path) and all(math.isfinite(x) and x > 0 for x in path), 'Positive finite marks required') peak = path[0] result = 0.0 for value in path: peak = max(peak, value) result = max(result, 1 - value / peak) return result def link(folds): require(bool(folds), 'At least one fold is required') carry = 1.0 linked = [] for fold in folds: require(bool(fold) and fold[0] == 1.0, 'Each fold must include its initial unit funding mark') drawdown(fold) linked.extend(carry * value for value in fold) carry *= fold[-1] return linked def funded_replay(): capital = 100000.0 g, cells = {}, [] for policy, shares in [('L', 500), ('H', 200)]: for cost, bps in [('L', 5), ('H', 10)]: buy, sell = shares*100, shares*101 fee = (buy+sell)*bps/10000 cash_after_buy = capital-buy-buy*bps/10000 require(cash_after_buy > 0, 'Unaffordable replay') wealth = capital+sell-buy-fee g[policy+cost] = math.log(wealth/capital) cells.append(dict(policy=policy,shares=shares,cost_bps_per_side=bps, traded_notional=buy+sell,direct_fee=fee, cash_after_buy=cash_after_buy,terminal_wealth=wealth,log_growth=g[policy+cost])) total=g['HH']-g['LL'] cost_first=[g['LH']-g['LL'],g['HH']-g['LH']] policy_first=[g['HL']-g['LL'],g['HH']-g['HL']] require(math.isclose(sum(cost_first),total,abs_tol=1e-14), 'Cost-first identity failed') require(math.isclose(sum(policy_first),total,abs_tol=1e-14), 'Policy-first identity failed') return dict(cells=cells,total_log_growth_change=total,cost_then_policy=cost_first,policy_then_cost=policy_first) def hedge_example(): weights=[.8,.2];covariance=[[.04,-.01],[-.01,.01]] product=[sum(a*b for a,b in zip(row,weights)) for row in covariance] volatility=math.sqrt(sum(a*b for a,b in zip(weights,product))) contributions=[w*p/volatility for w,p in zip(weights,product)] require(contributions[1]<0 and math.isclose(sum(contributions),volatility), 'Hedge allocation failed') return dict(weights=weights,covariance=covariance,volatility=volatility,contributions=contributions) def examples(): raw = [0.012, 0.014, 0.080, 0.400] adjusted = holm(raw) expected = [0.048, 0.048, 0.160, 0.400] require(all(math.isclose(a, b, abs_tol=1e-12) for a, b in zip(adjusted, expected)), 'Holm mismatch') tests = [dict(example_kind='invented', test=label, raw_p=p, holm_p=a, reject_at_005=a <= .05) for label, p, a in zip('ABCD', raw, adjusted)] costs = [] for label, orders, notional in [('A', 100, 1000), ('B', 20, 3000)]: total = orders * notional costs.append(dict(example_kind='invented', transaction_list=label, orders=orders, notional_per_order=notional, reference_capital=100000, gross_traded_notional=total, gross_turnover=total / 100000, cost_bps_per_side=5, direct_cost=total * 5 / 10000, cost_fraction_of_reference_capital=(total * 5 / 10000) / 100000)) order_reduction = 1 - costs[1]['orders'] / costs[0]['orders'] notional_reduction = 1 - costs[1]['gross_traded_notional'] / costs[0]['gross_traded_notional'] require(math.isclose(order_reduction, .8) and math.isclose(notional_reduction, .4), 'Cost mismatch') folds = [[1.0, 1.10, 1.04], [1.0, .98, .95]] linked = link(folds) worst_local = max(map(drawdown, folds)) linked_dd = drawdown(linked) require(math.isclose(linked[-1] - 1, -.012, abs_tol=1e-12), 'Linked return mismatch') require(math.isclose(worst_local, 3 / 55, abs_tol=1e-12), 'Local drawdown mismatch') require(math.isclose(linked_dd, 28 / 275, abs_tol=1e-12), 'Linked drawdown mismatch') equality_folds = [[1., 1.10, 1.10], [1., .98, .95]] require(math.isclose(drawdown(link(equality_folds)), max(map(drawdown, equality_folds)), abs_tol=1e-12), 'Equality mismatch') rows, peak = [], 1.0 for index, value in enumerate(linked): peak = max(peak, value) rows.append(dict(example_kind='invented', fold='AB'[index // 3], mark=['Initial', 'Observation 1', 'Observation 2'][index % 3], local_wealth=folds[index // 3][index % 3], linked_wealth=round(value, 12), linked_running_peak=peak, linked_drawdown=1 - value / peak)) check = dict(status='passed', example_kind='invented', scope='Arithmetic of constructed examples only; no empirical inference, strategy test or external audit.', raw_p_values_are_assumed_not_estimated=True, private_or_market_data_used=False, timeframe='unspecified', timeframe_scope='Constructed observations only; no trading cadence is specified.', turnover_convention='Sum of absolute buy and sell notionals divided by fixed reference capital; no halving.', tests_in_arithmetic_example=len(tests), adjusted_rejections=sum(r['reject_at_005'] for r in tests), order_reduction=order_reduction, notional_reduction=notional_reduction, linked_return=linked[-1]-1, worst_local_drawdown=worst_local, linked_drawdown=linked_dd, omitted_drawdown_percentage_points=100*(linked_dd-worst_local), equality_case_drawdown=drawdown(link(equality_folds))) check['funded_replay'] = funded_replay() check['hedge_example'] = hedge_example() return {'multiple_testing.csv': tests, 'transaction_costs.csv': costs, 'drawdown_paths.csv': rows}, check def write_examples(directory): tables, checks = examples() directory = Path(directory) directory.mkdir(parents=True, exist_ok=True) for name, rows in tables.items(): with (directory / name).open('w', encoding='utf-8', newline='') as stream: writer = csv.DictWriter(stream, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) (directory / 'example_checks.json').write_text(json.dumps(checks, indent=2, allow_nan=False) + '\n', encoding='utf-8') return checks if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output-dir', type=Path) args = parser.parse_args() checks = write_examples(args.output_dir) if args.output_dir else examples()[1] print(json.dumps(checks, indent=2, allow_nan=False))