tradingSystem/research/macro_grid_20261029/test_engine.py

100 lines
4.6 KiB
Python

"""经仓库单测护栏运行的合成数据测试。"""
import unittest
import numpy as np
import pandas as pd
from engine import past_rank, bins, entry_path, own_features, labels, qrs, split_fold, holm, brier
from regions import first_passage, response_path
def synthetic(n=1000):
rng = np.random.default_rng(19)
close = 100*np.exp(np.cumsum(rng.normal(.0002, .01, n)))
return pd.DataFrame({'open': close*.999, 'high': close*1.02, 'low': close*.98,
'close': close, 'amount': rng.uniform(500, 1500, n), 'volume': 100},
index=pd.bdate_range('2010-01-01', periods=n))
class CalculationTests(unittest.TestCase):
def test_past_rank_excludes_today_and_ties(self):
s = pd.Series([1., 2., 3., 4., 4., 4.])
self.assertEqual(past_rank(s, 3).iloc[3], 1)
self.assertEqual(past_rank(s, 3).iloc[5], 2/3)
def test_grid_boundary(self):
self.assertEqual(bins(pd.Series([0, .2, .8, 1.])).tolist(), [0, 1, 4, 4])
def test_future_edits_do_not_change_features(self):
d = synthetic()
original = own_features(d)
modified = d.copy()
modified.iloc[850:] *= 5
altered = own_features(modified)
pd.testing.assert_frame_equal(original.iloc[:850], altered.iloc[:850])
def test_truncation_is_identical(self):
d = synthetic()
pd.testing.assert_frame_equal(own_features(d).iloc[:850], own_features(d.iloc[:850]))
def test_missing_history_resets(self):
d = synthetic()
d.loc[d.index[700], ['open', 'high', 'low', 'close']] = np.nan
self.assertTrue(qrs(d).iloc[700:].isna().all())
self.assertTrue(own_features(d).price_rank.iloc[700:750].isna().all())
def test_efficiency_bounds_and_path(self):
f = own_features(synthetic())
self.assertTrue(f.efficiency.dropna().between(0, 1+1e-12).all())
b = pd.Series([np.nan, 1, 1, 2, 2, 0, np.nan, 3, 3, 2])
e = entry_path(b, pd.Series([1.]*10))
self.assertEqual(e.entry_direction.iloc[3], 1)
self.assertEqual(e.entry_bin_direction.iloc[5], -1)
self.assertTrue(e.iloc[7:9].isna().all().all())
def test_forward_open_alignment(self):
d = synthetic(100)
data = {s: d for s in ['000300.SH', '000905.SH', '000852.SH']}
f = {s: own_features(d) for s in data}
f['market'] = f['000300.SH']
l = labels(data, f, 20)
self.assertAlmostEqual(l['000300.SH']['return'].iloc[40], d.open.iloc[61]/d.open.iloc[41]-1)
self.assertEqual(l['000300.SH'].exit_date.iloc[40], d.index[61])
self.assertTrue(l['000300.SH']['return'].iloc[-21:].isna().all())
def test_market_majority_not_mean_return(self):
d = synthetic(100)
data = {s: d.copy() for s in ['000300.SH', '000905.SH', '000852.SH']}
for s in data:
data[s].loc[d.index[61], 'open'] = data[s].open.iloc[41] * (1.1 if s != '000852.SH' else .5)
data[s].loc[d.index[61], 'high'] = max(data[s].high.iloc[61], data[s].open.iloc[61])
data[s].loc[d.index[61], 'low'] = min(data[s].low.iloc[61], data[s].open.iloc[61])
f = {s: own_features(x) for s, x in data.items()}
f['market'] = f['000300.SH']
self.assertEqual(labels(data, f)['market']['class'].iloc[40], 2)
def test_split_removes_label_overlap(self):
idx = pd.bdate_range('2018-01-01', '2024-12-31')
f = pd.DataFrame({'x': 1.}, index=idx)
l = pd.DataFrame({'class': 1., 'exit_date': pd.Series(idx, index=idx).shift(-21)}, index=idx)
train, test = split_fold(f, l, 2024, all_features=f)
self.assertTrue((l.loc[train, 'exit_date'] < idx[idx.year == 2024][0]).all())
self.assertTrue((train.year >= 2019).all())
def test_first_passage_ignores_intraday_and_gaps(self):
self.assertEqual(first_passage(100, np.array([101, 104, 99]), 96, 103), ('upper', 2))
self.assertEqual(first_passage(104, np.array([100]), 96, 103), ('gap_upper', 0))
self.assertEqual(first_passage(100, np.array([99, 101]), 96, 103), ('timeout', None))
def test_response_obeys_failure_order(self):
z = {'low': 95, 'high': 97}
self.assertEqual(response_path(np.array([96., 94., 98., 99., 99., 99.]), 2, z, 'lower'), 'failed')
self.assertEqual(response_path(np.array([96., 97., 98., 97., 97., 97.]), 2, z, 'lower'), 'success')
self.assertEqual(response_path(np.array([96., 98.]), 2, z, 'lower'), 'incomplete')
def test_brier_and_multiplicity(self):
np.testing.assert_allclose(brier(np.eye(3), [0, 1, 2]), 0)
np.testing.assert_allclose(holm([.01, .02, .5]), [.03, .04, .5])
if __name__ == '__main__':
unittest.main()