"""Replay the 22 November 2026 Litecoin.watch LTC/USD forecast. Requires Python 3.10+ and numpy. python reproduce.py.txt --data . --out replay Reads closes.csv and sources.json. Does not use the network. """ import argparse import calendar import csv from datetime import date, timedelta from hashlib import sha256 import json from math import erfc, exp, log, sqrt from pathlib import Path from statistics import median import numpy as np AS_OF = date(2026, 11, 21) TARGETS = [date(2027, 12, 31), date(2030, 12, 31)] HORIZONS = [(target - AS_OF).days for target in TARGETS] LEVEL_DAYS = 1460 VOL_RETURNS = 730 HALF_LIFE = 730 PHI = exp(-log(2) / HALF_LIFE) PATHS = 40_000 BLOCK = 28 SEED = 20261122 LEVELS = (20, 50, 60, 100, 120, 200, 333, 1000) MODELS = ('walk', 'reversion', 'house') def read_data(folder): notes = json.loads((folder / 'sources.json').read_text(encoding='utf-8')) raw = (folder / 'closes.csv').read_bytes() assert sha256(raw).hexdigest() == notes['closes_sha256'] with (folder / 'closes.csv').open(encoding='utf-8', newline='') as stream: rows = list(csv.DictReader(stream)) days = [date.fromisoformat(row['utc_day']) for row in rows] prices = np.array([float(row['coinbase_ltc_usd_close']) for row in rows]) assert days[0] == date(2017, 1, 1) and days[-1] == AS_OF and len(days) == notes['days'] assert all(b - a == timedelta(days=1) for a, b in zip(days, days[1:])) assert np.isfinite(prices).all() and (prices > 0).all() and prices[-1] == float(notes['ltc_usd']) return days, np.log(prices), notes def parameters(history): assert len(history) >= LEVEL_DAYS vol = float(np.std(np.diff(history[-(VOL_RETURNS + 1):]), ddof=1)) return float(history[-1]), float(np.mean(history[-LEVEL_DAYS:])), vol def distributions(parameters_, horizon): spot, anchor, sigma = parameters_ decay = PHI ** horizon walk = (spot, sigma * sqrt(horizon)) reversion = (anchor + (spot - anchor) * decay, sigma * sqrt((1 - decay**2) / (1 - PHI**2))) return {'walk': [walk], 'reversion': [reversion], 'house': [walk, reversion]} def cdf(log_price, components): return sum(0.5 * erfc((mu - log_price) / (sd * sqrt(2))) for mu, sd in components) / len(components) def above(log_price, components): return sum(0.5 * erfc((log_price - mu) / (sd * sqrt(2))) for mu, sd in components) / len(components) def log_quantile(p, components): lo = min(mu - 12 * sd for mu, sd in components) hi = max(mu + 12 * sd for mu, sd in components) for _ in range(65): midpoint = (lo + hi) / 2 if cdf(midpoint, components) < p: lo = midpoint else: hi = midpoint return (lo + hi) / 2 def end_summary(components, spot_log): quantiles = {str(p): exp(log_quantile(p / 100, components)) for p in (5,10,25,50,75,90,95)} above_target = {str(level): above(log(level), components) for level in LEVELS} bounds = (20, 50, 100, 200) cumulative = [0, *(cdf(log(b), components) for b in bounds), 1] buckets = [b - a for a, b in zip(cumulative, cumulative[1:])] assert all(x >= 0 for x in buckets) and abs(sum(buckets) - 1) < 1e-10 assert all(a > b for a, b in zip(above_target.values(), list(above_target.values())[1:])) return {'quantiles_usd': quantiles, 'p_close_at_least': above_target, 'p_below_20': cumulative[1], 'p_close_above_start': above(spot_log, components), 'p_close_60_to_120': above_target['60'] - above_target['120'], 'p_buckets_lt20_20to50_50to100_100to200_ge200': buckets} def simulate(history, innovation): # Each path keeps its assigned model. The first half are walks and the rest revert. rng = np.random.Generator(np.random.PCG64(SEED if innovation == 'normal' else SEED + 1)) start, anchor, sigma = parameters(history) simulated = np.full(PATHS, start) hit = np.zeros(PATHS, dtype=bool) split = PATHS // 2 returns = np.diff(history[-(VOL_RETURNS + 1):]) centered = returns - np.mean(returns) cutoff = log(100) results = {} for step in range(1, max(HORIZONS) + 1): if innovation == 'normal': shock = sigma * rng.standard_normal(PATHS) else: offset = (step - 1) % BLOCK if offset == 0: start_indices = rng.integers(0, len(returns), size=PATHS) shock = centered[(start_indices + offset) % len(returns)] simulated[split:] += (1 - PHI) * (anchor - simulated[split:]) simulated += shock hit |= simulated >= cutoff if step in HORIZONS: finished = simulated >= cutoff crossed_then_below = hit & ~finished assert not np.any(finished & ~hit) result = {'paths': PATHS, 'close_ge100_count': int(finished.sum()), 'ever_daily_close_ge100_count': int(hit.sum()), 'crossed_but_ended_below_count': int(crossed_then_below.sum()), 'p_ever_daily_close_ge100': float(np.mean(hit)), 'p_finish_ge100': float(np.mean(finished)), 'fraction_of_crossers_finishing_below': float(crossed_then_below.sum() / hit.sum()), 'q10_q50_q90_usd': np.exp(np.quantile(simulated, [0.1, 0.5, 0.9])).tolist()} results[str(step)] = result return results def backtest(days, log_prices): rows = [] for index, origin in enumerate(days): if index + 1 < LEVEL_DAYS or origin.day != calendar.monthrange(origin.year, origin.month)[1]: continue params = parameters(log_prices[:index + 1]) for horizon in HORIZONS: end = index + horizon if end >= len(days): continue actual_log = float(log_prices[end]) double_barrier = params[0] + log(2) ever_doubled = int(float(np.max(log_prices[index + 1:end + 1])) >= double_barrier) models = distributions(params, horizon) for name, components in models.items(): low, center, high = [log_quantile(p, components) for p in (0.1, 0.5, 0.9)] p_up = above(params[0], components) rows.append({'model': name, 'horizon_days': horizon, 'origin_utc': origin.isoformat(), 'settled_utc': days[end].isoformat(), 'origin_usd': exp(params[0]), 'actual_usd': exp(actual_log), 'q10_usd': exp(low), 'median_usd': exp(center), 'q90_usd': exp(high), 'p_up': p_up, 'actual_up': int(actual_log > params[0]), 'inside_80': int(low <= actual_log <= high), 'p_end_at_least_double': above(double_barrier,components), 'actual_end_at_least_double': int(actual_log >= double_barrier), 'actual_ever_daily_close_at_least_double': ever_doubled, 'abs_log_error': abs(center - actual_log), 'brier': (p_up - (actual_log > params[0]))**2}) summary = {} for horizon in HORIZONS: metrics = {} for model in MODELS: selected = [r for r in rows if r['model'] == model and r['horizon_days'] == horizon] assert selected order = [] for row in selected: if not order or row['origin_utc'] >= order[-1]['settled_utc']: order.append(row) count = len(selected) metrics[model] = {'origins': count, 'first_origin': selected[0]['origin_utc'], 'last_origin': selected[-1]['origin_utc'], 'max_disjoint_windows': len(order), 'inside_80_count': sum(r['inside_80'] for r in selected), 'below_q10_count': sum(r['actual_usd'] < r['q10_usd'] for r in selected), 'above_q90_count': sum(r['actual_usd'] > r['q90_usd'] for r in selected), 'median_multiplicative_error': exp(median(r['abs_log_error'] for r in selected)), 'mean_brier_up': sum(r['brier'] for r in selected) / count, 'mean_p_end_at_least_double': sum(r['p_end_at_least_double'] for r in selected) / count, 'end_doubles': sum(r['actual_end_at_least_double'] for r in selected), 'ever_close_doubles': sum(r['actual_ever_daily_close_at_least_double'] for r in selected), 'actual_up_count': sum(r['actual_up'] for r in selected)} summary[str(horizon)] = metrics return rows, summary def main(folder, output): days, log_prices, sources = read_data(folder) params = parameters(log_prices) start, anchor, vol = params spot = float(sources['ltc_usd']) forecast = {} for horizon, target in zip(HORIZONS, TARGETS): models = distributions(params, horizon) forecast[target.isoformat()] = {'days': horizon, 'models': {name:end_summary(c, start) for name,c in models.items()}, 'required_cagr': {str(k):(k/spot)**(365.25/horizon)-1 for k in (60,100,200,333,1000)}} normal = simulate(log_prices, 'normal') bootstrap = simulate(log_prices, 'blocks') for horizon, target in zip(HORIZONS, TARGETS): expected = forecast[target.isoformat()]['models']['house']['p_close_at_least']['100'] assert abs(normal[str(horizon)]['p_finish_ge100'] - expected) < 5 * sqrt(expected*(1-expected)/PATHS) rows, scores = backtest(days, log_prices) for metrics in scores.values(): for model, m in metrics.items(): assert m['origins'] == m['inside_80_count'] + m['below_q10_count'] + m['above_q90_count'] assert abs(metrics['walk']['mean_brier_up'] - 0.25) < 1e-10 by_date = {d:float(exp(x)) for d,x in zip(days,log_prices)} october_price = by_date[date(2026, 10, 21)] end_2025 = by_date[date(2025, 12, 31)] result = {'as_of_utc_day': AS_OF.isoformat(), 'settlement': 'Coinbase Exchange LTC-USD UTC daily close on each target date', 'training_observations_available': len(days), 'numpy_version': np.__version__, 'assumptions': {'weight_walk': 0.5, 'weight_reversion': 0.5, 'anchor_close_days': LEVEL_DAYS, 'volatility_return_days': VOL_RETURNS, 'reversion_half_life_days': HALF_LIFE, 'paths_per_experiment': PATHS, 'circular_block_days': BLOCK, 'seed_normal': SEED, 'seed_blocks': SEED+1}, 'reference': {'ltc_usd': spot, 'btc_usd': float(sources['btc_usd']), 'bitstamp_ltc_usd': float(sources['bitstamp_ltc_usd']), 'geometric_anchor_usd': exp(anchor), 'annualized_daily_log_vol': vol*sqrt(365.25), 'october21_close': october_price, 'move_since_october': spot/october_price-1, 'btc_per_ltc_from_usd_closes': spot/float(sources['btc_usd']), 'finder_2025_actual_usd': end_2025, 'finder_actual_vs_159': end_2025/159-1}, 'forecast': forecast, 'gaussian_paths': normal, 'block_paths': bootstrap, 'historical_scores': scores} output.mkdir(parents=True, exist_ok=True) (output / 'model.json').write_text(json.dumps(result, indent=2, allow_nan=False) + '\n', encoding='utf-8') with (output / 'backtest.csv').open('w', encoding='utf-8', newline='') as stream: writer = csv.DictWriter(stream, fieldnames=list(rows[0]), lineterminator='\n') writer.writeheader() writer.writerows(rows) print(json.dumps({'targets': HORIZONS, 'walk_forward_rows': len(rows), 'numpy': np.__version__})) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--data', type=Path, default=Path('.')) parser.add_argument('--out', type=Path, required=True) args = parser.parse_args() main(args.data, args.out)