Compute option stats from exchange history instead of local DB.

Share history loading between history and stats APIs so average profit/loss matches the option history tab.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-07-11 09:34:49 +08:00
parent 68733eb4f9
commit baf94b4feb
5 changed files with 198 additions and 87 deletions
+17 -1
View File
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
from unittest import TestCase
from lib.options.options_db import init_options_tables
from lib.options.options_stats_lib import compute_options_stats
from lib.options.options_stats_lib import compute_options_stats, compute_options_stats_from_history
class OptionsStatsLibTests(TestCase):
@@ -67,3 +67,19 @@ class OptionsStatsLibTests(TestCase):
self.assertAlmostEqual(out["avg_loss_hold_sec"], 3 * 3600.0, delta=5.0)
self.assertEqual(out["open_count"], 1)
self.assertGreater(out["avg_open_hold_sec"], 1700.0)
def test_compute_options_stats_from_history_exchange_rows(self):
history = [
{"status": "open", "created_at": "2026-07-11 08:08:38"},
{"status": "closed", "realized_pnl": -3.99, "created_at": "2026-07-09 14:11:46", "closed_at": "2026-07-10 16:00:35"},
{"status": "closed", "realized_pnl": 0.87, "created_at": "2026-07-09 14:11:46", "closed_at": "2026-07-10 09:55:34"},
{"status": "closed", "realized_pnl": -1.33, "created_at": "2026-07-08 02:32:44", "closed_at": "2026-07-09 16:00:26"},
]
out = compute_options_stats_from_history(history)
self.assertEqual(out["total_closed"], 3)
self.assertEqual(out["win_count"], 1)
self.assertEqual(out["loss_count"], 2)
self.assertAlmostEqual(out["avg_win"], 0.87, places=4)
self.assertAlmostEqual(out["avg_loss"], 2.66, places=2)
self.assertAlmostEqual(out["profit_loss_ratio"], 0.33, places=2)
self.assertEqual(out["open_count"], 1)