Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
2822 lines (2539 loc) · 140 KB
/
Copy pathmain.py
File metadata and controls
2822 lines (2539 loc) · 140 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 os
import json
from dotenv import load_dotenv
load_dotenv(dotenv_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env"))
import logging
from utils import get_sgt_now
import random
import sqlite3
import time
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import yaml
from ingest_prices import PriceIngestor
from ingest_news import NewsIngestor
from positions import PositionTracker
from portfolio import PortfolioManager
from state_recovery import recover_positions_from_seed, enforce_position_cap, purge_seeded_open_positions
from broker import AlpacaBroker, AlpacaError, create_broker_from_env
# 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:
payload = yaml.safe_load(f) or {}
if isinstance(payload, dict):
payload.setdefault("_config_path", os.path.abspath(config_path))
payload.setdefault("_config_base_dir", os.path.dirname(os.path.abspath(config_path)))
return payload
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 _get_open_position_symbols(config_path, table_names=None):
"""Return distinct OPEN symbols across the requested position tables."""
config = _load_config(config_path)
if table_names is None:
ai_cfg = config.get("ai_trading", {}) if isinstance(config, dict) else {}
ai_disabled_by_env = str(os.getenv("DISABLE_AI_TRADING", "")).strip().lower() in {"1", "true", "yes", "on"}
ai_enabled = bool(ai_cfg.get("enabled", False)) and not ai_disabled_by_env
core_disabled_by_env = str(os.getenv("DISABLE_CORE_TRADING", "")).strip().lower() in {"1", "true", "yes", "on"}
table_names = []
if not core_disabled_by_env:
table_names.append("positions")
if ai_enabled:
table_names.append("positions_ai")
if not table_names:
table_names = ["positions"]
base_dir = os.path.dirname(os.path.abspath(config_path))
db_path = _resolve_path(base_dir, config["data"]["cache_path"])
ordered = []
seen = set()
conn = sqlite3.connect(db_path)
try:
for table_name in table_names:
safe_name = str(table_name or "").strip()
if safe_name not in {"positions", "positions_ai"}:
continue
try:
rows = conn.execute(
f"SELECT DISTINCT symbol FROM {safe_name} WHERE status='OPEN'"
).fetchall()
except sqlite3.OperationalError:
rows = []
for row in rows:
symbol = str((row[0] if row else "") or "").strip().upper()
if not symbol or symbol in seen:
continue
seen.add(symbol)
ordered.append(symbol)
finally:
conn.close()
return ordered
def _position_cash_metrics(positions_df, current_capital):
"""Return gross exposure and cash available for open positions.
Long positions consume cash at their current mark (or entry mark when no
current mark is available). Short positions are included in gross notional
exposure but do not reduce cash in this simple daily-report view.
"""
try:
capital = float(current_capital or 0.0)
except (TypeError, ValueError):
capital = 0.0
if positions_df is None or not hasattr(positions_df, "empty") or positions_df.empty:
return 0.0, max(0.0, capital)
gross_notional = 0.0
long_notional = 0.0
for _, row in positions_df.iterrows():
try:
quantity = abs(float(row.get("quantity", 0.0) or 0.0))
mark = row.get("current_price")
if mark is None or str(mark) == "nan":
mark = row.get("entry_price")
mark = float(mark or 0.0)
except (TypeError, ValueError):
continue
if quantity <= 0.0 or mark <= 0.0:
continue
notional = quantity * mark
gross_notional += notional
side = str(row.get("side", "LONG") or "LONG").strip().upper()
if side != "SHORT":
long_notional += notional
return gross_notional, max(0.0, capital - long_notional)
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")
# Initialize broker if Alpaca mode is enabled
self.broker_mode = os.environ.get("ARM_LIVE_TRADING", "simulation").lower()
self.core_broker = None
self.ai_broker = None
if self.broker_mode == "alpaca":
disable_core = str(os.environ.get("DISABLE_CORE_TRADING", "0")).strip() in {"1", "true", "yes"}
disable_ai = str(os.environ.get("DISABLE_AI_TRADING", "0")).strip() in {"1", "true", "yes"}
if not disable_core:
try:
self.core_broker = create_broker_from_env("core")
account = self.core_broker.validate_connection()
logger.info(
"Alpaca Core connected: equity=$%.2f, cash=$%.2f, buying_power=$%.2f",
account["equity"],
account["cash"],
account["buying_power"],
)
except Exception as e:
logger.error("Failed to connect Alpaca Core broker: %s", e)
raise RuntimeError(f"Alpaca Core broker connection failed in alpaca live trading mode: {e}")
if not disable_ai:
try:
self.ai_broker = create_broker_from_env("ai")
account = self.ai_broker.validate_connection()
logger.info(
"Alpaca AI connected: equity=$%.2f, cash=$%.2f, buying_power=$%.2f",
account["equity"],
account["cash"],
account["buying_power"],
)
except Exception as e:
logger.error("Failed to connect Alpaca AI broker: %s", e)
raise RuntimeError(f"Alpaca AI broker connection failed in alpaca live trading mode: {e}")
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 _sync_sqlite_positions_with_alpaca(self, tracker, broker, trade_date_str):
"""Synchronize the local SQLite positions table with the broker's actual open positions."""
if not broker:
return
try:
logger.info("Synchronizing SQLite table %s with Alpaca actual positions...", tracker.table_name)
alpaca_positions = broker.get_positions()
# Create mapping of symbol -> position dict from Alpaca
alpaca_map = {}
for p in alpaca_positions:
sym = str(p.get('symbol') or '').strip().upper()
if sym:
alpaca_map[sym] = p
# Fetch open positions from SQLite
with sqlite3.connect(tracker.db_path) as conn:
cursor = conn.cursor()
sqlite_open = cursor.execute(
f"SELECT id, symbol, entry_price, quantity, side FROM {tracker.table_name} WHERE status='OPEN'"
).fetchall()
sqlite_map = {row[1]: {'id': row[0], 'entry_price': row[2], 'quantity': row[3], 'side': row[4]} for row in sqlite_open}
# 1. Close positions in SQLite that do not exist on Alpaca
for sym, sql_pos in sqlite_map.items():
if sym not in alpaca_map:
logger.warning("Position %s is OPEN in SQLite but does not exist on Alpaca. Closing in SQLite at entry price.", sym)
# Close in SQLite at entry price to avoid phantom P&L
cursor.execute(
f"UPDATE {tracker.table_name} SET status='CLOSED', exit_date=?, exit_price=?, realized_pnl=0.0, exit_reason='alpaca_sync_close' WHERE id=?",
(trade_date_str, sql_pos['entry_price'], sql_pos['id'])
)
# 2. Add or update positions in SQLite to match Alpaca
for sym, alp_pos in alpaca_map.items():
alp_qty = float(int(abs(float(alp_pos.get('qty', 0.0)))))
alp_side = str(alp_pos.get('side') or 'LONG').upper()
alp_entry_price = float(alp_pos.get('avg_entry_price', 0.0) or alp_pos.get('price', 0.0))
if alp_qty <= 0.0:
continue
if sym in sqlite_map:
sql_pos = sqlite_map[sym]
# If quantity, side, or entry price differs significantly, update SQLite to match Alpaca
if abs(sql_pos['quantity'] - alp_qty) > 1e-5 or sql_pos['side'] != alp_side or abs(sql_pos['entry_price'] - alp_entry_price) > 0.01:
logger.info("Syncing existing position %s in SQLite: qty=%s -> %s, side=%s -> %s, entry=%s -> %s",
sym, sql_pos['quantity'], alp_qty, sql_pos['side'], alp_side, sql_pos['entry_price'], alp_entry_price)
cursor.execute(
f"UPDATE {tracker.table_name} SET quantity=?, side=?, entry_price=? WHERE id=?",
(alp_qty, alp_side, alp_entry_price, sql_pos['id'])
)
else:
logger.info("Position %s exists on Alpaca but not in SQLite. Opening in SQLite: qty=%s, side=%s, entry=%s",
sym, alp_qty, alp_side, alp_entry_price)
# Compute target price
tp_pct = float(tracker.config.get('trading', {}).get('take_profit_pct', 0.03))
if alp_side == 'SHORT':
target_price = alp_entry_price * (1.0 - tp_pct)
else:
target_price = alp_entry_price * (1.0 + tp_pct)
cursor.execute(
f"""
INSERT INTO {tracker.table_name} (
symbol, side, entry_date, entry_price, quantity, target_price, status, exit_reason
)
VALUES (?, ?, ?, ?, ?, ?, 'OPEN', 'alpaca_sync_open')
""",
(sym, alp_side, trade_date_str, alp_entry_price, alp_qty, target_price)
)
logger.info("Synchronization of SQLite table %s complete.", tracker.table_name)
except Exception as sync_exc:
logger.error("Error synchronizing SQLite positions with Alpaca: %s", sync_exc, exc_info=True)
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 compute_smc_signals_bulk(self, symbols, signal_date, conn, pivots_length=5):
"""
Compute LuxAlgo SMC signals in bulk for a list of symbols on a given signal_date.
"""
sig_date_str = pd.to_datetime(signal_date).strftime("%Y-%m-%d")
start_date = (pd.to_datetime(signal_date) - timedelta(days=120)).strftime("%Y-%m-%d")
symbols = [str(s).strip().upper() for s in symbols if str(s).strip()]
if not symbols:
return pd.DataFrame()
placeholders = ",".join(["?"] * len(symbols))
q = f"""
SELECT symbol, date, open, high, low, close
FROM prices
WHERE symbol IN ({placeholders}) AND date <= ? AND date >= ?
ORDER BY symbol, date ASC
"""
df = pd.read_sql(q, conn, params=list(symbols) + [sig_date_str, start_date])
if df.empty:
return pd.DataFrame()
df["date"] = pd.to_datetime(df["date"])
L = pivots_length
sig_rows = []
for symbol, group in df.groupby("symbol"):
group = group.sort_values("date").reset_index(drop=True)
if len(group) < 2 * L + 1:
continue
# Vectorized rolling pivots
group['is_pivot_high'] = (
(group['high'] >= group['high'].shift(1).rolling(L).max()) &
(group['high'] > group['high'].shift(-L).rolling(L).max())
)
group['is_pivot_low'] = (
(group['low'] <= group['low'].shift(1).rolling(L).min()) &
(group['low'] < group['low'].shift(-L).rolling(L).min())
)
# Chronological state loop
trend_bias = "NEUTRAL"
active_high_pivot = None
active_low_pivot = None
biases = []
signals = []
for i in range(len(group)):
pivot_check_idx = i - L
if pivot_check_idx >= 0:
if group.loc[pivot_check_idx, 'is_pivot_high']:
active_high_pivot = group.loc[pivot_check_idx, 'high']
if group.loc[pivot_check_idx, 'is_pivot_low']:
active_low_pivot = group.loc[pivot_check_idx, 'low']
close_t = group.loc[i, 'close']
signal = "NONE"
if trend_bias == "BEARISH":
if active_high_pivot is not None and close_t > active_high_pivot:
trend_bias = "BULLISH"
signal = "BULLISH_CHOCH"
elif trend_bias == "BULLISH":
if active_low_pivot is not None and close_t < active_low_pivot:
trend_bias = "BEARISH"
signal = "BEARISH_CHOCH"
elif trend_bias == "NEUTRAL":
if active_high_pivot is not None and close_t > active_high_pivot:
trend_bias = "BULLISH"
signal = "BULLISH_CHOCH"
elif active_low_pivot is not None and close_t < active_low_pivot:
trend_bias = "BEARISH"
signal = "BEARISH_CHOCH"
biases.append(trend_bias)
signals.append(signal)
group['trend_bias'] = biases
group['smc_signal'] = signals
group['return_10d'] = group['close'].pct_change(10)
if group.iloc[-1]['date'].strftime("%Y-%m-%d") == sig_date_str:
sig_rows.append(group.iloc[-1])
return pd.DataFrame(sig_rows) if sig_rows else pd.DataFrame()
def run_daily_test(self, test_date=None, pipeline_stats=None, backtest_signals=None):
"""
Position-Tracking Backtest with SMC Strategy:
1. Sync SQLite positions with Alpaca.
2. Open new positions based on SMC CHOCH close-above-level signals.
3. Check existing positions for 3% TP hits.
4. Report unrealized P&L.
"""
conn = sqlite3.connect(self.db_path)
rank_df = pd.DataFrame()
core_rank_df = pd.DataFrame()
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/holidays to find the last available date in prices
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)")
trade_date_str = test_date.strftime('%Y-%m-%d')
# Synchronize SQLite positions with Alpaca before doing any capital/portfolio checks
if self.core_broker and not (str(os.getenv("DISABLE_CORE_TRADING", "")).strip().lower() in {"1", "true", "yes", "on"}):
self._sync_sqlite_positions_with_alpaca(self.core_tracker, self.core_broker, trade_date_str)
# Load universe
universe_df = pd.read_csv(self.universe_path)
# Always load the fallback momentum rankings into rank_df so that it contains the full momentum rankings
rankings = self.get_fallback_rankings_for_date_bulk(
universe_df["ticker"].tolist(),
signal_date,
conn,
)
if rankings:
rank_df = pd.DataFrame(rankings)
rank_df["rank"] = rank_df["predicted_return"].rank(ascending=False, method="first").astype(int)
rank_df = rank_df.sort_values("rank").reset_index(drop=True)
rank_df["penalty"] = 1.0
rank_df["adjusted_score"] = rank_df["predicted_return"]
ai_cfg = self.config.get("ai_trading", {})
trading_cfg = self.config.get("trading", {})
ai_disabled_by_env = str(os.getenv("DISABLE_AI_TRADING", "")).strip().lower() in {
"1",
"true",
"yes",
"on",
}
ai_enabled = bool(ai_cfg.get("enabled", False)) and not ai_disabled_by_env
core_disabled_by_env = str(os.getenv("DISABLE_CORE_TRADING", "")).strip().lower() in {
"1",
"true",
"yes",
"on",
}
# Determine Current Capital (Compounding)
initial_capital = float(self.config.get('trading', {}).get('initial_capital', 100000))
leverage = float(self.config.get('trading', {}).get('leverage', 2))
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 + total_unrealized_dollars
capital_start = current_capital
# Override current_capital with Alpaca equity when broker is connected
if self.core_broker:
try:
alpaca_acct = self.core_broker.get_account()
alpaca_equity = float(alpaca_acct.get('equity', current_capital))
current_capital = alpaca_equity
capital_start = current_capital
logger.info("Position sizing: Alpaca equity=$%.2f", alpaca_equity)
except Exception as e:
logger.warning("Could not pull Alpaca equity for sizing, using SQLite: %s", e)
# Get updated open positions and slots
open_positions_df = self.core_tracker.get_open_positions()
open_symbols = set(open_positions_df['symbol']) if not open_positions_df.empty else set()
open_shorts_count = len(open_positions_df[open_positions_df['side'] == 'SHORT']) if not open_positions_df.empty else 0
max_positions = self.config.get('trading', {}).get('max_positions', 10)
max_shorts = self.config.get('trading', {}).get('max_shorts', 5)
enable_shorts = bool(self.config.get("trading", {}).get("enable_shorts", False))
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()
if self.core_broker:
try:
alpaca_positions = self.core_broker.get_positions()
invested_cost = sum(abs(float(p.get('market_value', 0))) for p in alpaca_positions)
open_symbols = set(p.get('symbol', '') for p in alpaca_positions)
available_slots = max(0, max_positions - len(open_symbols))
open_shorts_count = sum(1 for p in alpaca_positions if str(p.get('side', '')).upper() == 'SHORT')
except Exception:
pass
available_capital = max(0.0, current_capital - invested_cost)
new_positions = []
top_up_positions = []
target_portfolio = pd.DataFrame()
if not core_disabled_by_env and available_slots > 0 and available_capital > 0:
# Generate SMC signals for the universe
smc_all_df = self.compute_smc_signals_bulk(
universe_df["ticker"].tolist(), signal_date, conn,
pivots_length=self.config.get("smc", {}).get("pivots_length", 5)
)
candidates = []
if not smc_all_df.empty:
# Exclude currently open symbols
non_held = smc_all_df[~smc_all_df['symbol'].isin(open_symbols)].copy()
# Filter long and short candidates
for _, row in non_held.iterrows():
sig = row['smc_signal']
sym = row['symbol']
ret10 = row['return_10d']
if sig == "BULLISH_CHOCH":
candidates.append({
'symbol': sym,
'side': 'LONG',
'return_10d': ret10,
'momentum_score': ret10 if not pd.isna(ret10) else -999.0
})
elif enable_shorts and sig == "BEARISH_CHOCH":
candidates.append({
'symbol': sym,
'side': 'SHORT',
'return_10d': ret10,
'momentum_score': -ret10 if not pd.isna(ret10) else -999.0
})
# Sort candidates by momentum_score descending
candidates_df = pd.DataFrame(candidates)
selected_entries = []
if not candidates_df.empty:
candidates_df = candidates_df.sort_values('momentum_score', ascending=False)
# Select up to available slots, respecting max_shorts
curr_shorts = open_shorts_count
for _, cand in candidates_df.iterrows():
if len(selected_entries) >= available_slots:
break
if cand['side'] == 'SHORT':
if curr_shorts >= max_shorts:
continue
curr_shorts += 1
selected_entries.append(cand)
if selected_entries:
target_portfolio = pd.DataFrame(selected_entries)
target_portfolio['weight'] = 1.0 / len(target_portfolio)
# Populate rank_lookup for logging/reasoning
core_rank_df = target_portfolio.copy()
core_rank_df['predicted_return'] = core_rank_df['return_10d']
core_rank_df['adjusted_score'] = core_rank_df['momentum_score']
core_rank_df['penalty'] = 1.0
core_rank_df['rank'] = core_rank_df.index + 1
rank_lookup = core_rank_df.set_index('symbol')[['predicted_return', 'adjusted_score', 'penalty', 'rank']]
else:
rank_lookup = pd.DataFrame(columns=['predicted_return', 'adjusted_score', 'penalty', 'rank'])
else:
rank_lookup = pd.DataFrame(columns=['predicted_return', 'adjusted_score', 'penalty', 'rank'])
# Now execute entry orders for target_portfolio
remaining_capital = float(available_capital)
try:
min_order_dollars_cfg = float(self.config.get("trading", {}).get("min_order_dollars", 500.0) or 500.0)
except (TypeError, ValueError):
min_order_dollars_cfg = 500.0
try:
min_order_equity_pct_cfg = float(self.config.get("trading", {}).get("min_order_equity_pct", 0.005) or 0.005)
except (TypeError, ValueError):
min_order_equity_pct_cfg = 0.005
min_order_dollars = max(
0.0,
float(min_order_dollars_cfg),
float(current_capital) * max(0.0, float(min_order_equity_pct_cfg)),
)
if not core_disabled_by_env and not target_portfolio.empty:
for _, row in target_portfolio.iterrows():
symbol = row['symbol']
side = row['side']
price_data = pd.read_sql(
"SELECT open FROM prices WHERE symbol=? AND date=?",
conn,
params=(symbol, trade_date_str)
)
entry_price = None
if not price_data.empty:
val = price_data.iloc[0]['open']
if val is not None and not pd.isna(val):
entry_price = float(val)
if (entry_price is None or pd.isna(entry_price)) and self.core_broker:
# Fall back to broker's real-time price
entry_price = self.core_broker.get_latest_price(symbol)
if entry_price is not None and entry_price > 0.0:
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
if allocation_dollars < min_order_dollars:
logger.info(
"Skipping %s %s entry because allocation %.2f is below minimum order floor %.2f.",
symbol,
side,
allocation_dollars,
min_order_dollars,
)
raw_qty = allocation_dollars / entry_price
qty = max(1, int(raw_qty))
quantity = float(qty)
allocation_pct = (allocation_dollars / current_capital * 100) if current_capital else 0.0
target_price = entry_price * 1.03 if side == "LONG" else entry_price * 0.97
broker_order = None
if self.core_broker:
try:
alpaca_side = "buy" if side == "LONG" else "sell"
broker_order = self.core_broker.submit_order(
symbol=symbol,
qty=qty,
side=alpaca_side,
order_type="market",
time_in_force="day",
take_profit_price=target_price,
)
logger.info(
"Alpaca order submitted: %s %s %d shares @ market (order_id=%s, TP=%s)",
alpaca_side.upper(),
symbol,
qty,
broker_order.get("id", "unknown"),
f"${target_price:.2f}",
)
except AlpacaError as e:
logger.warning(
"Alpaca order rejected for %s: %s (code=%s). Skipping.",
symbol,
e.message,
e.code,
)
broker_order = None
except Exception as e:
logger.warning(
"Alpaca order failed for %s: %s. Skipping.",
symbol,
e,
)
broker_order = None
# Record position in SQLite (only if simulation or broker order succeeded)
if (not self.core_broker) or (broker_order is not None):
pos_id = self.core_tracker.open_position(
symbol=symbol,
entry_date=trade_date_str,
entry_price=entry_price,
quantity=quantity,
side=side,
target_price=target_price,
)
else:
pos_id = None
if pos_id:
reason = "SMC CHOCH Breakout"
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': target_price,
'quantity': quantity,
'allocation_pct': allocation_pct,
'allocation_dollars': allocation_dollars,
'reason': reason
})
remaining_capital = max(0.0, remaining_capital - allocation_dollars)
entries_today = list(new_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
if rank_df.empty:
rankings = self.get_fallback_rankings_for_date_bulk(
universe_df["ticker"].tolist(),
signal_date,
conn,
)
if rankings:
rank_df = pd.DataFrame(rankings)
rank_df["rank"] = rank_df["predicted_return"].rank(ascending=False, method="first").astype(int)
rank_df = rank_df.sort_values("rank").reset_index(drop=True)
rank_df["penalty"] = 1.0
rank_df["adjusted_score"] = rank_df["predicted_return"]
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 remaining open positions for TP hits on this day
tp_closed_positions = self.core_tracker.check_and_close_positions(
check_date=test_date.strftime('%Y-%m-%d')
)
# Close positions on Alpaca if broker is enabled
if self.core_broker and tp_closed_positions:
reverted_symbols = set()
for pos in tp_closed_positions:
symbol = pos.get('symbol')
if symbol:
try:
self.core_broker.close_position(symbol)
logger.info("Alpaca position closed on TP: %s", symbol)
except AlpacaError as e:
logger.warning(
"Alpaca close failed for %s: %s (code=%s). Reverting database close.",
symbol,
e.message,
e.code,
)
self.core_tracker.reopen_position(symbol)
reverted_symbols.add(symbol)
except Exception as e:
logger.warning("Alpaca close failed for %s: %s. Reverting database close.", symbol, e)
self.core_tracker.reopen_position(symbol)
reverted_symbols.add(symbol)
# Filter out the reverted positions
if reverted_symbols:
tp_closed_positions = [p for p in tp_closed_positions if p.get('symbol') not in reverted_symbols]
closed_positions = tp_closed_positions
# 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 / 100000.0
total_realized_pct = total_realized_dollars / 200000.0
total_unrealized_pct = total_unrealized_dollars / 200000.0
current_capital = initial_capital + total_realized_dollars + total_unrealized_dollars
new_account_return = (current_capital - initial_capital) / 200000.0
# Add previous account return
previous_return_pct = float(self.config.get('trading', {}).get('previous_return_pct') or 0.0)
total_account_return = (current_capital / 100000.0) / 2.0 - 0.5 + float(previous_return_pct or 0.0)
# Report gross exposure while keeping cash side-aware. Shorts add exposure
# but do not spend cash like long purchases, so they must not drive cash negative.
open_positions_now = self.core_tracker.get_open_positions()
invested_notional, available_cash = _position_cash_metrics(open_positions_now, current_capital)
period_start_core = self.core_tracker.get_performance_period_start()
report = {
'date': test_date.date(),
'performance_period_start': period_start_core,
'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,
'previous_return_pct': float(previous_return_pct or 0.0)
}
# --- OVERRIDE ALL DATA with Alpaca when broker is connected ---
if self.core_broker:
try:
# Keep a copy of SQLite-based unrealized DataFrame before overriding
sqlite_unrealized = unrealized.copy() if not unrealized.empty else pd.DataFrame()
alpaca_positions = self.core_broker.get_positions()
alpaca_account = self.core_broker.get_account()
alpaca_equity = float(alpaca_account.get('equity', 0))
alpaca_cash = float(alpaca_account.get('cash', 0))
# --- Build unrealized DataFrame from Alpaca ---
alpaca_unrealized_rows = []
for p in alpaca_positions:
symbol = p.get('symbol', '')
side = str(p.get('side', 'long')).upper()
qty = float(p.get('qty', 0))
entry_price = float(p.get('avg_entry_price', 0))
current_price = float(p.get('current_price', 0))
unrealized_pl = float(p.get('unrealized_pl', 0))
unrealized_plpc = float(p.get('unrealized_plpc', 0))
entry_date = None
target_price = None
if not sqlite_unrealized.empty:
match = sqlite_unrealized[sqlite_unrealized['symbol'] == symbol]
if not match.empty:
entry_date = match.iloc[0].get('entry_date')
target_price = match.iloc[0].get('target_price')
alpaca_unrealized_rows.append({
'symbol': symbol,
'side': side,
'entry_date': entry_date,
'entry_price': entry_price,
'quantity': qty,
'current_price': current_price,
'target_price': target_price,
'unrealized_pnl': unrealized_plpc,
'unrealized_pnl_dollars': unrealized_pl,
'distance_to_tp': abs(target_price - current_price) / current_price if target_price and current_price else None,
})
# Add any positions from SQLite that are not in Alpaca positions (e.g. newly entered today or historical)
alpaca_symbols = {p.get('symbol') for p in alpaca_positions}
if not sqlite_unrealized.empty:
for _, row in sqlite_unrealized.iterrows():
sym = row.get('symbol')
if sym and sym not in alpaca_symbols:
alpaca_unrealized_rows.append({
'symbol': sym,
'side': row.get('side'),
'entry_date': row.get('entry_date'),
'entry_price': row.get('entry_price'),
'quantity': row.get('quantity'),
'current_price': row.get('current_price'),
'target_price': row.get('target_price'),
'unrealized_pnl': row.get('unrealized_pnl'),
'unrealized_pnl_dollars': row.get('unrealized_pnl_dollars'),
'distance_to_tp': row.get('distance_to_tp'),
})
unrealized = pd.DataFrame(alpaca_unrealized_rows)
# --- Recompute P&L and metrics from the final combined list of open positions ---
alpaca_invested = sum(abs(float(row['quantity'] or 0) * float(row['current_price'] or 0)) for row in alpaca_unrealized_rows)
alpaca_unrealized_dollars = sum(float(row['unrealized_pnl_dollars'] or 0) for row in alpaca_unrealized_rows)
# --- Realized P&L: equity = initial + realized + unrealized ---
alpaca_realized_dollars = alpaca_equity - initial_capital - alpaca_unrealized_dollars
# --- Return calculation ---
equity_at_reset = self.config.get('trading', {}).get('equity_at_reset')
if equity_at_reset is None:
equity_at_reset = initial_capital + float(previous_return_pct or 0.0) * 200000.0
else:
equity_at_reset = float(equity_at_reset)
new_account_return = (alpaca_equity - equity_at_reset) / 200000.0
total_account_return = (alpaca_equity / 100000.0) / 2.0 - 0.5 + float(previous_return_pct or 0.0)
# --- Override report dict ---
report['open_positions'] = len(unrealized)
report['current_capital_estimate'] = alpaca_equity
report['invested_notional'] = alpaca_invested
# Calculate available cash as equity minus long positions value to satisfy Accounting Identity
alpaca_long_notional = sum(
float(row['quantity'] or 0) * float(row['current_price'] or 0)
for row in alpaca_unrealized_rows
if str(row.get('side', 'LONG')).upper() != 'SHORT'
)
report['available_cash'] = alpaca_equity - alpaca_long_notional
report['total_realized_pnl'] = alpaca_realized_dollars / 200000.0
report['total_realized_pnl_dollars'] = alpaca_realized_dollars
report['total_unrealized_pnl'] = alpaca_unrealized_dollars / 200000.0
report['total_unrealized_pnl_dollars'] = alpaca_unrealized_dollars
report['total_account_return'] = total_account_return
report['previous_return_pct'] = float(previous_return_pct or 0.0)