tradingSystem/research/signal_independence_20261111/test_research.py

61 lines
3.6 KiB
Python
Raw Permalink 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
import math
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import analyze as a
import weights as w
def main():
# 1. 无信号保留NaN,不能在相关样本中伪造0。
x=pd.DataFrame([{'day':'2026-11-09','code':'600000.SH','source':'qrs','direction':1},
{'day':'2026-11-09','code':'600001.SH','source':'mtf','direction':-1}])
p=a.panels(x);assert p[['qrs','mtf']].dropna().empty
# 2. 恒定方向不能得到“零相关、所以独立”的错误结论。
assert a.corr([1,1,1],[1,-1,1]) is None
# 3. 相同或完全反向两个通道都携带冗余,方向相反不增加独立预算。
assert math.isclose(abs(a.corr([1,-1,1,-1],[-1,1,-1,1])),1)
# 4. 正交且信息量对称,权重应等分。
orth=pd.DataFrame({'qrs':[1,1,-1,-1],'fund':[1,-1,1,-1],'mtf':[1,-1,-1,1]})
r=w.dependence_weights(orth);assert all(abs(v-1/3)<1e-12 for v in r['weights'].values())
# 5. 复制资金通道不能令该组多拿预算;分组后只保留观察时间确定的同一状态。
d=pd.DataFrame([{'day':'2026-11-09','code':'600000.SH','source':'intensity','direction':-1},
{'day':'2026-11-09','code':'600000.SH','source':'distribution','direction':-1}])
gp=w.grouped_panel(d);assert list(gp.columns)==['fund'] and gp.iloc[0,0]==-1
# 6. 午休不算经过的交易时间,前后两段相差一分钟。
assert a.trade_minute(dt.datetime(2026,11,9,13,1))-a.trade_minute(dt.datetime(2026,11,9,11,30))==1
# 7. 北交所及格式不明代码不能进入分析。
for c in ['920001.BJ','BJ430001','600000']:
try:a.code(c)
except ValueError:pass
else:raise AssertionError(c)
# 8. 当前生产缓存跨日重复preload不会重新读取;显式clear后才更新。
from intraday_timing.adapters.kline_daily_mem_cache import KlineDailyBulkMemCache
class Conn:
calls=0
day='2026-11-06'
def execute_query(self,*args,**kwargs):
self.calls+=1
return pd.DataFrame([{'symbol':'SH600000','trade_date':self.day,'open':10,'close':10,'high':11,'low':9,'vol':100,'amount':1000,'pre_close':10}])
c=Conn();cache=KlineDailyBulkMemCache(None,c)
cache.preload(['600000.SH'],dt.date(2026,11,1),dt.date(2026,11,9));c.day='2026-11-09'
assert cache.preload(['600000.SH'],dt.date(2026,11,1),dt.date(2026,11,10))==0 and c.calls==1
assert cache.get_kline_daily('600000.SH',dt.date(2026,11,1),dt.date(2026,11,10)).trade_date.max()==dt.date(2026,11,6)
cache.clear();cache.preload(['600000.SH'],dt.date(2026,11,1),dt.date(2026,11,10));assert c.calls==2
assert cache.get_kline_daily('600000.SH',dt.date(2026,11,1),dt.date(2026,11,10)).trade_date.max()==dt.date(2026,11,9)
# 9. 给历史序列追加未来极端行情,不得改变过去时点的QRS。
dates=pd.date_range('2026-01-01',periods=120).date
low=np.linspace(10,20,120)+np.sin(np.arange(120)/3)
high=low+1+np.cos(np.arange(120)/4)*.2
bars=pd.DataFrame({'trade_date':dates,'high':high,'low':low})
calc=w.DailyQRSComputer(None,n_regression=18,m_lookback=60,threshold=.7)
cutoff=dates[90];before=calc._compute_from_dataframe('600000.SH',bars.iloc[:91],cutoff).qrs_value
bars.loc[91:,['high','low']]*=100
after=calc._compute_from_dataframe('600000.SH',bars,cutoff).qrs_value
assert abs(before-after)<1e-12
print('9组离线边界通过,包含真实缓存类跨日复现与QRS未来截断一致性。')
if __name__=='__main__':main()