Files

81 lines
4.1 KiB
Python

from datetime import datetime, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace
import unittest
import zipfile
from unittest.mock import patch
import numpy as np
import pandas as pd
from mt5_app.config import ROOT, Settings
from mt5_app.research import download_history, export_archive, run_research
from mt5_app.store import Store
class ResearchTests(unittest.TestCase):
def setUp(self):
self.tmp = TemporaryDirectory(prefix='research_test_', dir=ROOT / 'data')
self.settings = Settings(data_path=Path(self.tmp.name), state_dir=Path(self.tmp.name))
self.store = Store(self.settings.state_dir)
def tearDown(self):
self.tmp.cleanup()
def test_identical_prices_and_rules_produce_identical_comparison_and_backtest(self):
days = pd.bdate_range('2024-02-01', periods=620)
rows = []
for i, day in enumerate(days):
for symbol, start, slope in [('SET', 1000, 1), ('AAA', 10, .1), ('BBB', 20, .15)]:
price = start + i * slope
rows.append((symbol, str(day.date()), price, price + .005, price - .005, price, 2_000_000, 200))
self.store.save_bars(rows)
archive, _ = export_archive(self.store, self.settings)
with patch('mt5_app.research.legacy_archives', return_value=[archive]):
result = run_research(self.store, self.settings, lambda *args: None)
comparison = result['comparison']
self.assertTrue(comparison['same_signal_membership_and_model'])
self.assertTrue(comparison['same_rankings'])
self.assertTrue(comparison['same_allocation_scores'])
self.assertEqual(comparison['ohlcv']['close']['different'], 0)
self.assertEqual(comparison['ohlcv']['volume']['different'], 0)
self.assertEqual(comparison['historical_target_days_different'], 0)
self.assertEqual(comparison['backtest_mt5']['metrics']['total_return'],
comparison['backtest_siamchart']['metrics']['total_return'])
self.assertTrue((self.settings.state_dir / 'comparison.json').is_file())
def test_real_volume_is_preserved_and_unfinished_today_is_not_imported(self):
rows = np.array([
(int(datetime(2026, 10, 14, tzinfo=timezone.utc).timestamp()), 10., 11., 9., 10., 99, 0, 100_000),
(int(datetime(2026, 10, 15, tzinfo=timezone.utc).timestamp()), 11., 12., 10., 11., 123, 0, 200_000),
], dtype=[('time', 'i8'), ('open', 'f8'), ('high', 'f8'), ('low', 'f8'), ('close', 'f8'),
('tick_volume', 'u8'), ('spread', 'i4'), ('real_volume', 'u8')])
broker = SimpleNamespace(symbols=lambda: [SimpleNamespace(name='AAA', path='SET\\Common Stock\\AAA')],
history=lambda *args: rows)
with patch.object(Settings, 'closed_through', return_value='2026-10-14'):
download_history(broker, self.store, self.settings, lambda *args: None)
stored = self.store.bars('2026-10-01', '2026-10-31')
self.assertEqual({r['day'] for r in stored}, {'2026-10-14'})
self.assertEqual(stored[0]['volume'], 100_000)
self.assertEqual(stored[0]['tick_volume'], 99)
def test_stock_bar_without_set_session_is_quarantined_not_forward_filled(self):
self.store.save_bars([
('SET', '2026-03-02', 1000, 1001, 999, 1000, 0, 1),
('AAA', '2026-03-02', 10, 10, 10, 10, 100, 1),
('AAA', '2026-03-03', 11, 11, 11, 11, 100, 1),
('SET', '2026-03-04', 1001, 1002, 1000, 1001, 0, 1),
('AAA', '2026-03-04', 11, 11, 11, 11, 100, 1),
])
archive, _ = export_archive(self.store, self.settings)
with zipfile.ZipFile(archive) as z:
self.assertEqual(len(z.namelist()), 2)
self.assertFalse(any('2026-03-03' in name for name in z.namelist()))
self.assertEqual(self.store.bar_summary()['rows'], 5) # Raw evidence is retained.
self.assertEqual(self.store.get('data_quality')['excluded_non_session_days'][0]['day'], '2026-03-03')
if __name__ == '__main__':
unittest.main()