262 lines
13 KiB
Python
262 lines
13 KiB
Python
|
|
"""三参数离线标定。候选全部披露,滚动选择只读取当时已发生的净值。"""
|
|||
|
|
import csv
|
|||
|
|
import datetime as dt
|
|||
|
|
import gzip
|
|||
|
|
import hashlib
|
|||
|
|
import itertools
|
|||
|
|
import json
|
|||
|
|
import math
|
|||
|
|
import statistics
|
|||
|
|
import sys
|
|||
|
|
from collections import Counter
|
|||
|
|
from pathlib import Path
|
|||
|
|
import numpy as np
|
|||
|
|
|
|||
|
|
from engine import Basket, TimingStrategy
|
|||
|
|
from prepare import ROOT, OLD, read, no_network
|
|||
|
|
|
|||
|
|
OUT = ROOT/'results'
|
|||
|
|
|
|||
|
|
|
|||
|
|
def save(name, value):
|
|||
|
|
payload = json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2)+'\n'
|
|||
|
|
path = OUT/name
|
|||
|
|
if name.endswith('.gz'):
|
|||
|
|
path.write_bytes(gzip.compress(payload.encode(), mtime=0))
|
|||
|
|
else:
|
|||
|
|
path.write_text(payload)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def key(params):
|
|||
|
|
return '_'.join(str(v).replace('.', 'p') for v in params)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def drawdown(values):
|
|||
|
|
a = np.array(values, dtype=float)
|
|||
|
|
return float(np.min(a/np.maximum.accumulate(a)-1))
|
|||
|
|
|
|||
|
|
|
|||
|
|
def stats(values):
|
|||
|
|
a = list(values)
|
|||
|
|
return {'n':len(a), 'mean':statistics.mean(a) if a else None,
|
|||
|
|
'median':statistics.median(a) if a else None,
|
|||
|
|
'min':min(a) if a else None, 'max':max(a) if a else None}
|
|||
|
|
|
|||
|
|
|
|||
|
|
class MeasuredBasket(Basket):
|
|||
|
|
def step(self, day, target, rows, limits, current_risk=frozenset()):
|
|||
|
|
start = len(self.trades)
|
|||
|
|
r = super().step(day, target, rows, limits, current_risk)
|
|||
|
|
weights = sorted((self.value(c, rows, 'close')/r['nav'] for c in self.units), reverse=True)
|
|||
|
|
r['max_weight'] = max(weights, default=0.)
|
|||
|
|
r['top5_weight'] = sum(weights[:5])
|
|||
|
|
for trade in self.trades[start:]:
|
|||
|
|
q = rows[trade['code']]
|
|||
|
|
trade['raw_open'] = q['open']
|
|||
|
|
trade['daily_amount_yuan'] = (q.get('amount') or 0)*1000
|
|||
|
|
return r
|
|||
|
|
|
|||
|
|
|
|||
|
|
def signal(row, params):
|
|||
|
|
low, high, _ = params
|
|||
|
|
s = row['signal']
|
|||
|
|
return {**s, 'low':s['activity'] < s['thresholds'][str(low)],
|
|||
|
|
'high':s['activity'] > s['thresholds'][str(high)]}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def run(data, params, bps=30, mode='combined', switches=None):
|
|||
|
|
s = TimingStrategy(mode=mode, cost=bps/10000)
|
|||
|
|
s.basket = MeasuredBasket(cost=bps/10000)
|
|||
|
|
for row in data:
|
|||
|
|
if switches and row['date'] in switches:
|
|||
|
|
params = switches[row['date']]
|
|||
|
|
s.step(row['date'], row['members'][:int(params[2])], row['rows'], row['limits'],
|
|||
|
|
set(row['risk']), signal(row, params))
|
|||
|
|
return s
|
|||
|
|
|
|||
|
|
|
|||
|
|
def metric(nav, dates):
|
|||
|
|
values = [1.]+list(nav)
|
|||
|
|
years = max(1, (dt.date.fromisoformat(dates[-1])-dt.date.fromisoformat(dates[0])).days)/365.25
|
|||
|
|
ar = float(values[-1]**(1/years)-1)
|
|||
|
|
dd = drawdown(values)
|
|||
|
|
return {'total_return':float(values[-1]-1), 'annualized_return':ar,
|
|||
|
|
'max_drawdown':dd, 'utility':ar-abs(dd)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def summary(s, data, params, bps):
|
|||
|
|
b = s.basket
|
|||
|
|
nav = [r['nav'] for r in b.records]
|
|||
|
|
dates = [r['date'] for r in b.records]
|
|||
|
|
annual, previous = {}, 1.
|
|||
|
|
for year in sorted(set(d[:4] for d in dates)):
|
|||
|
|
rows = [r for r in b.records if r['date'].startswith(year)]
|
|||
|
|
annual[year] = {'return':rows[-1]['nav']/previous-1,
|
|||
|
|
'max_drawdown':drawdown([previous]+[r['nav'] for r in rows]),
|
|||
|
|
'exposed_days':sum(r['positions'] > 0 for r in rows), 'days':len(rows)}
|
|||
|
|
previous = rows[-1]['nav']
|
|||
|
|
cycles = []
|
|||
|
|
for c in s.cycles_at_end():
|
|||
|
|
row = {k:v for k,v in c.items() if k != 'path'}
|
|||
|
|
row['max_drawdown'] = drawdown(c['path'])
|
|||
|
|
if c['exit_date']:
|
|||
|
|
row['exit_delay_days'] = dates.index(c['exit_date'])-dates.index(c['exit_signal_date'])-1
|
|||
|
|
i = c['entry_position']+20
|
|||
|
|
row['forward20_return'] = (b.records[i]['open_nav_before_trade']/c['entry_nav']-1
|
|||
|
|
if i < len(nav) else None)
|
|||
|
|
cycles.append(row)
|
|||
|
|
closed = [c for c in cycles if c['status'] == 'closed']
|
|||
|
|
pnl = Counter()
|
|||
|
|
for t in b.trades:
|
|||
|
|
pnl[t['code']] += (t['value'] if t['side'] == 'sell' else -t['value'])-t['fee']
|
|||
|
|
for code in b.units:
|
|||
|
|
pnl[code] += b.value(code, data[-1]['rows'], 'close')
|
|||
|
|
assert abs(sum(pnl.values())-(nav[-1]-1)) < 1e-8
|
|||
|
|
positive_pnl = sorted((v for v in pnl.values() if v > 0), reverse=True)
|
|||
|
|
# 订单尺寸诊断:以固定140万元初始本金缩放,不另称整手回测收益。
|
|||
|
|
capital = 1400000
|
|||
|
|
amounts = [t['value']*capital for t in b.trades]
|
|||
|
|
buys = [t for t in b.trades if t['side'] == 'buy']
|
|||
|
|
participation = [t['value']*capital/t['daily_amount_yuan'] for t in b.trades if t['daily_amount_yuan'] > 0]
|
|||
|
|
fee_est = sum(max(5., t['value']*capital*.0002)+t['value']*capital*(.00001+(.0005 if t['side']=='sell' else 0)) for t in b.trades)
|
|||
|
|
return {**metric(nav, dates), 'params':list(params), 'cost_bps':bps, 'annual':annual,
|
|||
|
|
'trade_count':len(b.trades), 'fees_initial_capital':sum(t['fee'] for t in b.trades),
|
|||
|
|
'mean_turnover':statistics.mean(r['turnover_two_sided'] for r in b.records),
|
|||
|
|
'median_turnover':statistics.median(r['turnover_two_sided'] for r in b.records),
|
|||
|
|
'max_stock_weight':max(r['max_weight'] for r in b.records),
|
|||
|
|
'max_top5_weight':max(r['top5_weight'] for r in b.records),
|
|||
|
|
'exposure_days':sum(r['positions']>0 for r in b.records),
|
|||
|
|
'max_actual_positions':max(r['positions'] for r in b.records),
|
|||
|
|
'over_target_days':sum(r['positions']>r['target_count'] and r['target_count']>0 for r in b.records),
|
|||
|
|
'unfilled':dict(Counter(r['reason'] for r in b.failures)),
|
|||
|
|
'stale_days':sum(r['stale_positions']>0 for r in b.records),
|
|||
|
|
'zero_mark_days':sum(r['zero_mark_positions']>0 for r in b.records),
|
|||
|
|
'entry_reasons':dict(Counter(c['reason'] for c in cycles)),
|
|||
|
|
'cycle_count':len(cycles), 'closed_cycles':len(closed),
|
|||
|
|
'cycle_returns':stats(c['return_value'] for c in closed),
|
|||
|
|
'holding_days':stats(c['holding_trade_days'] for c in cycles),
|
|||
|
|
'exit_delay_days':stats(c['exit_delay_days'] for c in closed),
|
|||
|
|
'cycles':cycles, 'positive_pnl_top5_share':sum(positive_pnl[:5])/sum(positive_pnl) if positive_pnl else None,
|
|||
|
|
'capacity':{'capital':capital, 'fee_schedule_estimate':fee_est,
|
|||
|
|
'minimum_commission_hits':sum(a*.0002<5 for a in amounts),
|
|||
|
|
'buy_below_min_lot':sum(t['value']*capital/t['raw_open'] < (200 if t['code'].startswith('68') else 100) for t in buys),
|
|||
|
|
'max_daily_participation':max(participation, default=0),
|
|||
|
|
'p95_daily_participation':float(np.quantile(participation,.95)) if participation else None}}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def neighbors(params, axes):
|
|||
|
|
out = [tuple(params)]
|
|||
|
|
for axis, values in enumerate(axes):
|
|||
|
|
i = values.index(params[axis])
|
|||
|
|
for j in (i-1, i+1):
|
|||
|
|
if 0 <= j < len(values):
|
|||
|
|
p = list(params)
|
|||
|
|
p[axis] = values[j]
|
|||
|
|
out.append(tuple(p))
|
|||
|
|
return out
|
|||
|
|
|
|||
|
|
|
|||
|
|
def choose(metrics, axes):
|
|||
|
|
scored = []
|
|||
|
|
for p, m in metrics.items():
|
|||
|
|
around = [metrics[n]['utility'] for n in neighbors(p, axes)]
|
|||
|
|
score = statistics.median(around)
|
|||
|
|
scored.append((score, m['utility'], -abs(p[2]-30), -abs(p[0]-5)-abs(p[1]-95), tuple(-x for x in p), p))
|
|||
|
|
winner = max(scored)[-1]
|
|||
|
|
return winner, {key(p):statistics.median(metrics[n]['utility'] for n in neighbors(p,axes)) for p in metrics}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
sys.addaudithook(no_network)
|
|||
|
|
p = read(ROOT/'protocol.json')
|
|||
|
|
assert hashlib.sha256((ROOT/'protocol.json').read_bytes()).hexdigest() == (ROOT/'protocol.sha256').read_text().split()[0]
|
|||
|
|
source = ROOT/'cache/daily.json.gz'
|
|||
|
|
assert hashlib.sha256(source.read_bytes()).hexdigest() == read(ROOT/'coverage.json')['cache_sha256']
|
|||
|
|
data = read(source)
|
|||
|
|
OUT.mkdir(exist_ok=True)
|
|||
|
|
axes = [p['entry_percentiles'],p['exit_percentiles'],p['sizes']]
|
|||
|
|
combos = list(itertools.product(*axes))
|
|||
|
|
baseline = tuple(p['baseline'])
|
|||
|
|
# 先逐日复现旧30和100结果,再计算新组合。
|
|||
|
|
audit = {}
|
|||
|
|
for size, folder in [(30,'timed_micro30'),(100,'timed_micro100_repaired')]:
|
|||
|
|
account = run(data, (5,95,size))
|
|||
|
|
old = read(OLD/f'results/{folder}/accounts.json.gz')['combined_30']['daily']
|
|||
|
|
diffs = [abs(x['nav']-y['nav']) for x,y in zip(old,account.basket.records)]
|
|||
|
|
assert len(diffs) == 678 and max(diffs) < 1e-10
|
|||
|
|
audit[str(size)] = {'daily_matches':len(diffs), 'max_nav_difference':max(diffs)}
|
|||
|
|
save('baseline_audit.json', audit)
|
|||
|
|
print('旧30/100账户逐日复现通过', flush=True)
|
|||
|
|
all_results, navs, dates = {}, {}, [r['date'] for r in data]
|
|||
|
|
for bps in [p['primary_cost_bps'], p['stress_cost_bps']]:
|
|||
|
|
results = {}
|
|||
|
|
for i, params in enumerate(combos):
|
|||
|
|
account = run(data, params, bps)
|
|||
|
|
results[key(params)] = summary(account, data, params, bps)
|
|||
|
|
if bps == p['primary_cost_bps']:
|
|||
|
|
navs[params] = [r['nav'] for r in account.basket.records]
|
|||
|
|
if (i+1)%21 == 0:
|
|||
|
|
print('成本',bps,'已完成',i+1,'/',len(combos),flush=True)
|
|||
|
|
all_results[str(bps)] = results
|
|||
|
|
save(f'grid_{bps}.json.gz', results)
|
|||
|
|
metrics = {c:all_results['30'][key(c)] for c in combos}
|
|||
|
|
hindsight, scores = choose(metrics, axes)
|
|||
|
|
switches, selection = {}, []
|
|||
|
|
for year in ('2024','2025'):
|
|||
|
|
n = sum(d[:4] <= year for d in dates)
|
|||
|
|
train = {c:metric(navs[c][:n], dates[:n]) for c in combos}
|
|||
|
|
winner, train_scores = choose(train, axes)
|
|||
|
|
end = dates[n-1]
|
|||
|
|
switches[end] = winner
|
|||
|
|
selection.append({'train_end':end,'apply_year':str(int(year)+1),'params':list(winner),
|
|||
|
|
'train':train[winner], 'neighbor_median_utility':train_scores[key(winner)],
|
|||
|
|
'training_cycle_count':sum(c['entry_date']<=end for c in metrics[winner]['cycles'])})
|
|||
|
|
rolling = run(data, baseline, switches=switches)
|
|||
|
|
rolling_summary = summary(rolling,data,baseline,30)
|
|||
|
|
save('walk_forward.json', {'selection':selection, 'summary':rolling_summary,
|
|||
|
|
'annual_selection_note':'持仓和现金连续,年末收盘切换下一日参数;2024为初始基线,不算检验期。',
|
|||
|
|
'daily':rolling.basket.records, 'trades':rolling.basket.trades, 'decisions':rolling.decisions})
|
|||
|
|
best_return = max(combos, key=lambda c:metrics[c]['total_return'])
|
|||
|
|
pareto = [c for c in combos if not any(metrics[o]['total_return'] >= metrics[c]['total_return'] and
|
|||
|
|
metrics[o]['max_drawdown'] >= metrics[c]['max_drawdown'] and
|
|||
|
|
(metrics[o]['total_return'] > metrics[c]['total_return'] or metrics[o]['max_drawdown'] > metrics[c]['max_drawdown']) for o in combos)]
|
|||
|
|
selected = dict.fromkeys([baseline,hindsight,best_return]+[tuple(s['params']) for s in selection])
|
|||
|
|
details = {}
|
|||
|
|
for c in selected:
|
|||
|
|
s = run(data,c)
|
|||
|
|
details[key(c)] = {'daily':s.basket.records, 'trades':s.basket.trades,
|
|||
|
|
'decisions':s.decisions, 'failures':s.basket.failures}
|
|||
|
|
save('selected_accounts.json.gz',details)
|
|||
|
|
ablations = {}
|
|||
|
|
for c in (baseline,hindsight):
|
|||
|
|
for mode in ('growth','low'):
|
|||
|
|
s = run(data,c,mode=mode)
|
|||
|
|
ablations[key(c)+'_'+mode] = summary(s,data,c,30)
|
|||
|
|
save('ablations.json',ablations)
|
|||
|
|
# 等收益可能来自完全相同入退场,披露实际不同的净值路径数量。
|
|||
|
|
signatures = {c:hashlib.sha256(np.asarray(navs[c],dtype='<f8').tobytes()).hexdigest() for c in combos}
|
|||
|
|
overview = {'grid_count':len(combos),'primary':30,'stress':60,'baseline':list(baseline),
|
|||
|
|
'full_sample_neighbor_choice':list(hindsight),'full_sample_max_return':list(best_return),
|
|||
|
|
'pareto':[list(c) for c in pareto],'neighbor_scores':scores,'unique_nav_paths':len(set(signatures.values())),
|
|||
|
|
'selections':selection,'baseline_return':metrics[baseline]['total_return'],
|
|||
|
|
'median_return':statistics.median(m['total_return'] for m in metrics.values()),
|
|||
|
|
'mean_return':statistics.mean(m['total_return'] for m in metrics.values()),
|
|||
|
|
'beat_baseline_count':sum(m['total_return']>metrics[baseline]['total_return'] for m in metrics.values())}
|
|||
|
|
save('overview.json',overview)
|
|||
|
|
with (OUT/'grid.csv').open('w',newline='') as f:
|
|||
|
|
fields=['entry_percentile','exit_percentile','stocks','cost_bps','return','annualized','drawdown','return2024','return2025','return2026','cycles','closed','turnover','max_weight','trades','neighbor_score']
|
|||
|
|
w=csv.writer(f,lineterminator='\n');w.writerow(fields)
|
|||
|
|
for bps, results in all_results.items():
|
|||
|
|
for r in results.values():
|
|||
|
|
w.writerow(r['params']+[bps,r['total_return'],r['annualized_return'],r['max_drawdown']]+[r['annual'][y]['return'] for y in ('2024','2025','2026')]+[r['cycle_count'],r['closed_cycles'],r['mean_turnover'],r['max_stock_weight'],r['trade_count'],scores[key(r['params'])] if bps=='30' else ''])
|
|||
|
|
np.savez_compressed(OUT/'navs.npz', dates=np.array(dates), params=np.array(combos), nav=np.array([navs[c] for c in combos]))
|
|||
|
|
save('run_manifest.json', {'protocol_sha256':hashlib.sha256((ROOT/'protocol.json').read_bytes()).hexdigest(),
|
|||
|
|
'cache_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),
|
|||
|
|
'scripts':{n:hashlib.sha256((ROOT/n).read_bytes()).hexdigest() for n in ('prepare.py','engine.py','calibrate.py')},
|
|||
|
|
'completed_at':dt.datetime.now().astimezone().isoformat()})
|
|||
|
|
print(json.dumps(overview,ensure_ascii=False),flush=True)
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == '__main__':
|
|||
|
|
main()
|