-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathmcp_server.py
More file actions
2313 lines (2175 loc) · 86.1 KB
/
Copy pathmcp_server.py
File metadata and controls
2313 lines (2175 loc) · 86.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
MCP Server for Backtest Analysis
Exposes backtest data to LLMs (GitHub Copilot, Claude, ChatGPT)
via the Model Context Protocol.
Usage:
# Standalone (single directory)
python -m investing_algorithm_framework.cli.mcp_server \
-d examples/batch_one
# Multiple directories
python -m investing_algorithm_framework.cli.mcp_server \
-d examples/batch_one -d examples/batch_two
# Via CLI
investing-algorithm-framework mcp -d examples/batch_one
Configure in VS Code (.vscode/mcp.json):
{
"servers": {
"backtest-analysis": {
"command": "python",
"args": [
"-m", "investing_algorithm_framework.cli.mcp_server",
"-d", "examples/batch_one",
"-d", "examples/batch_two"
]
}
}
}
"""
import sys
import json
import os
import argparse
from typing import Optional, List, Union
def _load_backtests(directory: Union[str, List[str]]):
"""Load and recalculate backtests from directory(ies)."""
from investing_algorithm_framework import (
BacktestReport, recalculate_backtests,
)
# Normalize to a list of directories
if isinstance(directory, str):
# Support comma-separated directories for backward compatibility
dirs = [d.strip() for d in directory.split(',') if d.strip()]
else:
dirs = [d.strip() for d in directory if d.strip()]
if len(dirs) == 1:
report = BacktestReport.open(directory_path=dirs[0])
else:
report = BacktestReport.open(directory_path=dirs)
recalculate_backtests(report.backtests)
return report.backtests, report._source_tags
def _fmt_pct(v):
if v is None:
return "—"
return f"{v * 100:.2f}%"
def _fmt_dec(v, decimals=2):
if v is None:
return "—"
return f"{v:.{decimals}f}"
def _strategy_summary(bt):
"""Build a summary dict for one Backtest."""
s = bt.backtest_summary
summary = {}
if s:
summary = s.to_dict()
return {
"algorithm_id": bt.algorithm_id,
"parameters": bt.parameters or {},
"num_windows": len(bt.backtest_runs),
"summary": summary,
}
def _metrics_table(bt):
"""Build a markdown metrics table for a strategy."""
s = bt.backtest_summary
if not s:
return "No summary metrics available."
d = s.to_dict()
lines = []
for k, v in sorted(d.items()):
if v is not None:
lines.append(f"- **{k}**: {v}")
return "\n".join(lines)
def _per_window_table(bt):
"""Markdown table of per-window metrics."""
runs = bt.get_all_backtest_runs()
if not runs:
return "No runs available."
header = (
"| Window | CAGR | Sharpe | Sortino"
" | Max DD | Win Rate | Trades |"
)
sep = "|--------|------|--------|---------|--------|----------|--------|"
rows = [header, sep]
for run in runs:
m = run.backtest_metrics
name = run.backtest_date_range_name or "—"
if m:
rows.append(
f"| {name} "
f"| {_fmt_pct(m.cagr)} "
f"| {_fmt_dec(m.sharpe_ratio)} "
f"| {_fmt_dec(m.sortino_ratio)} "
f"| {_fmt_pct(abs(m.max_drawdown) if m.max_drawdown else None)} " # noqa: E501
f"| {_fmt_pct(m.win_rate)} "
f"| {m.number_of_trades or 0} |"
)
else:
rows.append(f"| {name} | — | — | — | — | — | — |")
return "\n".join(rows)
def _trading_activity_table(backtests, tags=None):
"""Markdown table of trading-activity metrics."""
has_tags = tags and any(tags.values())
tag_hdr = "| Batch " if has_tags else ""
tag_sep = "|-------" if has_tags else ""
header = (
"| Strategy " + tag_hdr
+ "| Profit Factor | Win Rate"
" | Trades/yr | Trades/mo "
"| Trades/wk | # Trades"
" | Avg Return | Median Return "
"| Avg Duration | Win Streak"
" | Loss Streak | % Win Months |"
)
sep = (
"|----------" + tag_sep
+ "|---------------|----------"
"|-----------|----------"
"|-----------|----------"
"|------------|---------------"
"|--------------|------------"
"|-------------|--------------|"
)
rows = [header, sep]
for bt in backtests:
s = bt.backtest_summary
tag_col = ""
if has_tags:
t = (tags or {}).get(bt.algorithm_id, '')
tag_col = f"| {t} "
if not s:
rows.append(
f"| {bt.algorithm_id} "
f"{tag_col}|" + " — |" * 12
)
continue
tpy = getattr(s, "trades_per_year", None)
tpw = (tpy / 52) if tpy is not None else None
rows.append(
f"| {bt.algorithm_id} "
f"{tag_col}"
f"| {_fmt_dec(getattr(s, 'profit_factor', None))} "
f"| {_fmt_pct(getattr(s, 'win_rate', None))} "
f"| {_fmt_dec(tpy)} "
f"| {_fmt_dec(getattr(s, 'trades_per_month', None))} "
f"| {_fmt_dec(tpw)} "
f"| {getattr(s, 'number_of_trades', None) or 0} "
f"| {_fmt_pct(getattr(s, 'average_trade_return_percentage', None))} " # noqa: E501
f"| {_fmt_pct(getattr(s, 'median_trade_return_percentage', None))} " # noqa: E501
f"| {_fmt_dec(getattr(s, 'average_trade_duration', None))} "
f"| {getattr(s, 'max_consecutive_wins', None) or 0} "
f"| {getattr(s, 'max_consecutive_losses', None) or 0} "
f"| {_fmt_pct(getattr(s, 'percentage_winning_months', None))} |"
)
return "\n".join(rows)
def _ranking_table(
backtests, metric="sharpe_ratio", ascending=False, tags=None
):
"""Rank strategies by a metric across all windows (summary)."""
has_tags = tags and any(tags.values())
entries = []
for bt in backtests:
s = bt.backtest_summary
val = getattr(s, metric, None) if s else None
entries.append({
"algorithm_id": bt.algorithm_id,
"value": val,
})
entries.sort(
key=lambda x: (x["value"] is None, x["value"] or 0),
reverse=not ascending,
)
tag_hdr = "| Batch " if has_tags else ""
tag_sep = "|-------" if has_tags else ""
header = f"| Rank | Strategy {tag_hdr}| {metric} |"
sep = (
"|------|----------"
+ tag_sep
+ "|" + "-" * (len(metric) + 2) + "|"
)
rows = [header, sep]
for i, e in enumerate(entries):
v = _fmt_dec(e["value"]) if e["value"] is not None else "—"
tag_col = ""
if has_tags:
t = (tags or {}).get(e["algorithm_id"], '')
tag_col = f"| {t} "
rows.append(
f"| {i + 1} | {e['algorithm_id']} {tag_col}| {v} |"
)
return "\n".join(rows)
def _top_trades(bt, n=10):
"""Get top trades by magnitude for a strategy."""
all_trades = []
for run in bt.get_all_backtest_runs():
for t in (run.trades or []):
cost = getattr(t, 'cost', 0) or 0
ng = getattr(t, 'net_gain', 0) or 0
pct = (ng / cost * 100) if cost else 0
all_trades.append({
"symbol": getattr(t, 'target_symbol', '—'),
"opened": str(t.opened_at)[:10] if t.opened_at else "—",
"closed": str(t.closed_at)[:10] if t.closed_at else "—",
"return_pct": round(pct, 2),
"net_gain": round(ng, 2),
"window": run.backtest_date_range_name or "—",
})
all_trades.sort(key=lambda x: abs(x["return_pct"]), reverse=True)
return all_trades[:n]
def _full_analysis(backtests, tags=None):
"""Generate a complete analysis markdown document."""
has_tags = tags and any(tags.values())
md = "# Backtest Analysis Data\n\n"
md += f"**Strategies:** {len(backtests)}\n"
windows = set()
for bt in backtests:
for r in bt.get_all_backtest_runs():
windows.add(r.backtest_date_range_name or "—")
md += f"**Windows:** {len(windows)}\n\n"
# Ranking table
md += "## Strategy Ranking (by Sharpe Ratio)\n\n"
md += _ranking_table(
backtests, "sharpe_ratio", tags=tags
) + "\n\n"
# Per strategy
for bt in backtests:
md += f"## {bt.algorithm_id}\n\n"
if has_tags:
t = (tags or {}).get(bt.algorithm_id, '')
if t:
md += f"**Batch:** {t}\n\n"
if bt.parameters:
params = ", ".join(f"{k}={v}" for k, v in bt.parameters.items())
md += f"**Parameters:** {params}\n\n"
md += "### Summary Metrics\n\n"
md += _metrics_table(bt) + "\n\n"
md += "### Per-Window Breakdown\n\n"
md += _per_window_table(bt) + "\n\n"
trades = _top_trades(bt, 5)
if trades:
md += "### Top Trades\n\n"
md += (
"| Symbol | Opened | Closed"
" | Return % | Net Gain | Window |\n"
)
md += (
"|--------|--------|--------"
"|----------|----------|--------|\n"
)
for t in trades:
md += (
f"| {t['symbol']} | {t['opened']} | {t['closed']} "
f"| {t['return_pct']}% | {t['net_gain']} "
f"| {t['window']} |\n"
)
md += "\n"
return md
def _fmt_date(d):
"""Format a datetime to YYYY-MM-DD."""
if d is None:
return "—"
if hasattr(d, 'strftime'):
return d.strftime("%Y-%m-%d")
return str(d)[:10]
def _equity_curve_table(bt, window=None, sample=50):
"""Equity curve as a markdown table, sampled to limit size."""
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
if not runs:
return "No runs found."
md = ""
for run in runs:
m = run.backtest_metrics
if not m or not m.equity_curve:
continue
ec = m.equity_curve
name = run.backtest_date_range_name or "—"
md += f"### {name}\n\n"
md += "| Date | Value | Growth % |\n"
md += "|------|-------|----------|\n"
initial = ec[0][0] if ec else 1
if initial == 0:
initial = 1
step = max(1, len(ec) // sample)
for i in range(0, len(ec), step):
v, d = ec[i]
growth = (v / initial - 1) * 100
md += f"| {_fmt_date(d)} | {v:.2f} | {growth:.2f}% |\n"
# Always include last point
if (len(ec) - 1) % step != 0:
v, d = ec[-1]
growth = (v / initial - 1) * 100
md += f"| {_fmt_date(d)} | {v:.2f} | {growth:.2f}% |\n"
md += "\n"
return md or "No equity curve data."
def _equity_curves_stacked(backtests, sids, window=None, sample=50):
"""Multi-strategy equity curves as a stacked markdown table."""
# Collect per-window data for each strategy
windows = {}
for bt, sid in zip(backtests, sids):
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
for run in runs:
m = run.backtest_metrics
if not m or not m.equity_curve:
continue
wname = run.backtest_date_range_name or "—"
ec = m.equity_curve
initial = ec[0][0] if ec else 1
if initial == 0:
initial = 1
step = max(1, len(ec) // sample)
points = []
for i in range(0, len(ec), step):
v, d = ec[i]
points.append((_fmt_date(d), (v / initial - 1) * 100))
if (len(ec) - 1) % step != 0:
v, d = ec[-1]
points.append((_fmt_date(d), (v / initial - 1) * 100))
windows.setdefault(wname, {})[sid] = points
if not windows:
return "No equity curve data."
md = f"# Equity Curves — {', '.join(sids)}\n\n"
for wname, strats in sorted(windows.items()):
md += f"### {wname}\n\n"
md += "| Date |"
for sid in sids:
if sid in strats:
md += f" {sid} |"
md += "\n|------|"
for sid in sids:
if sid in strats:
md += "--------|"
md += "\n"
# Merge dates
all_dates = []
for sid in sids:
if sid in strats:
for d, _ in strats[sid]:
if d not in all_dates:
all_dates.append(d)
all_dates.sort()
date_map = {}
for sid in sids:
if sid in strats:
date_map[sid] = {d: v for d, v in strats[sid]}
for d in all_dates:
md += f"| {d} |"
for sid in sids:
if sid in strats:
v = date_map[sid].get(d)
md += f" {v:.2f}% |" if v is not None else " — |"
md += "\n"
md += "\n"
return md
def _drawdown_series_stacked(backtests, sids, window=None, sample=50):
"""Multi-strategy drawdown series as a stacked markdown table."""
windows = {}
for bt, sid in zip(backtests, sids):
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
for run in runs:
m = run.backtest_metrics
if not m or not m.drawdown_series:
continue
wname = run.backtest_date_range_name or "—"
dd = m.drawdown_series
step = max(1, len(dd) // sample)
points = []
for i in range(0, len(dd), step):
v, d = dd[i]
pct = v * 100 if abs(v) < 1 else v
points.append((_fmt_date(d), pct))
if (len(dd) - 1) % step != 0:
v, d = dd[-1]
pct = v * 100 if abs(v) < 1 else v
points.append((_fmt_date(d), pct))
windows.setdefault(wname, {})[sid] = points
if not windows:
return "No drawdown data."
md = f"# Drawdown Series — {', '.join(sids)}\n\n"
for wname, strats in sorted(windows.items()):
md += f"### {wname}\n\n"
md += "| Date |"
for sid in sids:
if sid in strats:
md += f" {sid} |"
md += "\n|------|"
for sid in sids:
if sid in strats:
md += "--------|"
md += "\n"
all_dates = []
for sid in sids:
if sid in strats:
for d, _ in strats[sid]:
if d not in all_dates:
all_dates.append(d)
all_dates.sort()
date_map = {sid: {d: v for d, v in strats[sid]}
for sid in sids if sid in strats}
for d in all_dates:
md += f"| {d} |"
for sid in sids:
if sid in strats:
v = date_map[sid].get(d)
md += f" {v:.2f}% |" if v is not None else " — |"
md += "\n"
md += "\n"
return md
def _rolling_sharpe_stacked(backtests, sids, window=None, sample=50):
"""Multi-strategy rolling Sharpe as a stacked markdown table."""
windows = {}
for bt, sid in zip(backtests, sids):
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
for run in runs:
m = run.backtest_metrics
if not m or not m.rolling_sharpe_ratio:
continue
wname = run.backtest_date_range_name or "—"
rs = m.rolling_sharpe_ratio
step = max(1, len(rs) // sample)
points = []
for i in range(0, len(rs), step):
v, d = rs[i]
points.append((_fmt_date(d), v))
if (len(rs) - 1) % step != 0:
v, d = rs[-1]
points.append((_fmt_date(d), v))
windows.setdefault(wname, {})[sid] = points
if not windows:
return "No rolling Sharpe data."
md = f"# Rolling Sharpe — {', '.join(sids)}\n\n"
for wname, strats in sorted(windows.items()):
md += f"### {wname}\n\n"
md += "| Date |"
for sid in sids:
if sid in strats:
md += f" {sid} |"
md += "\n|------|"
for sid in sids:
if sid in strats:
md += "--------|"
md += "\n"
all_dates = []
for sid in sids:
if sid in strats:
for d, _ in strats[sid]:
if d not in all_dates:
all_dates.append(d)
all_dates.sort()
date_map = {sid: {d: v for d, v in strats[sid]}
for sid in sids if sid in strats}
for d in all_dates:
md += f"| {d} |"
for sid in sids:
if sid in strats:
v = date_map[sid].get(d)
md += f" {v:.3f} |" if v is not None else " — |"
md += "\n"
md += "\n"
return md
def _yearly_returns_stacked(backtests, sids, window=None):
"""Multi-strategy yearly returns as a stacked markdown table."""
windows = {}
for bt, sid in zip(backtests, sids):
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
for run in runs:
m = run.backtest_metrics
if not m or not m.yearly_returns:
continue
wname = run.backtest_date_range_name or "—"
points = []
for v, d in m.yearly_returns:
yr = d.year if hasattr(d, 'year') else str(d)
pct = v * 100 if abs(v) < 1 else v
points.append((str(yr), pct))
windows.setdefault(wname, {})[sid] = points
if not windows:
return "No yearly returns data."
md = f"# Yearly Returns — {', '.join(sids)}\n\n"
for wname, strats in sorted(windows.items()):
md += f"### {wname}\n\n"
md += "| Year |"
for sid in sids:
if sid in strats:
md += f" {sid} |"
md += "\n|------|"
for sid in sids:
if sid in strats:
md += "--------|"
md += "\n"
all_years = []
for sid in sids:
if sid in strats:
for yr, _ in strats[sid]:
if yr not in all_years:
all_years.append(yr)
all_years.sort()
year_map = {sid: {yr: v for yr, v in strats[sid]}
for sid in sids if sid in strats}
for yr in all_years:
md += f"| {yr} |"
for sid in sids:
if sid in strats:
v = year_map[sid].get(yr)
md += f" {v:.2f}% |" if v is not None else " — |"
md += "\n"
md += "\n"
return md
def _monthly_returns_stacked(backtests, sids, window=None):
"""Multi-strategy monthly returns — sequential tables per strategy."""
md = f"# Monthly Returns — {', '.join(sids)}\n\n"
found = False
for bt, sid in zip(backtests, sids):
sub = _monthly_returns_table(bt, window=window)
if sub and sub != "No monthly returns data.":
md += f"## {sid}\n\n{sub}\n"
found = True
return md if found else "No monthly returns data."
def _portfolio_snapshots_stacked(backtests, sids, window=None):
"""Multi-strategy portfolio snapshots as a stacked table."""
md = f"# Portfolio Snapshots — {', '.join(sids)}\n\n"
md += "| Strategy | Window | Initial | Final | Net Gain | Growth % |\n"
md += "|----------|--------|---------|-------|----------|----------|\n"
found = False
for bt, sid in zip(backtests, sids):
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
for run in runs:
wname = run.backtest_date_range_name or "—"
if run.portfolio_snapshots:
first = run.portfolio_snapshots[0]
last = run.portfolio_snapshots[-1]
iv = getattr(first, 'trading_symbol_balance', 0) or 0
fv = getattr(last, 'trading_symbol_balance', 0) or 0
ng = fv - iv
gr = (fv / iv - 1) * 100 if iv else 0
md += (
f"| {sid} | {wname} | {iv:.2f} | {fv:.2f} "
f"| {ng:.2f} | {gr:.2f}% |\n"
)
found = True
return md if found else "No portfolio snapshot data."
def _drawdown_series_table(bt, window=None, sample=50):
"""Drawdown series as a markdown table."""
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
md = ""
for run in runs:
m = run.backtest_metrics
if not m or not m.drawdown_series:
continue
dd = m.drawdown_series
name = run.backtest_date_range_name or "—"
md += f"### {name}\n\n"
md += "| Date | Drawdown % |\n"
md += "|------|------------|\n"
step = max(1, len(dd) // sample)
for i in range(0, len(dd), step):
v, d = dd[i]
pct = v * 100 if abs(v) < 1 else v
md += f"| {_fmt_date(d)} | {pct:.2f}% |\n"
if (len(dd) - 1) % step != 0:
v, d = dd[-1]
pct = v * 100 if abs(v) < 1 else v
md += f"| {_fmt_date(d)} | {pct:.2f}% |\n"
md += "\n"
return md or "No drawdown data."
def _monthly_returns_table(bt, window=None):
"""Monthly returns heatmap data as markdown."""
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
md = ""
for run in runs:
m = run.backtest_metrics
if not m or not m.monthly_returns:
continue
name = run.backtest_date_range_name or "—"
md += f"### {name}\n\n"
# Build heatmap: {year: {month: value}}
heatmap = {}
for v, d in m.monthly_returns:
y = d.year if hasattr(d, 'year') else int(str(d)[:4])
mo = d.month if hasattr(d, 'month') else int(str(d)[5:7])
pct = v * 100 if abs(v) < 1 else v
heatmap.setdefault(y, {})[mo] = round(pct, 2)
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
md += "| Year | " + " | ".join(months) + " | Total |\n"
md += "|------|" + "|".join(["------"] * 12) + "|-------|\n"
for y in sorted(heatmap.keys()):
row = [f"| {y} "]
total = 0
for mo in range(1, 13):
val = heatmap[y].get(mo)
if val is not None:
row.append(f" {val:.1f}% ")
total += val
else:
row.append(" — ")
row.append(f" {total:.1f}% |")
md += "|".join(row) + "\n"
md += "\n"
return md or "No monthly returns data."
def _yearly_returns_table(bt, window=None):
"""Yearly returns as markdown."""
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
md = ""
for run in runs:
m = run.backtest_metrics
if not m or not m.yearly_returns:
continue
name = run.backtest_date_range_name or "—"
md += f"### {name}\n\n"
md += "| Year | Return % |\n"
md += "|------|----------|\n"
for v, d in m.yearly_returns:
yr = d.year if hasattr(d, 'year') else str(d)
pct = v * 100 if abs(v) < 1 else v
md += f"| {yr} | {pct:.2f}% |\n"
md += "\n"
return md or "No yearly returns data."
def _rolling_sharpe_table(bt, window=None, sample=50):
"""Rolling Sharpe ratio as markdown."""
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
md = ""
for run in runs:
m = run.backtest_metrics
if not m or not m.rolling_sharpe_ratio:
continue
rs = m.rolling_sharpe_ratio
name = run.backtest_date_range_name or "—"
md += f"### {name}\n\n"
md += "| Date | Sharpe |\n"
md += "|------|--------|\n"
step = max(1, len(rs) // sample)
for i in range(0, len(rs), step):
v, d = rs[i]
md += f"| {_fmt_date(d)} | {v:.3f} |\n"
if (len(rs) - 1) % step != 0:
v, d = rs[-1]
md += f"| {_fmt_date(d)} | {v:.3f} |\n"
md += "\n"
return md or "No rolling Sharpe data."
def _symbol_breakdown(bt):
"""Per-symbol trade breakdown."""
sym_stats = {}
for run in bt.get_all_backtest_runs():
for t in (run.trades or []):
sym = getattr(t, 'target_symbol', '') or '—'
ng = getattr(t, 'net_gain', 0) or 0
entry = sym_stats.setdefault(sym, {
'count': 0, 'gain': 0.0, 'wins': 0, 'losses': 0
})
entry['count'] += 1
entry['gain'] += ng
if ng > 0:
entry['wins'] += 1
elif ng < 0:
entry['losses'] += 1
if not sym_stats:
return "No trade data available."
md = "| Symbol | Trades | Net Gain | Wins | Losses | Win Rate |\n"
md += "|--------|--------|----------|------|--------|----------|\n"
for sym, s in sorted(sym_stats.items(),
key=lambda x: x[1]['gain'], reverse=True):
wr = (s['wins'] / s['count'] * 100) if s['count'] else 0
md += (
f"| {sym} | {s['count']} | {s['gain']:.2f} "
f"| {s['wins']} | {s['losses']} | {wr:.1f}% |\n"
)
return md
def _return_scenarios(bt):
"""Return scenario analysis (best/worst month/year, etc.)."""
s = bt.backtest_summary
md = ""
if not s:
return "No summary data."
# Best/worst from per-run metrics
all_months, all_years = [], []
for run in bt.get_all_backtest_runs():
m = run.backtest_metrics
if not m:
continue
if m.best_month and m.best_month[0] is not None:
v = m.best_month[0]
pct = v * 100 if abs(v) < 1 else v
all_months.append(("Best Month", pct, m.best_month[1],
run.backtest_date_range_name))
if m.worst_month and m.worst_month[0] is not None:
v = m.worst_month[0]
pct = v * 100 if abs(v) < 1 else v
all_months.append(("Worst Month", pct, m.worst_month[1],
run.backtest_date_range_name))
if m.best_year and m.best_year[0] is not None:
v = m.best_year[0]
pct = v * 100 if abs(v) < 1 else v
all_years.append(("Best Year", pct, m.best_year[1],
run.backtest_date_range_name))
if m.worst_year and m.worst_year[0] is not None:
v = m.worst_year[0]
pct = v * 100 if abs(v) < 1 else v
all_years.append(("Worst Year", pct, m.worst_year[1],
run.backtest_date_range_name))
if all_months or all_years:
md += "| Scenario | Return % | Date | Window |\n"
md += "|----------|----------|------|--------|\n"
for label, pct, d, win in all_months + all_years:
md += f"| {label} | {pct:.2f}% | {_fmt_date(d)} | {win or '—'} |\n"
md += "\n"
# Key risk stats
md += "**Risk Summary:**\n"
md += f"- Max Drawdown: {_fmt_pct(s.max_drawdown)}\n"
md += f"- VaR 95%: {_fmt_pct(getattr(s, 'var_95', None))}\n"
md += f"- CVaR 95%: {_fmt_pct(getattr(s, 'cvar_95', None))}\n"
win_mo = _fmt_pct(
getattr(s, 'percentage_winning_months', None)
)
win_yr = _fmt_pct(
getattr(s, 'percentage_winning_years', None)
)
md += f"- % Winning Months: {win_mo}\n"
md += f"- % Winning Years: {win_yr}\n"
cons_w = getattr(s, 'max_consecutive_wins', '—')
cons_l = getattr(s, 'max_consecutive_losses', '—')
md += f"- Max Consecutive Wins: {cons_w}\n"
md += f"- Max Consecutive Losses: {cons_l}\n"
return md
def _correlation_matrix(backtests, window=None):
"""Cross-strategy return correlation matrix."""
# Collect monthly return series per strategy
series = {}
for bt in backtests:
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
returns = {}
for run in runs:
m = run.backtest_metrics
if m and m.monthly_returns:
for v, d in m.monthly_returns:
key = f"{d.year}-{d.month:02d}" if hasattr(d, 'year') \
else str(d)[:7]
returns[key] = v
if returns:
series[bt.algorithm_id] = returns
if len(series) < 2:
return "Need at least 2 strategies with return data for correlation."
ids = list(series.keys())
# Find common months
common = set(series[ids[0]].keys())
for sid in ids[1:]:
common &= set(series[sid].keys())
common = sorted(common)
if len(common) < 3:
return "Insufficient overlapping return data for correlation."
# Compute Pearson correlation
def _mean(vals):
return sum(vals) / len(vals) if vals else 0
def _corr(x, y):
mx, my = _mean(x), _mean(y)
num = sum((a - mx) * (b - my) for a, b in zip(x, y))
dx = sum((a - mx) ** 2 for a in x) ** 0.5
dy = sum((b - my) ** 2 for b in y) ** 0.5
return num / (dx * dy) if dx * dy > 0 else 0
md = f"Correlation matrix based on {len(common)} common months.\n\n"
md += "| | " + " | ".join(ids) + " |\n"
md += "|" + "|".join(["---"] * (len(ids) + 1)) + "|\n"
for i, a in enumerate(ids):
row = [f"| **{a}** "]
x = [series[a].get(m, 0) for m in common]
for j, b in enumerate(ids):
y = [series[b].get(m, 0) for m in common]
c = _corr(x, y)
row.append(f" {c:.2f} ")
md += "|".join(row) + "|\n"
return md
def _window_coverage(backtests):
"""Window coverage summary — which strategies ran in which windows."""
windows = {}
for bt in backtests:
for run in bt.get_all_backtest_runs():
name = run.backtest_date_range_name or "—"
start = _fmt_date(run.backtest_start_date)
end = _fmt_date(run.backtest_end_date)
days = 0
if run.backtest_start_date and run.backtest_end_date:
days = (run.backtest_end_date - run.backtest_start_date).days
entry = windows.setdefault(name, {
'start': start, 'end': end, 'days': days,
'strategies': []
})
entry['strategies'].append(bt.algorithm_id)
md = "| Window | Start | End | Days | Strategies |\n"
md += "|--------|-------|-----|------|------------|\n"
for name, w in sorted(windows.items()):
md += (
f"| {name} | {w['start']} | {w['end']} | {w['days']} "
f"| {len(w['strategies'])} |\n"
)
return md
def _portfolio_snapshots(bt, window=None):
"""Portfolio snapshot summaries per window."""
runs = bt.get_all_backtest_runs()
if window:
runs = [r for r in runs if r.backtest_date_range_name == window]
md = "| Window | Initial | Final | Net Gain | Growth % |\n"
md += "|--------|---------|-------|----------|----------|\n"
for run in runs:
name = run.backtest_date_range_name or "—"
if run.portfolio_snapshots:
first = run.portfolio_snapshots[0]
last = run.portfolio_snapshots[-1]
fv = getattr(first, 'total_value', 0) or 0
lv = getattr(last, 'total_value', 0) or 0
ng = lv - fv
growth = ((lv / fv - 1) * 100) if fv else 0
md += (
f"| {name} | {fv:.2f} | {lv:.2f} "
f"| {ng:.2f} | {growth:.2f}% |\n"
)
else:
md += f"| {name} | — | — | — | — |\n"
return md
# ── Notes Storage ──
def _notes_path(directory):
"""Path to the notes JSON file in the backtest directory."""
return os.path.join(directory, ".analysis_notes.json")
def _load_notes(directory):
"""Load notes from disk. Returns dict with notes list + counters."""
path = _notes_path(directory)
if os.path.exists(path):
with open(path, "r") as f:
data = json.load(f)
return data
return {"notes": [], "noteIdCounter": 0, "snapshotIdCounter": 0}
def _save_notes(directory, data):
"""Save notes to disk."""
path = _notes_path(directory)
with open(path, "w") as f:
json.dump(data, f, indent=2)
def _filter_strategies(backtests, conditions):
"""Filter strategies by metric conditions.
conditions: list of dicts with {metric, operator, value}
operator: >, <, >=, <=, ==
"""
ops = {
">": lambda a, b: a > b,
"<": lambda a, b: a < b,
">=": lambda a, b: a >= b,
"<=": lambda a, b: a <= b,
"==": lambda a, b: abs(a - b) < 1e-9,
}
result = []
for bt in backtests:
s = bt.backtest_summary
if not s:
continue
passes = True
for cond in conditions:
metric = cond.get("metric", "")
op = cond.get("operator", ">")
val = cond.get("value", 0)
actual = getattr(s, metric, None)
if actual is None:
passes = False
break
fn = ops.get(op)
if fn is None:
passes = False
break
if not fn(actual, val):
passes = False
break
if passes:
result.append(bt)
return result
# ── MCP Protocol Implementation ──
class BacktestMCPServer:
"""Minimal MCP server using stdio transport (JSON-RPC 2.0)."""
def __init__(self, directory: Union[str, List[str]]):