-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1689 lines (1496 loc) · 76.4 KB
/
main.py
File metadata and controls
1689 lines (1496 loc) · 76.4 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
import json
from dotenv import load_dotenv
import logging
from utils import get_sgt_now
import os
import random
import sqlite3
import time
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import yaml
from utils import get_sgt_now
from ingest_prices import PriceIngestor
from ingest_news import NewsIngestor
from features import FeatureEngineer
from train import ModelManager
from positions import PositionTracker
from portfolio import PortfolioManager
from backtest_signals import build_signal_snapshot
from state_recovery import recover_positions_from_seed, enforce_position_cap, purge_seeded_open_positions
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def _get_config_path(config_path=None):
if config_path:
return config_path
base_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_dir, 'config.yaml')
def _load_config(config_path):
with open(config_path, 'r') as f:
return yaml.safe_load(f)
def _resolve_path(base_dir, path_value):
if os.path.isabs(path_value):
return path_value
return os.path.join(base_dir, path_value)
def _record_pipeline_issue(pipeline_stats, severity, source, message, max_items=20):
"""Record pipeline warnings/errors in a bounded structure that can be emailed."""
if not isinstance(pipeline_stats, dict):
return
sev = str(severity or "ERROR").strip().upper()
if sev not in {"ERROR", "WARNING"}:
sev = "ERROR"
key = "error_count" if sev == "ERROR" else "warning_count"
pipeline_stats[key] = int(pipeline_stats.get(key, 0) or 0) + 1
issues = pipeline_stats.get("issues")
if not isinstance(issues, list):
issues = []
pipeline_stats["issues"] = issues
issue = {
"time": get_sgt_now().strftime("%H:%M:%S"),
"severity": sev,
"source": str(source or "pipeline"),
"message": str(message or ""),
}
if len(issues) < int(max_items):
issues.append(issue)
else:
pipeline_stats["issue_overflow_count"] = int(pipeline_stats.get("issue_overflow_count", 0) or 0) + 1
def _finalize_pipeline_health(pipeline_stats):
if not isinstance(pipeline_stats, dict):
return
errors = int(pipeline_stats.get("error_count", 0) or 0)
warnings = int(pipeline_stats.get("warning_count", 0) or 0)
failed = int(pipeline_stats.get("tickers_failed", 0) or 0)
if failed > errors:
errors = failed
pipeline_stats["error_count"] = errors
pipeline_stats["warning_count"] = warnings
pipeline_stats["run_health"] = "ERROR" if errors > 0 else ("WARNING" if warnings > 0 else "OK")
class DailyBacktester:
def __init__(self, config_path=None):
self.config_path = _get_config_path(config_path)
self.config = _load_config(self.config_path)
self.base_dir = os.path.dirname(os.path.abspath(self.config_path))
self.db_path = _resolve_path(self.base_dir, self.config['data']['cache_path'])
self.feature_store_dir = os.path.join(self.base_dir, 'feature_store')
self.registry_path = os.path.join(self.base_dir, 'model_registry.json')
self.models_dir = os.path.join(self.base_dir, 'models')
self.results_dir = _resolve_path(
self.base_dir,
self.config.get('output', {}).get('results_dir', './results')
)
self.universe_path = _resolve_path(self.base_dir, self.config['universe']['source'])
self.core_tracker = PositionTracker(self.config_path, table_name="positions")
self.ai_tracker = PositionTracker(self.config_path, table_name="positions_ai")
self.feature_engineer = FeatureEngineer(self.config_path)
self.init_all_tables()
def init_all_tables(self):
"""Ensure all required database tables exist before any processing starts."""
from ingest_prices import PriceIngestor
from ingest_news import NewsIngestor
from positions import PositionTracker
# Initialize core tables
PriceIngestor(self.config_path).init_db()
NewsIngestor(self.config_path).init_db()
PositionTracker(self.config_path, table_name="positions")
PositionTracker(self.config_path, table_name="positions_ai")
logger.info("All database tables initialized successfully.")
def get_prediction_for_date(self, symbol, signal_date):
"""Get prediction using features as of signal_date (T-1)."""
if not os.path.exists(self.registry_path):
return None
with open(self.registry_path, 'r') as f:
registry = json.load(f)
if symbol not in registry:
return None
reg_entry = registry[symbol]
model_id = reg_entry['latest_model']
model_path = os.path.join(self.models_dir, f"{model_id}.npy")
if not os.path.exists(model_path):
return None
coeffs = np.load(model_path)
features_list = reg_entry['features']
# Compute features on-the-fly from SQLite (minimizes disk usage by avoiding feature_store CSVs).
df = self.feature_engineer.generate(symbol)
if df is None or df.empty:
return None
if "date" not in df.columns:
return None
df["date"] = pd.to_datetime(df["date"])
row = df[df["date"] == pd.to_datetime(signal_date)]
if row.empty:
return None
# Ensure all required feature columns exist.
for col in features_list:
if col not in row.columns:
return None
X = row[features_list].values[0]
X_bias = np.insert(X, 0, 1.0)
pred_return = X_bias @ coeffs
return pred_return
def get_predictions_for_date_bulk(self, symbols, signal_date, conn):
"""
Faster S&P500-scale predictor:
- Loads recent prices for all symbols in one query
- Computes technical features via groupby
- Uses per-symbol OLS coefficients from models/ and model_registry.json
"""
if not os.path.exists(self.registry_path):
return []
with open(self.registry_path, "r") as f:
registry = json.load(f) or {}
# Only symbols with an existing model are eligible.
eligible = []
for s in symbols:
sym = str(s or "").strip().upper()
if not sym:
continue
reg = registry.get(sym)
if not isinstance(reg, dict):
continue
model_id = reg.get("latest_model")
if not model_id:
continue
model_path = os.path.join(self.models_dir, f"{model_id}.npy")
if not os.path.exists(model_path):
continue
eligible.append(sym)
if not eligible:
return []
sig = pd.to_datetime(signal_date)
# Need enough history for MA50/RSI14/vol20. 80 trading days is fine.
start = (sig - timedelta(days=120)).strftime("%Y-%m-%d")
sig_str = sig.strftime("%Y-%m-%d")
# SQLite placeholder limit is fine for 503.
placeholders = ",".join(["?"] * len(eligible))
q = (
"SELECT symbol, date, open, high, low, close, volume "
"FROM prices "
f"WHERE symbol IN ({placeholders}) AND date >= ? "
"ORDER BY symbol, date"
)
df = pd.read_sql(q, conn, params=list(eligible) + [start])
if df.empty:
return []
df["date"] = pd.to_datetime(df["date"])
def _add_feats(g):
g = g.sort_values("date").reset_index(drop=True)
g["return_1d"] = g["close"].pct_change(1)
g["return_5d"] = g["close"].pct_change(5)
g["return_10d"] = g["close"].pct_change(10)
g["volatility_20d"] = g["return_1d"].rolling(20).std()
g["ma_20"] = g["close"].rolling(20).mean()
g["ma_50"] = g["close"].rolling(50).mean()
g["dist_ma_20"] = (g["close"] - g["ma_20"]) / g["ma_20"]
g["dist_ma_50"] = (g["close"] - g["ma_50"]) / g["ma_50"]
delta = g["close"].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
rs = gain / loss
g["rsi_14"] = 100 - (100 / (1 + rs))
g["volume_ma_20"] = g["volume"].rolling(20).mean()
g["volume_ratio"] = g["volume"] / g["volume_ma_20"]
# News features default to 0 if you don't ingest news for all 503 daily.
g["news_count_7d"] = 0
g["news_sentiment_7d"] = 0.0
return g
feat = df.groupby("symbol", group_keys=False).apply(_add_feats)
# Pull features for the signal_date.
feat_on_date = feat[feat["date"] == pd.to_datetime(sig_str)]
if feat_on_date.empty:
return []
feat_on_date = feat_on_date.set_index("symbol")
rankings = []
for sym in eligible:
row = feat_on_date.loc[[sym]] if sym in feat_on_date.index else None
if row is None or row.empty:
continue
reg_entry = registry.get(sym) or {}
model_id = reg_entry.get("latest_model")
features_list = reg_entry.get("features") or []
if not model_id or not features_list:
continue
try:
coeffs = np.load(os.path.join(self.models_dir, f"{model_id}.npy"))
except Exception:
continue
missing = [c for c in features_list if c not in row.columns]
if missing:
continue
try:
X = row[features_list].values[0]
X_bias = np.insert(X, 0, 1.0)
pred_return = float(X_bias @ coeffs)
except Exception:
continue
rankings.append({"symbol": sym, "predicted_return": pred_return})
return rankings
def get_fallback_rankings_for_date_bulk(self, symbols, signal_date, conn, lookback_days=120):
"""
Fallback ranking when no ML models are available.
Uses simple 10-day momentum computed from price history.
"""
sig = pd.to_datetime(signal_date)
start = (sig - timedelta(days=int(lookback_days))).strftime("%Y-%m-%d")
sig_str = sig.strftime("%Y-%m-%d")
symbols = [str(s or "").strip().upper() for s in symbols if str(s or "").strip()]
if not symbols:
return []
placeholders = ",".join(["?"] * len(symbols))
q = (
"SELECT symbol, date, close "
"FROM prices "
f"WHERE symbol IN ({placeholders}) AND date >= ? "
"ORDER BY symbol, date"
)
df = pd.read_sql(q, conn, params=list(symbols) + [start])
if df.empty:
return []
df["date"] = pd.to_datetime(df["date"])
def _add_momentum(g):
g = g.sort_values("date").reset_index(drop=True)
g["return_10d"] = g["close"].pct_change(10)
return g
feat = df.groupby("symbol", group_keys=False).apply(_add_momentum)
feat_on_date = feat[feat["date"] == pd.to_datetime(sig_str)]
if feat_on_date.empty:
return []
rankings = []
for _, row in feat_on_date.iterrows():
sym = str(row.get("symbol", "")).strip().upper()
if not sym:
continue
try:
score = float(row.get("return_10d", 0.0))
except Exception:
continue
rankings.append({"symbol": sym, "predicted_return": score})
return rankings
def run_daily_test(self, test_date=None, pipeline_stats=None, backtest_signals=None):
"""
Position-Tracking Backtest:
1. Open new positions based on signals.
2. Check existing positions for TP hits.
3. Report unrealized P&L.
"""
conn = sqlite3.connect(self.db_path)
if test_date is None:
last_date = pd.read_sql("SELECT MAX(date) as max_date FROM prices", conn).iloc[0, 0]
if not last_date:
logger.warning("No price data available for backtest.")
conn.close()
return None
test_date = pd.to_datetime(last_date)
else:
test_date = pd.to_datetime(test_date)
# signal_date is the day BEFORE test_date
signal_date = test_date - timedelta(days=1)
# Handle weekends
attempts = 0
while attempts < 5:
check = pd.read_sql(
f"SELECT COUNT(*) as cnt FROM prices WHERE date='{signal_date.strftime('%Y-%m-%d')}'",
conn
)
if check.iloc[0]['cnt'] > 0:
break
signal_date = signal_date - timedelta(days=1)
attempts += 1
logger.info(f"Running position-tracking backtest for {test_date.date()}")
logger.info(f"Using signals from {signal_date.date()} (T-1)")
# Load universe
universe_df = pd.read_csv(self.universe_path)
# Generate rankings using T-1 features
rankings = self.get_predictions_for_date_bulk(
universe_df["ticker"].tolist(),
signal_date,
conn,
)
if not rankings:
logger.warning("No ML predictions generated; falling back to momentum-based rankings.")
rankings = self.get_fallback_rankings_for_date_bulk(
universe_df["ticker"].tolist(),
signal_date,
conn,
)
if not rankings:
logger.warning("No fallback rankings generated.")
conn.close()
return None
rank_df = pd.DataFrame(rankings).sort_values('predicted_return', ascending=False)
# Apply meta-learner adjustments
from meta_learner import MetaLearner
meta = MetaLearner(self.config_path)
# IMPORTANT: refresh meta-learner state from recent closed trades.
# Without this, meta_learner_state.json can become stale and repeat the same tickers/penalties forever.
try:
ml_cfg = self.config.get("meta_learning", {}) if isinstance(self.config, dict) else {}
lookback_days = int(ml_cfg.get("lookback_days", 30))
meta.analyze_past_trades(lookback_days=lookback_days)
except Exception as exc:
logger.warning(f"Meta-learner analysis failed; continuing without updated penalties: {exc}")
rank_df = meta.get_confidence_adjustments(rank_df)
rank_df = rank_df.sort_values('adjusted_score', ascending=False).reset_index(drop=True)
rank_df['rank'] = rank_df.index + 1
rank_lookup = rank_df.set_index('symbol')[['predicted_return', 'adjusted_score', 'penalty', 'rank']]
# Capture Meta-Learner Insights
meta_insights = meta.get_daily_insights()
core_disabled_by_env = str(os.getenv("DISABLE_CORE_TRADING", "")).strip().lower() in {
"1",
"true",
"yes",
"on",
}
# Determine Current Capital (Compounding)
initial_capital = 100000
summary = self.core_tracker.get_portfolio_summary()
total_realized_dollars = summary.get('total_realized_pnl_dollars', 0.0)
total_unrealized_dollars = summary.get('total_unrealized_pnl_dollars', 0.0)
current_capital = initial_capital + total_realized_dollars
capital_start = current_capital
# Portfolio selection (top K)
open_positions_df = self.core_tracker.get_open_positions()
open_symbols = set(open_positions_df['symbol']) if not open_positions_df.empty else set()
max_positions = self.config.get('trading', {}).get('max_positions', 10)
trading_cfg = self.config.get("trading", {}) if isinstance(self.config, dict) else {}
risk_cfg = self.config.get("risk", {}) if isinstance(self.config, dict) else {}
short_threshold = float(trading_cfg.get("short_threshold", -0.0))
available_slots = max(0, max_positions - len(open_symbols))
invested_cost = 0.0
if not open_positions_df.empty:
invested_cost = (open_positions_df['entry_price'] * open_positions_df['quantity']).sum()
available_capital = max(0.0, current_capital - invested_cost)
cash_pct = (available_capital / current_capital) if current_capital else 0.0
max_cash_pct = float(trading_cfg.get("max_cash_pct", 1.0))
max_cash_pct = max(0.0, min(1.0, max_cash_pct))
min_weight = float(trading_cfg.get("min_total_weight", 0.0) or 0.0)
min_weight = max(0.0, min(1.0, min_weight))
idle_cash_caps = [float(current_capital) * max_cash_pct]
if min_weight > 0.0:
idle_cash_caps.append(float(current_capital) * max(0.0, 1.0 - min_weight))
allowed_idle_cash = min(idle_cash_caps) if idle_cash_caps else 0.0
cash_drag_excess = available_capital > 0 and cash_pct > max_cash_pct
if available_slots == 0 or available_capital <= 0:
if available_slots == 0 and cash_drag_excess:
logger.warning(
"Cash drag %.1f%% exceeds max_cash_pct %.1f%% but no slots are available (max_positions reached).",
cash_pct * 100,
max_cash_pct * 100,
)
logger.info("No available slots or capital for new positions today.")
target_portfolio = pd.DataFrame()
else:
rank_df_filtered = rank_df[~rank_df['symbol'].isin(open_symbols)]
# Also avoid recently exited names (cooldown) to prevent repeating the same tickers.
blocked = meta.get_exit_cooldown_symbols(as_of_date=signal_date)
if blocked:
rank_df_filtered = rank_df_filtered[~rank_df_filtered['symbol'].isin(blocked)]
portfolio_mgr = PortfolioManager(self.config_path)
enable_shorts = bool(self.config.get("trading", {}).get("enable_shorts", False))
max_shorts = int(self.config.get("trading", {}).get("max_shorts", 0))
long_df = rank_df_filtered[rank_df_filtered["adjusted_score"] > 0].copy()
short_df = pd.DataFrame()
if enable_shorts and max_shorts > 0:
short_df = rank_df_filtered[rank_df_filtered["adjusted_score"] <= short_threshold].copy()
# Cash-drag fallback: if no signals and cash is too high, relax filters.
if cash_drag_excess and long_df.empty and short_df.empty:
logger.warning(
"Cash drag %.1f%% exceeds max_cash_pct %.1f%%; relaxing signal filters to deploy capital.",
cash_pct * 100,
max_cash_pct * 100,
)
long_df = rank_df_filtered.copy()
if enable_shorts and max_shorts > 0:
short_df = rank_df_filtered[rank_df_filtered["adjusted_score"] < 0].copy()
if not short_df.empty:
long_df = long_df[~long_df["symbol"].isin(short_df["symbol"])]
# Allocate slots between longs and shorts (shorts capped).
shorts_slots = min(max_shorts, available_slots)
long_slots = max(0, available_slots - shorts_slots)
target_portfolio = portfolio_mgr.generate_target_portfolio(long_df, max_positions=long_slots)
if not short_df.empty and shorts_slots > 0:
# Take the most negative adjusted scores (strongest short signals)
short_df = short_df.sort_values("adjusted_score", ascending=True).head(shorts_slots).copy()
# Size shorts using absolute adjusted score
if portfolio_mgr.equal_weight:
short_df["weight"] = 1.0 / len(short_df)
else:
scores = (-short_df["adjusted_score"]).clip(lower=0)
total = scores.sum()
short_df["weight"] = (scores / total) if total else (1.0 / len(short_df))
short_df["side"] = "SHORT"
if target_portfolio is None or target_portfolio.empty:
target_portfolio = short_df
else:
target_portfolio = pd.concat([target_portfolio, short_df], ignore_index=True)
# Guardrail: combined long+short weights must never exceed 100% total capital.
if target_portfolio is not None and not target_portfolio.empty:
target_portfolio["weight"] = pd.to_numeric(
target_portfolio["weight"], errors="coerce"
).fillna(0.0).clip(lower=0.0)
total_weight = float(target_portfolio["weight"].sum() or 0.0)
if total_weight > 1.0:
target_portfolio["weight"] = target_portfolio["weight"] / total_weight
# Guardrail: enforce minimum total weight to avoid leaving too much cash idle
if min_weight > 0 and 0 < total_weight < min_weight:
target_portfolio["weight"] = target_portfolio["weight"] * (min_weight / total_weight)
logger.info(f"Adjusted weights from {total_weight:.2%} to {min_weight:.2%} to deploy more capital")
# Open NEW positions for selected stocks
tp_pct = self.config.get('trading', {}).get('take_profit_pct', 0.03)
new_positions = []
top_up_positions = []
remaining_capital = float(available_capital)
for _, row in target_portfolio.iterrows():
symbol = row['symbol']
raw_side = row.get("side", None)
if raw_side is None or (isinstance(raw_side, float) and pd.isna(raw_side)):
side = "LONG"
else:
side = str(raw_side).strip().upper() or "LONG"
if side not in {"LONG", "SHORT"}:
side = "LONG"
# Get entry price (Day T Open)
price_data = pd.read_sql(
f"SELECT * FROM prices WHERE symbol='{symbol}' AND date='{test_date.strftime('%Y-%m-%d')}'",
conn
)
if not price_data.empty:
entry_price = price_data.iloc[0]['open']
requested_allocation = max(
0.0, float(row.get('weight', 0.0) or 0.0) * float(available_capital)
)
allocation_dollars = min(requested_allocation, max(0.0, remaining_capital))
if allocation_dollars <= 0.0:
continue
quantity = allocation_dollars / entry_price
allocation_pct = (allocation_dollars / current_capital * 100) if current_capital else 0.0
pos_id = self.core_tracker.open_position(
symbol=symbol,
entry_date=test_date.strftime('%Y-%m-%d'),
entry_price=entry_price,
quantity=quantity,
side=side
)
if pos_id:
reason = "Top-ranked model signal"
if symbol in rank_lookup.index:
info = rank_lookup.loc[symbol]
pred = float(info['predicted_return'])
adj = float(info['adjusted_score'])
penalty = float(info['penalty'])
rank = int(info['rank'])
reason = (
f"Rank {rank} signal (pred {pred:.2%}, adj {adj:.2%}, penalty {penalty:.2f})"
)
new_positions.append({
'symbol': symbol,
'side': side,
'entry_price': entry_price,
'target_price': entry_price * (1 + tp_pct) if side == "LONG" else entry_price * (1 - tp_pct),
'quantity': quantity,
'allocation_pct': allocation_pct,
'allocation_dollars': allocation_dollars,
'reason': reason
})
remaining_capital = max(0.0, remaining_capital - allocation_dollars)
# If older under-sized positions are occupying slots, scale into the best-held names
# before leaving excess cash idle.
extra_to_deploy = max(0.0, float(remaining_capital) - float(allowed_idle_cash))
max_position_equity_pct = float(risk_cfg.get("max_position_equity_pct", 1.0) or 1.0)
max_position_equity_pct = max(0.0, min(1.0, max_position_equity_pct))
if extra_to_deploy > 0.0 and max_position_equity_pct > 0.0:
open_positions_for_top_up = self.core_tracker.get_open_positions()
if open_positions_for_top_up is not None and not open_positions_for_top_up.empty:
top_up_df = open_positions_for_top_up.copy()
top_up_df["symbol"] = top_up_df["symbol"].astype(str).str.strip().str.upper()
top_up_df["side"] = top_up_df["side"].fillna("LONG").astype(str).str.upper()
top_up_df["entry_price"] = pd.to_numeric(top_up_df["entry_price"], errors="coerce").fillna(0.0)
top_up_df["quantity"] = pd.to_numeric(top_up_df["quantity"], errors="coerce").fillna(0.0)
top_up_df["notional"] = top_up_df["entry_price"] * top_up_df["quantity"]
top_up_df["adjusted_score"] = top_up_df["symbol"].map(
lambda sym: float(rank_lookup.loc[sym]["adjusted_score"]) if sym in rank_lookup.index else 0.0
)
top_up_df["rank_priority"] = top_up_df["adjusted_score"].abs()
supported_mask = (
((top_up_df["side"] == "LONG") & (top_up_df["adjusted_score"] > 0))
| ((top_up_df["side"] == "SHORT") & (top_up_df["adjusted_score"] <= short_threshold))
)
top_up_candidates = top_up_df[supported_mask].copy()
if top_up_candidates.empty:
top_up_candidates = top_up_df.copy()
top_up_candidates = top_up_candidates.sort_values(
["rank_priority", "adjusted_score"],
ascending=[False, False],
)
max_position_notional = float(current_capital) * max_position_equity_pct
logger.warning(
"Core cash drag remains %.2f with idle-cash cap %.2f; topping up existing positions.",
float(remaining_capital),
float(allowed_idle_cash),
)
for _, pos in top_up_candidates.iterrows():
if extra_to_deploy <= 0.0:
break
current_notional = float(pos.get("notional", 0.0) or 0.0)
room = max(0.0, max_position_notional - current_notional)
if room <= 0.0:
continue
symbol = str(pos["symbol"]).strip().upper()
side = str(pos.get("side") or "LONG").upper()
price_data = pd.read_sql(
"SELECT open FROM prices WHERE symbol=? AND date=?",
conn,
params=(symbol, test_date.strftime("%Y-%m-%d")),
)
if price_data.empty:
continue
entry_price = float(price_data.iloc[0]["open"] or 0.0)
if entry_price <= 0.0:
continue
allocation_dollars = min(extra_to_deploy, room)
quantity = allocation_dollars / entry_price if entry_price else 0.0
if quantity <= 0.0:
continue
added = self.core_tracker.add_to_position(
symbol=symbol,
add_date=test_date.strftime("%Y-%m-%d"),
add_price=entry_price,
quantity=quantity,
side=side,
)
if not added:
continue
reason = "Cash-drag top-up of existing position"
if symbol in rank_lookup.index:
info = rank_lookup.loc[symbol]
reason = (
f"Cash-drag top-up (pred {float(info['predicted_return']):.2%}, "
f"adj {float(info['adjusted_score']):.2%}, rank {int(info['rank'])})"
)
top_up_positions.append({
"symbol": symbol,
"side": side,
"entry_price": entry_price,
"target_price": added["target_price"],
"quantity": quantity,
"allocation_pct": (allocation_dollars / current_capital * 100) if current_capital else 0.0,
"allocation_dollars": allocation_dollars,
"reason": reason,
})
remaining_capital = max(0.0, remaining_capital - allocation_dollars)
extra_to_deploy = max(0.0, extra_to_deploy - allocation_dollars)
if extra_to_deploy > 0.0:
logger.warning(
"Core cash drag persists after top-ups; %.2f cash still exceeds the idle-cash cap.",
extra_to_deploy,
)
entries_today = list(new_positions) + list(top_up_positions)
# Keep Core + AI strategies distinct by optionally preventing overlap.
core_reserved_symbols = set(open_symbols)
if target_portfolio is not None and hasattr(target_portfolio, "empty") and not target_portfolio.empty:
try:
core_reserved_symbols |= set([str(s).strip().upper() for s in target_portfolio["symbol"].tolist() if str(s).strip()])
except Exception:
pass
conn.close()
os.makedirs(self.results_dir, exist_ok=True)
date_str = test_date.strftime('%Y%m%d')
report = None
unrealized = pd.DataFrame()
closed_positions = []
if core_disabled_by_env:
logger.info("Core trading disabled by env; skipping core strategy path.")
else:
# Check ALL open positions for TP hits on this day
closed_positions = self.core_tracker.check_and_close_positions(
check_date=test_date.strftime('%Y-%m-%d')
)
# Save closed trades for meta-learning (per-day)
if closed_positions:
trades_df = pd.DataFrame(closed_positions)
trades_df = trades_df.rename(columns={
"realized_pnl": "strat_return",
"realized_pnl_dollars": "pnl_dollars",
})
trades_df.to_csv(
os.path.join(self.results_dir, f"trades_{date_str}.csv"),
index=False
)
# Get updated portfolio state
summary = self.core_tracker.get_portfolio_summary()
unrealized = self.core_tracker.get_unrealized_pnl()
total_realized_dollars = summary.get('total_realized_pnl_dollars', 0.0)
total_unrealized_dollars = summary.get('total_unrealized_pnl_dollars', 0.0)
# Calculate Realized P&L for TODAY
realized_today_dollars = sum([p.get('realized_pnl_dollars', 0.0) for p in closed_positions])
realized_today = (realized_today_dollars / capital_start) if capital_start else 0.0
total_realized_pct = (total_realized_dollars / initial_capital) if initial_capital else 0.0
total_unrealized_pct = (total_unrealized_dollars / initial_capital) if initial_capital else 0.0
total_account_return = ((total_realized_dollars + total_unrealized_dollars) / initial_capital) if initial_capital else 0.0
current_capital = initial_capital + total_realized_dollars
# Available cash (notional-based; shorts consume capital too)
open_positions_now = self.core_tracker.get_open_positions()
invested_notional = 0.0
if not open_positions_now.empty:
invested_notional = float((open_positions_now["entry_price"] * open_positions_now["quantity"]).sum() or 0.0)
available_cash = float(current_capital) - invested_notional
report = {
'date': test_date.date(),
'new_positions_opened': len(new_positions),
'positions_topped_up': len(top_up_positions),
'positions_closed_at_tp': len(closed_positions),
'open_positions': summary['open_positions'],
'realized_pnl_today': realized_today,
'realized_pnl_today_dollars': realized_today_dollars,
'total_realized_pnl': total_realized_pct,
'total_realized_pnl_dollars': total_realized_dollars,
'total_unrealized_pnl': total_unrealized_pct,
'total_unrealized_pnl_dollars': total_unrealized_dollars,
'total_account_return': total_account_return,
'current_capital_estimate': current_capital,
'invested_notional': invested_notional,
'available_cash': available_cash,
'initial_capital': initial_capital
}
pd.DataFrame([report]).to_csv(
os.path.join(self.results_dir, f"daily_report_{date_str}.csv"),
index=False
)
if not unrealized.empty:
unrealized.to_csv(
os.path.join(self.results_dir, f"unrealized_{date_str}.csv"),
index=False
)
logger.info(f"Daily report saved to {self.results_dir}")
# --- AI strategy (separate $100k account) ---
from llm_trader import propose_trades_with_llm
ai_cfg = self.config.get("ai_trading", {})
ai_enabled = bool(ai_cfg.get("enabled", False))
ai_disabled_by_env = str(os.getenv("DISABLE_AI_TRADING", "")).strip().lower() in {
"1",
"true",
"yes",
"on",
}
if ai_disabled_by_env:
ai_enabled = False
ai_report = None
ai_unrealized = pd.DataFrame()
ai_closed = []
ai_new = []
ai_llm_status = {"enabled": False, "ok": False, "error": "disabled"}
if ai_disabled_by_env:
ai_llm_status = {"enabled": False, "ok": True, "error": "disabled_by_env"}
if ai_enabled:
ai_initial_capital = float(ai_cfg.get("initial_capital", 100000))
# Capture pre-close capital for reporting, then close TP positions before
# deciding new AI entries so freed slots/cash are usable in the same run.
ai_summary_pre_close = self.ai_tracker.get_portfolio_summary()
ai_realized_pre_close = float(ai_summary_pre_close.get("total_realized_pnl_dollars", 0.0))
ai_capital_pre_close = ai_initial_capital + ai_realized_pre_close
ai_closed = self.ai_tracker.check_and_close_positions(check_date=test_date.strftime('%Y-%m-%d'))
ai_summary0 = self.ai_tracker.get_portfolio_summary()
ai_realized_total_dollars0 = float(ai_summary0.get("total_realized_pnl_dollars", 0.0))
ai_current_capital0 = ai_initial_capital + ai_realized_total_dollars0
ai_open_df = self.ai_tracker.get_open_positions()
ai_open_symbols = set(ai_open_df["symbol"]) if not ai_open_df.empty else set()
ai_invested_cost = (ai_open_df["entry_price"] * ai_open_df["quantity"]).sum() if not ai_open_df.empty else 0.0
ai_available_capital = max(0.0, ai_current_capital0 - ai_invested_cost)
ai_max_positions = int(ai_cfg.get("max_positions", 10))
ai_allow_shorts = bool(ai_cfg.get("allow_shorts", True))
ai_max_shorts = int(ai_cfg.get("max_shorts", 5))
ai_available_slots = max(0, ai_max_positions - len(ai_open_symbols))
# AI strategy uses the trained model only. Core rankings remain untouched.
def _pyfloat(value):
try:
if pd.isna(value):
return None
return float(value)
except Exception:
return None
def _recent_price_metrics(conn_, sym_, lookback=30):
dfp = pd.read_sql(
"SELECT date, close, volume FROM prices WHERE symbol=? ORDER BY date DESC LIMIT ?",
conn_,
params=(sym_, int(lookback)),
)
if dfp.empty or len(dfp) < 2:
return None
dfp = dfp.sort_values("date").reset_index(drop=True)
closes = dfp["close"].astype(float).tolist()
tail_n = min(10, len(closes))
closes_tail = [float(x) for x in closes[-tail_n:]]
v20 = float(dfp["volume"].astype(float).tail(20).mean()) if "volume" in dfp.columns else None
v1 = float(dfp["volume"].astype(float).iloc[-1]) if "volume" in dfp.columns else None
return {
"last_date": str(dfp["date"].iloc[-1]),
"last_close": float(closes_tail[-1]),
"closes_tail": closes_tail,
"volume_1d": v1,
"volume_20d_avg": v20,
}
def _latest_feature_snapshot(conn_, sym_, lookback=80, news_window_days=7):
dfp = pd.read_sql(
"SELECT date, close, volume FROM prices WHERE symbol=? ORDER BY date DESC LIMIT ?",
conn_,
params=(sym_, int(lookback)),
)
if dfp.empty or len(dfp) < 20:
return {
"return_1d": None,
"return_5d": None,
"return_10d": None,
"volatility_20d": None,
"dist_ma_20": None,
"dist_ma_50": None,
"rsi_14": None,
"volume_ratio": None,
"news_count_7d": 0,
"news_sentiment_7d": 0.0,
}
dfp = dfp.sort_values("date").reset_index(drop=True).copy()
dfp["close"] = pd.to_numeric(dfp["close"], errors="coerce")
dfp["volume"] = pd.to_numeric(dfp["volume"], errors="coerce")
dfp["return_1d"] = dfp["close"].pct_change(1)
dfp["return_5d"] = dfp["close"].pct_change(5)
dfp["return_10d"] = dfp["close"].pct_change(10)
dfp["volatility_20d"] = dfp["return_1d"].rolling(20).std()
dfp["ma_20"] = dfp["close"].rolling(20).mean()
dfp["ma_50"] = dfp["close"].rolling(50).mean()
dfp["dist_ma_20"] = (dfp["close"] - dfp["ma_20"]) / dfp["ma_20"]
dfp["dist_ma_50"] = (dfp["close"] - dfp["ma_50"]) / dfp["ma_50"]
delta = dfp["close"].diff()
gain = delta.where(delta > 0, 0.0).rolling(window=14).mean()
loss = (-delta.where(delta < 0, 0.0)).rolling(window=14).mean()
rs = gain / loss.replace(0, pd.NA)
dfp["rsi_14"] = 100 - (100 / (1 + rs))
dfp["volume_ma_20"] = dfp["volume"].rolling(20).mean()
dfp["volume_ratio"] = dfp["volume"] / dfp["volume_ma_20"]
latest = dfp.iloc[-1]
end_dt = pd.to_datetime(latest["date"])
news_count_7d = 0
news_sentiment_7d = 0.0
try:
news_df = pd.read_sql(
"SELECT datetime, sentiment_score FROM news WHERE symbol=? ORDER BY datetime DESC LIMIT 250",
conn_,
params=(sym_,),
)
if not news_df.empty and "datetime" in news_df.columns:
news_df["datetime"] = pd.to_datetime(news_df["datetime"], errors="coerce")
news_df = news_df.dropna(subset=["datetime"])
if not news_df.empty:
start_dt = end_dt - pd.Timedelta(days=int(news_window_days or 7))
news_df = news_df[news_df["datetime"] >= start_dt]
news_count_7d = int(len(news_df))
if "sentiment_score" in news_df.columns:
sentiment = pd.to_numeric(news_df["sentiment_score"], errors="coerce").dropna()
if not sentiment.empty:
news_sentiment_7d = float(sentiment.mean())
except Exception:
news_count_7d = 0
news_sentiment_7d = 0.0
return {
"return_1d": _pyfloat(latest.get("return_1d")),
"return_5d": _pyfloat(latest.get("return_5d")),
"return_10d": _pyfloat(latest.get("return_10d")),
"volatility_20d": _pyfloat(latest.get("volatility_20d")),
"dist_ma_20": _pyfloat(latest.get("dist_ma_20")),
"dist_ma_50": _pyfloat(latest.get("dist_ma_50")),
"rsi_14": _pyfloat(latest.get("rsi_14")),
"volume_ratio": _pyfloat(latest.get("volume_ratio")),
"news_count_7d": int(news_count_7d),
"news_sentiment_7d": float(news_sentiment_7d),
}
universe_symbols = [str(t).strip().upper() for t in universe_df["ticker"].tolist() if str(t).strip()]
universe_symbols = [s for s in universe_symbols if s not in ai_open_symbols]
disallow_overlap = bool(ai_cfg.get("disallow_core_overlap", True))
blocked_by_core = 0
if disallow_overlap and core_reserved_symbols:
before = len(universe_symbols)
universe_symbols = [s for s in universe_symbols if s not in core_reserved_symbols]
blocked_by_core = before - len(universe_symbols)
conn_ai = sqlite3.connect(self.db_path)
cand = []
try:
seed = f"{pd.to_datetime(signal_date).date().isoformat()}-ai"
rng = random.Random(seed)
rng.shuffle(universe_symbols)
prompt_limit_cfg = int(ai_cfg.get("prompt_candidates_limit", 200) or 200)
prompt_limit_env_raw = str(os.getenv("AI_PROMPT_CANDIDATES_LIMIT") or "").strip()
if prompt_limit_env_raw:
try:
prompt_limit = int(float(prompt_limit_env_raw))
except Exception:
prompt_limit = prompt_limit_cfg
else:
prompt_limit = prompt_limit_cfg
prompt_limit = max(1, prompt_limit)
price_lookback = int(ai_cfg.get("price_lookback_days", 30) or 30)
feature_lookback = int(ai_cfg.get("feature_lookback_days", 80) or 80)
news_window_days = int(ai_cfg.get("news_window_days", 7) or 7)
for sym in universe_symbols:
if len(cand) >= max(1, prompt_limit):
break
snapshot = _recent_price_metrics(conn_ai, sym, lookback=price_lookback)
if not snapshot:
continue
snapshot.update(
_latest_feature_snapshot(
conn_ai,
sym,
lookback=feature_lookback,
news_window_days=news_window_days,
)
)
snapshot["symbol"] = sym
snapshot["as_of_date"] = str(pd.to_datetime(signal_date).date())
cand.append(snapshot)
finally:
conn_ai.close()
if ai_available_capital <= 0.0 or ai_available_slots <= 0:
ai_trades = []
ai_llm_status = {
"enabled": True,
"ok": True,
"skipped_reason": "no_capacity",
"error": None,
"model": ((ai_cfg.get("trained_model") or {}).get("base_model") or (ai_cfg.get("trained_model") or {}).get("inference_url")),
"model_used": None,
"disallow_core_overlap": disallow_overlap,
"blocked_by_core": blocked_by_core,
"candidates_built": len(cand),
"available_capital": float(ai_available_capital),
"available_slots": int(ai_available_slots),
}
else:
ai_trades, ai_llm_status = propose_trades_with_llm(
self.config,
cand,
max_positions=ai_available_slots,
allow_shorts=ai_allow_shorts,
max_shorts=ai_max_shorts,
)
if isinstance(ai_llm_status, dict):