tradingSystem/research/strategy_chart_review_20261030/verify.py

80 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""检查图表数据、引用、浏览器布局及交付摘要;不访问外部服务。"""
import datetime as dt,hashlib,json,re,ast
from pathlib import Path
import pandas as pd
import numpy as np
from playwright.sync_api import sync_playwright
ROOT=Path(__file__).resolve().parent
def sha(path):
h=hashlib.sha256()
with path.open('rb') as f:
for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
return h.hexdigest()
def main():
manifest=json.loads((ROOT/'manifest.json').read_text());checks=[]
for name,digest in manifest['source_sha256'].items():assert sha(ROOT.parent/name)==digest
for path in ROOT.glob('*.py'):ast.parse(path.read_text())
pagefile=ROOT/'热度与评分实验六图汇总.html';content=pagefile.read_text();assert '<script' not in content and 'http://' not in content and 'https://' not in content
links=[]
for link in re.findall(r'href="([^"]+)"',content):
if not link.startswith('#'):assert (ROOT/link).exists(),link;links.append(link)
# 每份绘图数据重新与原CSV按唯一主键比对,避免作图时串列或把比例当百分数。
sources={}
for i,path in enumerate(sorted((ROOT/'data').glob('*.csv')),1):
data=pd.read_csv(path,dtype={'period':str})
if i==1:
src=ROOT.parent/'signal_scores_20261028/grid.csv';keys=['total','smart','hold','period','regime_index','regime','fee_bps'];fields=['mean_net','active_days','completed']
elif i in [2,4]:
src=ROOT.parent/'score_recurrence_20261029/grid.csv.gz';keys=['config','hold','period','phase_index','stage'];fields=['mean_net30','mean_net60','delta_k0_net30','active_days','completed']
elif i==3:
src=ROOT.parent/'heat_recurrence_20261029/grid.csv.gz';keys=['config','hold','period','phase_index','stage'];fields=['mean_net30','delta_k0_net30','active_days','completed']
elif i==5:
heat=pd.read_csv(ROOT.parent/'heat_calibration_20261028/results/grid_asof.csv')
heat=heat[(heat.heat==.75)&(heat.lower==0)&(heat.upper==2)&(heat.hold==4)].iloc[0]
score=sources[ROOT.parent/'score_recurrence_20261029/grid.csv.gz']
score=score[(score.score=='smart')&(score.threshold==.95)&(score['mode']=='frequency')&(score.k==13)&(score.hold==5)&(score.period=='2026')&(score.phase_index=='all')].iloc[0]
assert len(data)==4
for row in data.itertuples():
original=score if row.example.startswith('smart') else heat
metric=('mean_net' if row.example.startswith('smart') else 'mean_daily_net')+str(row.fee_bps)
assert np.isclose(row.mean_net,original[metric],atol=1e-12)
assert row.completed==original.completed
checks.append({'chart':i,'verified_cells':4,'fields':['mean_net','completed']});continue
elif i==6:
coverage=json.loads((ROOT.parent/'heat_recurrence_20261029/coverage.json').read_text())
daily=pd.read_csv(ROOT.parent/'heat_recurrence_20261029/current_window_comparison.csv')
n=daily[(daily.condition=='仅当天完整样本')&(daily.hold==5)].iloc[0].active_days
expected=[n]+[coverage['basis_coverage'][basis]['usable_days'] for basis in ['available','strict','latest']]
assert data['有效选股日'].tolist()==expected
checks.append({'chart':i,'verified_cells':4,'fields':['有效选股日']});continue
elif i==7:
src=ROOT.parent/'heat_recurrence_20261029/current_window_comparison.csv';keys=['condition','hold'];fields=['mean_net30','mean_net60','active_days','completed']
if src not in sources:sources[src]=pd.read_csv(src,dtype={'period':str})
merged=data.merge(sources[src][keys+fields],on=keys,suffixes=('_chart','_original'),validate='one_to_one');assert len(merged)==len(data)
for f in fields:assert np.allclose(merged[f+'_chart'],merged[f+'_original'],atol=1e-12,equal_nan=True)
checks.append({'chart':i,'verified_cells':len(data),'fields':fields})
errors=[];external=[]
with sync_playwright() as p:
browser=p.chromium.launch(executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',headless=True)
ctx=browser.new_context(viewport={'width':1440,'height':1050},device_scale_factor=1)
def route(r):
if r.request.url.startswith(('file:','data:','blob:')):r.continue_()
else:external.append(r.request.url.split('?')[0]);r.abort()
ctx.route('**/*',route);page=ctx.new_page();page.on('pageerror',lambda e:errors.append(str(e)));page.goto(pagefile.as_uri(),wait_until='load')
assert page.locator('article').count()==7;assert page.locator('img').count()==7;assert page.evaluate('Array.from(document.images).every(x=>x.complete&&x.naturalWidth>1000)')
assert 'stock_fund_heat_scores.score' in page.locator('#current-heat').inner_text()
assert '2026年10月29日09:58' in page.locator('#current-heat').inner_text()
page.screenshot(path=str(ROOT/'cache/desktop.png'),full_page=False)
page.locator('nav a[href="#chart-7"]').click();assert page.url.endswith('#chart-7');page.locator('#chart-7').screenshot(path=str(ROOT/'cache/current-heat.png'))
page.locator('nav a[href="#chart-4"]').click();assert page.url.endswith('#chart-4');page.locator('#chart-4 summary').click();assert page.locator('#chart-4 details').get_attribute('open') is not None
page.locator('#chart-4').screenshot(path=str(ROOT/'cache/stage-detail.png'));page.locator('#chart-4 summary').click()
page.set_viewport_size({'width':430,'height':932});page.goto(pagefile.as_uri(),wait_until='load');assert not page.evaluate('document.documentElement.scrollWidth>innerWidth');page.screenshot(path=str(ROOT/'cache/mobile.png'),full_page=False)
assert not errors and not external
browser.close()
manifest.update(status='完成',verified_at_beijing=dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).isoformat(),validation={'source_hashes':'全部一致','chart_data_checks':checks,'local_links':len(links),'browser':'本机独立无头Google Chrome','checks':['7张图片成功加载','热度说明包含真实字段及历史核验时刻','图目录锚点可用','明细表展开正确','430像素视口无页面横向溢出'],'external_requests':external,'page_errors':errors,'visual_review':'另由人工式目视检查PNG;检查记录在visual_review.json'},live_strategy_changes=False,outstanding_work=[])
manifest['files_sha256']={str(x.relative_to(ROOT)):sha(x) for x in ROOT.rglob('*') if x.is_file() and not any(part in ['cache','__pycache__'] for part in x.parts) and x.name!='manifest.json'}
(ROOT/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n');print('源哈希、436个绘图数据行、链接和浏览器检查通过;外部请求0')
if __name__=='__main__':main()