"""离线标定的时间边界与持仓连续性测试。经项目隔离入口运行。""" import copy import datetime as dt import sys import unittest from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from prepare import threshold_rows, quantile from calibrate import run from engine import TimingStrategy def rows(n=6): out = [] for i in range(n): out.append({'date':str(dt.date(2024,1,2)+dt.timedelta(days=i)), 'members':['A','B','C'], 'risk':[], 'rows':{c:{'open':10.,'close':10.,'adj_factor':1.,'vol':100.,'amount':1000.} for c in 'ABC'}, 'limits':{c:{'up_limit':11.,'down_limit':9.} for c in 'ABC'}, 'signal':{'activity':0.,'activity_percentile':0.,'growth_break':False, 'thresholds':{'5':1.,'10':2.,'85':8.,'95':9.}}}) return out class CalibrationTests(unittest.TestCase): def test_threshold_excludes_today_and_future(self): obs=[{'date':str(dt.date(2018,1,1)+dt.timedelta(days=i)), 'activity':float(i)} for i in range(760)] history=[r['activity'] for r in obs[:756]] s={'date':obs[756]['date'],'activity':756.,'activity_percentile':1., 'low_threshold':quantile(history,.05),'high_threshold':quantile(history,.95)} original=threshold_rows([s],obs,[5,95])[0]['thresholds'] obs[756]['activity']=s['activity']=1e9 for x in obs[757:]: x['activity']=-1e9 self.assertEqual(original,threshold_rows([s],obs,[5,95])[0]['thresholds']) self.assertEqual(original,threshold_rows([s],obs[:757],[5,95])[0]['thresholds']) def test_trade_next_open_and_preserve_existing_units(self): data=rows(3) data[1]['rows']['A']['close']=10.5 s=run(data,(5,95,2)) self.assertFalse([t for t in s.basket.trades if t['date']==data[0]['date']]) self.assertEqual(len(s.basket.trades),2) self.assertTrue(all(t['date']==data[1]['date'] for t in s.basket.trades)) self.assertEqual(s.basket.units['A'],s.basket.units['B']) def test_high_vetoes_growth_and_low(self): data=rows(2) for row in data: row['signal'].update(activity=10.,growth_break=True) s=run(data,(5,95,2)) self.assertEqual(s.basket.trades,[]) self.assertTrue(s.decisions[0]['entry_vetoed_by_high']) def test_exit_residual_cannot_restart_buying(self): data=rows(5) data[1]['signal']['activity']=10. data[2]['rows']['A']['open']=9. data[3]['rows']['A']['open']=9. s=run(data,(5,95,1)) self.assertEqual([(t['date'],t['side']) for t in s.basket.trades], [(data[1]['date'],'buy'),(data[4]['date'],'sell')]) self.assertEqual(s.decisions[2]['state_after_close'],'exiting') self.assertEqual(s.decisions[3]['state_after_close'],'exiting') def test_parameter_change_preserves_account_and_is_next_day(self): data=rows(5) # 已买入两只以后,只数改成一只,随后再改回两只;不能重置净值。 changes={data[2]['date']:(5,95,1),data[3]['date']:(5,95,2)} s=run(data,(5,95,2),switches=changes) self.assertEqual([r['positions'] for r in s.basket.records],[0,2,2,1,2]) self.assertLess(s.basket.records[-1]['nav'],s.basket.records[1]['nav']) self.assertEqual(len([t for t in s.basket.trades if t['code']=='A']),1) self.assertEqual(s.decisions[3]['executed_signal_date'],data[2]['date']) def test_future_prices_and_lists_do_not_change_prefix(self): data=rows(6) a=run(data,(5,95,2)) altered=copy.deepcopy(data) for row in altered[3:]: row['members'].reverse() row['rows']['A']['close']=10000. row['signal']['activity']=100. b=run(altered,(5,95,2)) prefix=run(data[:3],(5,95,2)) self.assertEqual(a.basket.records[:3],b.basket.records[:3]) self.assertEqual(a.basket.records[:3],prefix.basket.records) if __name__=='__main__': unittest.main()