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weight version for CPU sandbox.
|
| 4 |
+
"""
|
| 5 |
+
import sys, os, time, json, warnings
|
| 6 |
+
warnings.filterwarnings('ignore')
|
| 7 |
+
|
| 8 |
+
# Force unbuffered output
|
| 9 |
+
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buffering=1)
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, '/app')
|
| 16 |
+
|
| 17 |
+
print("=" * 70)
|
| 18 |
+
print(" AI-POWERED TRADING INTELLIGENCE SYSTEM v1.0")
|
| 19 |
+
print("=" * 70)
|
| 20 |
+
start = time.time()
|
| 21 |
+
|
| 22 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 23 |
+
# 1. GENERATE DATA
|
| 24 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 25 |
+
print("\n[1/5] Generating realistic financial data...")
|
| 26 |
+
|
| 27 |
+
np.random.seed(42)
|
| 28 |
+
num_days = 1500
|
| 29 |
+
dt = 1/252
|
| 30 |
+
prices = [150.0]
|
| 31 |
+
vol = 0.20
|
| 32 |
+
|
| 33 |
+
for i in range(num_days - 1):
|
| 34 |
+
vol = vol + 0.1 * (0.20 - vol) * dt + 0.3 * np.sqrt(dt) * np.random.normal()
|
| 35 |
+
vol = max(vol, 0.05)
|
| 36 |
+
ret = (0.08 - 0.5 * vol**2) * dt + vol * np.sqrt(dt) * np.random.normal()
|
| 37 |
+
prices.append(prices[-1] * np.exp(ret))
|
| 38 |
+
|
| 39 |
+
df = pd.DataFrame({
|
| 40 |
+
'date': pd.date_range('2019-01-02', periods=num_days, freq='B')[:num_days],
|
| 41 |
+
'open': [p * (1 + np.random.normal(0, 0.002)) for p in prices],
|
| 42 |
+
'high': [p * (1 + abs(np.random.normal(0, 0.01))) for p in prices],
|
| 43 |
+
'low': [p * (1 - abs(np.random.normal(0, 0.01))) for p in prices],
|
| 44 |
+
'close': prices,
|
| 45 |
+
'volume': [int(1e6 * np.exp(np.random.normal(0, 0.3))) for _ in range(num_days)],
|
| 46 |
+
})
|
| 47 |
+
# Fix OHLC consistency
|
| 48 |
+
df['high'] = df[['open', 'high', 'close']].max(axis=1) * (1 + abs(np.random.normal(0, 0.002, num_days)))
|
| 49 |
+
df['low'] = df[['open', 'low', 'close']].min(axis=1) * (1 - abs(np.random.normal(0, 0.002, num_days)))
|
| 50 |
+
|
| 51 |
+
print(f" Generated {num_days} days: ${prices[0]:.2f} -> ${prices[-1]:.2f}")
|
| 52 |
+
|
| 53 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 54 |
+
# 2. FEATURE ENGINEERING
|
| 55 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
+
print("\n[2/5] Computing features...")
|
| 57 |
+
from trading_intelligence.feature_engine import FeatureEngine
|
| 58 |
+
|
| 59 |
+
fe = FeatureEngine(lookback_window=30, prediction_horizons=[1, 5, 20])
|
| 60 |
+
features = fe.compute_all_features(df)
|
| 61 |
+
features_norm, norm_params = fe.normalize_features(features)
|
| 62 |
+
|
| 63 |
+
print(f" Features: {len(fe.feature_names)} channels")
|
| 64 |
+
print(f" Samples after windowing: {len(features)}")
|
| 65 |
+
|
| 66 |
+
# Create sequences
|
| 67 |
+
target_cols = []
|
| 68 |
+
for h in [1, 5, 20]:
|
| 69 |
+
target_cols.extend([f'target_direction_{h}', f'target_return_{h}'])
|
| 70 |
+
|
| 71 |
+
X, y = fe.create_sequences(features_norm, target_cols=target_cols)
|
| 72 |
+
valid = np.isfinite(X).all(axis=(1, 2)) & np.isfinite(y).all(axis=1)
|
| 73 |
+
X, y = X[valid], y[valid]
|
| 74 |
+
|
| 75 |
+
print(f" X shape: {X.shape}, y shape: {y.shape}")
|
| 76 |
+
|
| 77 |
+
# Split
|
| 78 |
+
n = len(X)
|
| 79 |
+
train_end = int(n * 0.7)
|
| 80 |
+
val_end = int(n * 0.85)
|
| 81 |
+
|
| 82 |
+
X_train, y_train = X[:train_end], y[:train_end]
|
| 83 |
+
X_val, y_val = X[train_end:val_end], y[train_end:val_end]
|
| 84 |
+
X_test, y_test = X[val_end:], y[val_end:]
|
| 85 |
+
|
| 86 |
+
print(f" Train: {len(X_train)}, Val: {len(X_val)}, Test: {len(X_test)}")
|
| 87 |
+
|
| 88 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 89 |
+
# 3. MODEL TRAINING
|
| 90 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 91 |
+
print("\n[3/5] Training prediction model...")
|
| 92 |
+
from trading_intelligence.prediction_model import TradingTransformer, MultiTaskLoss
|
| 93 |
+
from torch.utils.data import TensorDataset, DataLoader
|
| 94 |
+
|
| 95 |
+
device = torch.device('cpu')
|
| 96 |
+
num_channels = X.shape[1]
|
| 97 |
+
|
| 98 |
+
model = TradingTransformer(
|
| 99 |
+
num_channels=num_channels, seq_len=30, patch_len=6, stride=3,
|
| 100 |
+
d_model=64, n_heads=4, n_layers=2, d_ff=128,
|
| 101 |
+
num_horizons=3, dropout=0.1,
|
| 102 |
+
).to(device)
|
| 103 |
+
|
| 104 |
+
loss_fn = MultiTaskLoss(num_horizons=3).to(device)
|
| 105 |
+
params = sum(p.numel() for p in model.parameters())
|
| 106 |
+
print(f" Model: {params:,} parameters")
|
| 107 |
+
|
| 108 |
+
optimizer = torch.optim.AdamW(
|
| 109 |
+
list(model.parameters()) + list(loss_fn.parameters()),
|
| 110 |
+
lr=1e-3, weight_decay=1e-4
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
train_ds = TensorDataset(torch.FloatTensor(X_train), torch.FloatTensor(y_train))
|
| 114 |
+
val_ds = TensorDataset(torch.FloatTensor(X_val), torch.FloatTensor(y_val))
|
| 115 |
+
train_loader = DataLoader(train_ds, batch_size=128, shuffle=True)
|
| 116 |
+
val_loader = DataLoader(val_ds, batch_size=128, shuffle=False)
|
| 117 |
+
|
| 118 |
+
best_val = float('inf')
|
| 119 |
+
best_state = None
|
| 120 |
+
|
| 121 |
+
for epoch in range(15):
|
| 122 |
+
model.train()
|
| 123 |
+
train_loss = 0
|
| 124 |
+
n_batch = 0
|
| 125 |
+
for xb, yb in train_loader:
|
| 126 |
+
xb, yb = xb.to(device), yb.to(device)
|
| 127 |
+
preds = model(xb)
|
| 128 |
+
|
| 129 |
+
directions = torch.stack([yb[:, i*2] for i in range(3)], dim=1)
|
| 130 |
+
returns = torch.stack([yb[:, i*2+1] for i in range(3)], dim=1)
|
| 131 |
+
|
| 132 |
+
losses = loss_fn(preds, {'direction': directions, 'returns': returns})
|
| 133 |
+
optimizer.zero_grad()
|
| 134 |
+
losses['total_loss'].backward()
|
| 135 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 136 |
+
optimizer.step()
|
| 137 |
+
train_loss += losses['total_loss'].item()
|
| 138 |
+
n_batch += 1
|
| 139 |
+
|
| 140 |
+
# Validate
|
| 141 |
+
model.eval()
|
| 142 |
+
val_loss = 0
|
| 143 |
+
val_batches = 0
|
| 144 |
+
correct = np.zeros(3)
|
| 145 |
+
total = 0
|
| 146 |
+
|
| 147 |
+
with torch.no_grad():
|
| 148 |
+
for xb, yb in val_loader:
|
| 149 |
+
xb, yb = xb.to(device), yb.to(device)
|
| 150 |
+
preds = model(xb)
|
| 151 |
+
directions = torch.stack([yb[:, i*2] for i in range(3)], dim=1)
|
| 152 |
+
returns = torch.stack([yb[:, i*2+1] for i in range(3)], dim=1)
|
| 153 |
+
losses = loss_fn(preds, {'direction': directions, 'returns': returns})
|
| 154 |
+
val_loss += losses['total_loss'].item()
|
| 155 |
+
val_batches += 1
|
| 156 |
+
|
| 157 |
+
dir_preds = (torch.sigmoid(preds['direction_logits']) > 0.5).float()
|
| 158 |
+
for h in range(3):
|
| 159 |
+
correct[h] += (dir_preds[:, h] == directions[:, h]).sum().item()
|
| 160 |
+
total += len(xb)
|
| 161 |
+
|
| 162 |
+
tl = train_loss / max(n_batch, 1)
|
| 163 |
+
vl = val_loss / max(val_batches, 1)
|
| 164 |
+
accs = [correct[h] / max(total, 1) for h in range(3)]
|
| 165 |
+
|
| 166 |
+
print(f" Epoch {epoch+1:2d} | Train: {tl:.4f} | Val: {vl:.4f} | "
|
| 167 |
+
f"DA-1d: {accs[0]:.1%} | DA-5d: {accs[1]:.1%} | DA-20d: {accs[2]:.1%}")
|
| 168 |
+
|
| 169 |
+
if vl < best_val:
|
| 170 |
+
best_val = vl
|
| 171 |
+
best_state = {k: v.cpu().clone() for k, v in model.state_dict().items()}
|
| 172 |
+
|
| 173 |
+
if best_state:
|
| 174 |
+
model.load_state_dict(best_state)
|
| 175 |
+
model.to(device)
|
| 176 |
+
|
| 177 |
+
# Save
|
| 178 |
+
os.makedirs('/app/models', exist_ok=True)
|
| 179 |
+
torch.save({'model_state': model.state_dict(), 'config': {'num_channels': num_channels}},
|
| 180 |
+
'/app/models/TECH1_model.pt')
|
| 181 |
+
print(f" Best val loss: {best_val:.4f}")
|
| 182 |
+
|
| 183 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 184 |
+
# 4. EVALUATION (BACKTEST)
|
| 185 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 186 |
+
print("\n[4/5] Backtesting on test set...")
|
| 187 |
+
from trading_intelligence.evaluation import Evaluator, format_evaluation
|
| 188 |
+
|
| 189 |
+
evaluator = Evaluator(prediction_horizons=[1, 5, 20], trading_costs=0.001)
|
| 190 |
+
test_ds = TensorDataset(torch.FloatTensor(X_test), torch.FloatTensor(y_test))
|
| 191 |
+
test_loader = DataLoader(test_ds, batch_size=128, shuffle=False)
|
| 192 |
+
|
| 193 |
+
eval_results = evaluator.evaluate_predictions(model, test_loader, device)
|
| 194 |
+
print(format_evaluation(eval_results))
|
| 195 |
+
|
| 196 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 197 |
+
# 5. RISK MODEL + PERSONALIZATION + DECISIONS
|
| 198 |
+
# βββββββββββββββββββββββββββββββββββββββββββ
|
| 199 |
+
print("\n[5/5] Risk Model + Personalization + Decision Engine...")
|
| 200 |
+
|
| 201 |
+
# Risk Model Demo
|
| 202 |
+
from trading_intelligence.risk_model import RiskModel
|
| 203 |
+
from trading_intelligence.personalization import TraderProfiler, BehaviorAlertSystem, PersonalizationEngine, TRADER_TYPES
|
| 204 |
+
from trading_intelligence.decision_engine import DecisionEngine, format_decision
|
| 205 |
+
|
| 206 |
+
risk_model = RiskModel(market_dim=64, portfolio_dim=64, behavior_dim=64)
|
| 207 |
+
risk_model.eval()
|
| 208 |
+
|
| 209 |
+
with torch.no_grad():
|
| 210 |
+
market_state = torch.randn(2, 64)
|
| 211 |
+
positions = torch.randn(2, 5, 8)
|
| 212 |
+
position_mask = torch.ones(2, 5, dtype=torch.bool)
|
| 213 |
+
position_mask[:, 3:] = False
|
| 214 |
+
account = torch.tensor([[100000, 10000, 0.05, 3, 0.3, 0.7],
|
| 215 |
+
[50000, 5000, 0.15, 3, 0.5, 0.5]], dtype=torch.float32)
|
| 216 |
+
trades = torch.randn(2, 20, 12)
|
| 217 |
+
|
| 218 |
+
risk_out = risk_model(market_state, positions, account, trades, position_mask)
|
| 219 |
+
|
| 220 |
+
print("\n RISK MODEL OUTPUTS:")
|
| 221 |
+
for i, label in enumerate(["Conservative Trader", "Aggressive Trader"]):
|
| 222 |
+
print(f"\n {label}:")
|
| 223 |
+
print(f" Risk Score: {risk_out['risk_score'][i]:.3f}")
|
| 224 |
+
print(f" Position Size: {risk_out['adjusted_position_size'][i]:.1%}")
|
| 225 |
+
print(f" SL ATR Multiple: {risk_out['stop_loss_atr_mult'][i]:.2f}")
|
| 226 |
+
print(f" TP ATR Multiple: {risk_out['take_profit_atr_mult'][i]:.2f}")
|
| 227 |
+
dd = risk_out['drawdown_probs'][i]
|
| 228 |
+
print(f" P(DD>5/10/15/20%): {dd[0]:.0%}/{dd[1]:.0%}/{dd[2]:.0%}/{dd[3]:.0%}")
|
| 229 |
+
beh = risk_out['behavior_profile']
|
| 230 |
+
print(f" Risk Appetite: {beh['risk_appetite'][i]:.3f}")
|
| 231 |
+
print(f" Overtrading: {beh['overtrading_prob'][i]:.0%}")
|
| 232 |
+
print(f" Revenge Trading: {beh['revenge_trading_prob'][i]:.0%}")
|
| 233 |
+
tt = torch.argmax(beh['trader_type_logits'][i]).item()
|
| 234 |
+
print(f" Trader Type: {TRADER_TYPES[tt]}")
|
| 235 |
+
|
| 236 |
+
# Personalization Demo
|
| 237 |
+
print("\n PERSONALIZATION:")
|
| 238 |
+
profiler = TraderProfiler()
|
| 239 |
+
alert_system = BehaviorAlertSystem()
|
| 240 |
+
personalization = PersonalizationEngine()
|
| 241 |
+
|
| 242 |
+
for name, trades_list, portfolio_val in [
|
| 243 |
+
("Conservative Carol",
|
| 244 |
+
[{'entry_price': 100, 'exit_price': 101, 'size': 0.01, 'pnl': 10, 'holding_time': 2880, 'direction': 1}] * 20 +
|
| 245 |
+
[{'entry_price': 100, 'exit_price': 99.5, 'size': 0.01, 'pnl': -5, 'holding_time': 1440, 'direction': 1}] * 8,
|
| 246 |
+
100000),
|
| 247 |
+
("Aggressive Alex",
|
| 248 |
+
[{'entry_price': 100, 'exit_price': 105, 'size': 0.15, 'pnl': 750, 'holding_time': 60, 'direction': 1}] * 12 +
|
| 249 |
+
[{'entry_price': 100, 'exit_price': 93, 'size': 0.20, 'pnl': -1400, 'holding_time': 30, 'direction': 1}] * 10,
|
| 250 |
+
50000),
|
| 251 |
+
("Scalper Sam",
|
| 252 |
+
[{'entry_price': 100, 'exit_price': 100.1, 'size': 0.03, 'pnl': 3, 'holding_time': 2, 'direction': 1}] * 80 +
|
| 253 |
+
[{'entry_price': 100, 'exit_price': 99.95, 'size': 0.03, 'pnl': -1.5, 'holding_time': 1, 'direction': -1}] * 50,
|
| 254 |
+
75000),
|
| 255 |
+
]:
|
| 256 |
+
feats = profiler.extract_behavior_features(trades_list)
|
| 257 |
+
profile = profiler.predict_type(feats)
|
| 258 |
+
alerts = alert_system.analyze(trades_list[-10:], portfolio_val, 1.0)
|
| 259 |
+
params = personalization.get_personalized_params(profile, alerts)
|
| 260 |
+
|
| 261 |
+
print(f"\n {name}: Type={profile['type_name']}, Win={profile['features']['win_rate']:.0%}, "
|
| 262 |
+
f"PF={profile['features']['profit_factor']:.1f}, Status={alerts['status'].upper()}")
|
| 263 |
+
print(f" -> Max Position: {params['max_position_pct']:.1%}, Min Confidence: {params['min_confidence']:.0%}")
|
| 264 |
+
for a in alerts['alerts']:
|
| 265 |
+
print(f" [{a['severity']}] {a['type']}")
|
| 266 |
+
|
| 267 |
+
# Decision Engine Demo
|
| 268 |
+
print("\n DECISION ENGINE:")
|
| 269 |
+
engine = DecisionEngine(prediction_model=model, personalization_engine=personalization)
|
| 270 |
+
|
| 271 |
+
market_feats = np.random.randn(1, num_channels, 30).astype(np.float32)
|
| 272 |
+
decisions = engine.make_multi_horizon_decisions(
|
| 273 |
+
market_features=market_feats,
|
| 274 |
+
trader_profile={'cluster': 1, 'type_name': 'Moderate'},
|
| 275 |
+
behavior_alerts={'alerts': [], 'risk_multiplier': 1.0, 'status': 'normal'},
|
| 276 |
+
current_atr=0.015,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
for d in decisions:
|
| 280 |
+
print(format_decision(d))
|
| 281 |
+
|
| 282 |
+
# Decision with alert override
|
| 283 |
+
alert_decision = engine.make_decision(
|
| 284 |
+
market_features=market_feats,
|
| 285 |
+
trader_profile={'cluster': 2, 'type_name': 'Aggressive'},
|
| 286 |
+
behavior_alerts={
|
| 287 |
+
'alerts': [{'type': 'REVENGE_TRADING', 'severity': 'CRITICAL',
|
| 288 |
+
'message': 'Position size tripled after loss'}],
|
| 289 |
+
'risk_multiplier': 0.3, 'status': 'critical'
|
| 290 |
+
},
|
| 291 |
+
current_atr=0.015, horizon_idx=0,
|
| 292 |
+
)
|
| 293 |
+
print("\n WITH CRITICAL ALERT:")
|
| 294 |
+
print(format_decision(alert_decision))
|
| 295 |
+
|
| 296 |
+
# Save results
|
| 297 |
+
elapsed = time.time() - start
|
| 298 |
+
results_json = {
|
| 299 |
+
'eval_results': {k: v for k, v in eval_results.items()
|
| 300 |
+
if k != 'summary' or True},
|
| 301 |
+
'model_params': params,
|
| 302 |
+
'elapsed_seconds': elapsed,
|
| 303 |
+
}
|
| 304 |
+
# Clean for JSON serialization
|
| 305 |
+
def clean_for_json(obj):
|
| 306 |
+
if isinstance(obj, dict):
|
| 307 |
+
return {k: clean_for_json(v) for k, v in obj.items()
|
| 308 |
+
if k not in ['equity_curve', 'daily_returns']}
|
| 309 |
+
elif isinstance(obj, (np.floating, np.integer)):
|
| 310 |
+
return float(obj)
|
| 311 |
+
elif isinstance(obj, np.ndarray):
|
| 312 |
+
return obj.tolist()
|
| 313 |
+
return obj
|
| 314 |
+
|
| 315 |
+
with open('/app/results_summary.json', 'w') as f:
|
| 316 |
+
json.dump(clean_for_json(results_json), f, indent=2, default=str)
|
| 317 |
+
|
| 318 |
+
print(f"\n{'='*70}")
|
| 319 |
+
print(f" COMPLETE in {elapsed:.1f}s")
|
| 320 |
+
print(f" Model saved: /app/models/TECH1_model.pt")
|
| 321 |
+
print(f" Results: /app/results_summary.json")
|
| 322 |
+
print(f"{'='*70}")
|