PROSTLE commited on
Commit
de73820
·
unverified ·
1 Parent(s): 77da8c8

Update trader.py

Browse files
Files changed (1) hide show
  1. trader.py +206 -60
trader.py CHANGED
@@ -1,34 +1,26 @@
1
- """
2
- StockSense AI — Auto Trading Engine (Paper Trading)
3
- Strategy: LSTM Prediction-Based
4
- - BUY when model predicts price going UP in next 5 days
5
- - SELL when stop-loss / take-profit / trailing-stop / prediction reversal
6
- """
7
 
8
  import json
9
  import os
10
  from datetime import datetime
11
  from threading import Lock
12
 
13
- # ── CONFIG ────────────────────────────────���────────────
14
- INITIAL_BALANCE = 100_000.00
15
- STOP_LOSS_PCT = -3.0 # -3% from buy price
16
- TAKE_PROFIT_PCT = 5.0 # +5% from buy price
17
- TRAILING_STOP_PCT = -2.0 # -2% from peak after buy
18
- MAX_HOLD_DAYS = 5 # auto-sell after 5 days
19
- POSITION_SIZE_PCT = 10.0 # use 10% of balance per trade
20
 
21
  DATA_FILE = "portfolio.json"
22
  _lock = Lock()
23
 
24
 
25
- # ── PORTFOLIO STATE ────────────────────────────────────
26
  def _default_state():
27
  return {
28
  "balance": INITIAL_BALANCE,
29
  "initial_balance": INITIAL_BALANCE,
30
- "positions": {}, # ticker -> position dict
31
- "trade_history": [], # list of completed trades
32
  "bot_active": False,
33
  "created_at": datetime.now().isoformat(),
34
  }
@@ -47,14 +39,12 @@ def _save_state(state: dict):
47
 
48
 
49
  def get_portfolio() -> dict:
50
- """Return current portfolio state."""
51
  with _lock:
52
  state = _load_state()
53
  return state
54
 
55
 
56
  def reset_portfolio() -> dict:
57
- """Reset portfolio to initial state."""
58
  with _lock:
59
  state = _default_state()
60
  _save_state(state)
@@ -62,7 +52,6 @@ def reset_portfolio() -> dict:
62
 
63
 
64
  def toggle_bot() -> dict:
65
- """Toggle auto-trading bot ON/OFF."""
66
  with _lock:
67
  state = _load_state()
68
  state["bot_active"] = not state["bot_active"]
@@ -70,20 +59,14 @@ def toggle_bot() -> dict:
70
  return {"bot_active": state["bot_active"]}
71
 
72
 
73
- # ── TRADING LOGIC ──────────────────────────────────────
74
  def execute_buy(ticker: str, current_price: float, predicted_prices: list,
75
  confidence: float) -> dict:
76
- """
77
- Execute a BUY order (paper trade).
78
- """
79
  with _lock:
80
  state = _load_state()
81
 
82
- # Already holding this ticker?
83
  if ticker in state["positions"]:
84
  return {"status": "skipped", "reason": f"Already holding {ticker}"}
85
 
86
- # Calculate position size
87
  position_value = state["balance"] * (POSITION_SIZE_PCT / 100)
88
  if position_value < current_price:
89
  return {"status": "skipped", "reason": "Insufficient balance"}
@@ -94,11 +77,9 @@ def execute_buy(ticker: str, current_price: float, predicted_prices: list,
94
 
95
  cost = shares * current_price
96
 
97
- # Stop-loss & take-profit prices
98
  stop_loss = round(current_price * (1 + STOP_LOSS_PCT / 100), 2)
99
  take_profit = round(current_price * (1 + TAKE_PROFIT_PCT / 100), 2)
100
 
101
- # Create position
102
  position = {
103
  "ticker": ticker,
104
  "shares": shares,
@@ -132,9 +113,6 @@ def execute_buy(ticker: str, current_price: float, predicted_prices: list,
132
 
133
 
134
  def execute_sell(ticker: str, current_price: float, reason: str) -> dict:
135
- """
136
- Execute a SELL order (paper trade).
137
- """
138
  with _lock:
139
  state = _load_state()
140
 
@@ -146,7 +124,6 @@ def execute_sell(ticker: str, current_price: float, reason: str) -> dict:
146
  profit = revenue - pos["cost"]
147
  profit_pct = (profit / pos["cost"]) * 100
148
 
149
- # Record trade history
150
  trade = {
151
  "ticker": ticker,
152
  "shares": pos["shares"],
@@ -181,10 +158,6 @@ def execute_sell(ticker: str, current_price: float, reason: str) -> dict:
181
 
182
 
183
  def check_position(ticker: str, current_price: float) -> dict:
184
- """
185
- Check if a position should be sold based on stop-loss,
186
- take-profit, or trailing stop.
187
- """
188
  with _lock:
189
  state = _load_state()
190
 
@@ -195,17 +168,13 @@ def check_position(ticker: str, current_price: float) -> dict:
195
  buy_price = pos["buy_price"]
196
  change_pct = ((current_price - buy_price) / buy_price) * 100
197
 
198
- # ── STOP LOSS ──
199
  if current_price <= pos["stop_loss"]:
200
  return {"action": "sell", "reason": f"Stop-loss triggered ({STOP_LOSS_PCT}%)"}
201
 
202
- # ── TAKE PROFIT ──
203
  if current_price >= pos["take_profit"]:
204
  return {"action": "sell", "reason": f"Take-profit reached (+{TAKE_PROFIT_PCT}%)"}
205
 
206
- # ── TRAILING STOP ──
207
  if current_price > pos["peak_price"]:
208
- # Update peak and trailing stop
209
  with _lock:
210
  state = _load_state()
211
  state["positions"][ticker]["peak_price"] = current_price
@@ -216,7 +185,6 @@ def check_position(ticker: str, current_price: float) -> dict:
216
  elif current_price <= pos["trailing_stop"]:
217
  return {"action": "sell", "reason": f"Trailing stop triggered ({TRAILING_STOP_PCT}%)"}
218
 
219
- # ── MAX HOLD DAYS ──
220
  pos["day_count"] += 1
221
  if pos["day_count"] >= MAX_HOLD_DAYS:
222
  return {"action": "sell", "reason": f"Max hold period ({MAX_HOLD_DAYS} days)"}
@@ -232,56 +200,234 @@ def check_position(ticker: str, current_price: float) -> dict:
232
  }
233
 
234
 
235
- def evaluate_trade_signal(ticker: str, current_price: float,
236
- predicted_prices: list, confidence: float) -> dict:
237
- """
238
- Core strategy: Decide BUY / SELL / HOLD based on LSTM prediction.
239
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  state = _load_state()
241
 
242
- # Prediction analysis
 
 
 
 
 
 
 
 
 
243
  pred_day1 = predicted_prices[0]
244
  pred_day5 = predicted_prices[-1]
245
- pred_change_pct = ((pred_day5 - current_price) / current_price) * 100
246
  pred_direction = "up" if pred_day5 > current_price else "down"
247
 
248
- # Count how many predicted days are above current price
249
- days_above = sum(1 for p in predicted_prices if p > current_price)
250
-
251
  signal = {
252
  "ticker": ticker,
253
  "current_price": current_price,
254
  "predicted_day1": round(pred_day1, 2),
255
  "predicted_day5": round(pred_day5, 2),
256
- "pred_change_pct": round(pred_change_pct, 2),
257
  "pred_direction": pred_direction,
258
- "days_above_current": days_above,
259
  "confidence": confidence,
 
 
 
260
  }
261
 
262
- # Already holding?
263
  if ticker in state["positions"]:
264
  check = check_position(ticker, current_price)
265
  if check["action"] == "sell":
266
  result = execute_sell(ticker, current_price, check["reason"])
267
  signal["action"] = "SELL"
268
  signal["trade_result"] = result
269
- elif pred_direction == "down" and days_above <= 1 and confidence > 40:
270
- result = execute_sell(ticker, current_price, "Prediction reversal (downtrend)")
 
271
  signal["action"] = "SELL"
272
  signal["trade_result"] = result
273
  else:
274
  signal["action"] = "HOLD"
275
  signal["position"] = check
276
  else:
277
- # BUY conditions: prediction is UP + enough confidence
278
- if (pred_direction == "up" and days_above >= 3 and
279
- confidence >= 35 and pred_change_pct > 0.5):
 
 
 
280
  result = execute_buy(ticker, current_price, predicted_prices, confidence)
281
  signal["action"] = "BUY"
282
  signal["trade_result"] = result
283
  else:
284
  signal["action"] = "WAIT"
285
- signal["reason"] = "Conditions not met for entry"
 
 
 
286
 
287
- return signal
 
 
 
 
 
 
 
1
 
2
  import json
3
  import os
4
  from datetime import datetime
5
  from threading import Lock
6
 
7
+ INITIAL_BALANCE = 1_000_000.00
8
+ STOP_LOSS_PCT = -3.0
9
+ TAKE_PROFIT_PCT = 5.0
10
+ TRAILING_STOP_PCT = -2.0
11
+ MAX_HOLD_DAYS = 5
12
+ POSITION_SIZE_PCT = 10.0
 
13
 
14
  DATA_FILE = "portfolio.json"
15
  _lock = Lock()
16
 
17
 
 
18
  def _default_state():
19
  return {
20
  "balance": INITIAL_BALANCE,
21
  "initial_balance": INITIAL_BALANCE,
22
+ "positions": {},
23
+ "trade_history": [],
24
  "bot_active": False,
25
  "created_at": datetime.now().isoformat(),
26
  }
 
39
 
40
 
41
  def get_portfolio() -> dict:
 
42
  with _lock:
43
  state = _load_state()
44
  return state
45
 
46
 
47
  def reset_portfolio() -> dict:
 
48
  with _lock:
49
  state = _default_state()
50
  _save_state(state)
 
52
 
53
 
54
  def toggle_bot() -> dict:
 
55
  with _lock:
56
  state = _load_state()
57
  state["bot_active"] = not state["bot_active"]
 
59
  return {"bot_active": state["bot_active"]}
60
 
61
 
 
62
  def execute_buy(ticker: str, current_price: float, predicted_prices: list,
63
  confidence: float) -> dict:
 
 
 
64
  with _lock:
65
  state = _load_state()
66
 
 
67
  if ticker in state["positions"]:
68
  return {"status": "skipped", "reason": f"Already holding {ticker}"}
69
 
 
70
  position_value = state["balance"] * (POSITION_SIZE_PCT / 100)
71
  if position_value < current_price:
72
  return {"status": "skipped", "reason": "Insufficient balance"}
 
77
 
78
  cost = shares * current_price
79
 
 
80
  stop_loss = round(current_price * (1 + STOP_LOSS_PCT / 100), 2)
81
  take_profit = round(current_price * (1 + TAKE_PROFIT_PCT / 100), 2)
82
 
 
83
  position = {
84
  "ticker": ticker,
85
  "shares": shares,
 
113
 
114
 
115
  def execute_sell(ticker: str, current_price: float, reason: str) -> dict:
 
 
 
116
  with _lock:
117
  state = _load_state()
118
 
 
124
  profit = revenue - pos["cost"]
125
  profit_pct = (profit / pos["cost"]) * 100
126
 
 
127
  trade = {
128
  "ticker": ticker,
129
  "shares": pos["shares"],
 
158
 
159
 
160
  def check_position(ticker: str, current_price: float) -> dict:
 
 
 
 
161
  with _lock:
162
  state = _load_state()
163
 
 
168
  buy_price = pos["buy_price"]
169
  change_pct = ((current_price - buy_price) / buy_price) * 100
170
 
 
171
  if current_price <= pos["stop_loss"]:
172
  return {"action": "sell", "reason": f"Stop-loss triggered ({STOP_LOSS_PCT}%)"}
173
 
 
174
  if current_price >= pos["take_profit"]:
175
  return {"action": "sell", "reason": f"Take-profit reached (+{TAKE_PROFIT_PCT}%)"}
176
 
 
177
  if current_price > pos["peak_price"]:
 
178
  with _lock:
179
  state = _load_state()
180
  state["positions"][ticker]["peak_price"] = current_price
 
185
  elif current_price <= pos["trailing_stop"]:
186
  return {"action": "sell", "reason": f"Trailing stop triggered ({TRAILING_STOP_PCT}%)"}
187
 
 
188
  pos["day_count"] += 1
189
  if pos["day_count"] >= MAX_HOLD_DAYS:
190
  return {"action": "sell", "reason": f"Max hold period ({MAX_HOLD_DAYS} days)"}
 
200
  }
201
 
202
 
203
+ def compute_technical_score(indicators: dict) -> float:
204
+ score = 50.0
205
+
206
+ rsi = indicators.get("RSI", 50)
207
+ macd = indicators.get("MACD", 0)
208
+ macd_signal = indicators.get("MACD_Signal", 0)
209
+ sma_20 = indicators.get("SMA_20", 0)
210
+ sma_50 = indicators.get("SMA_50", 0)
211
+ price = indicators.get("price", 0)
212
+
213
+ if rsi < 25:
214
+ score += 20
215
+ elif rsi < 35:
216
+ score += 12
217
+ elif rsi < 45:
218
+ score += 5
219
+ elif rsi > 75:
220
+ score -= 20
221
+ elif rsi > 65:
222
+ score -= 12
223
+ elif rsi > 55:
224
+ score -= 5
225
+
226
+ macd_diff = macd - macd_signal
227
+ if macd_diff > 0:
228
+ score += min(15, macd_diff * 100)
229
+ else:
230
+ score += max(-15, macd_diff * 100)
231
+
232
+ if sma_20 > 0 and price > sma_20:
233
+ score += 8
234
+ elif sma_20 > 0:
235
+ score -= 8
236
+
237
+ if sma_50 > 0 and price > sma_50:
238
+ score += 7
239
+ elif sma_50 > 0:
240
+ score -= 7
241
+
242
+ if sma_20 > 0 and sma_50 > 0:
243
+ if sma_20 > sma_50:
244
+ score += 5
245
+ else:
246
+ score -= 5
247
+
248
+ return max(0, min(100, score))
249
+
250
+
251
+ def compute_composite_score(
252
+ predicted_prices: list,
253
+ current_price: float,
254
+ confidence: float,
255
+ indicators: dict | None = None,
256
+ sentiment_score: float | None = None,
257
+ ) -> dict:
258
+ pred_day5 = predicted_prices[-1]
259
+ pred_change_pct = ((pred_day5 - current_price) / current_price) * 100
260
+ days_above = sum(1 for p in predicted_prices if p > current_price)
261
+
262
+ lstm_score = 50.0
263
+ lstm_score += pred_change_pct * 5
264
+ lstm_score += (days_above - 2.5) * 6
265
+ lstm_score += (confidence - 50) * 0.3
266
+ lstm_score = max(0, min(100, lstm_score))
267
+
268
+ if indicators:
269
+ tech_score = compute_technical_score(indicators)
270
+ else:
271
+ tech_score = 50.0
272
+
273
+ if sentiment_score is not None:
274
+ sent_score = 50 + sentiment_score * 50
275
+ sent_score = max(0, min(100, sent_score))
276
+ else:
277
+ sent_score = 50.0
278
+
279
+ LSTM_W, TECH_W, SENT_W = 0.40, 0.35, 0.25
280
+ composite = (lstm_score * LSTM_W) + (tech_score * TECH_W) + (sent_score * SENT_W)
281
+ composite = round(max(0, min(100, composite)), 1)
282
+
283
+ return {
284
+ "composite_score": composite,
285
+ "lstm_score": round(lstm_score, 1),
286
+ "tech_score": round(tech_score, 1),
287
+ "sent_score": round(sent_score, 1),
288
+ "pred_change_pct": round(pred_change_pct, 2),
289
+ "days_above": days_above,
290
+ }
291
+
292
+
293
+ def detect_market_regime(indicators: dict | None) -> dict:
294
+ if not indicators:
295
+ return {
296
+ "regime": "NEUTRAL",
297
+ "buy_threshold": 52,
298
+ "sell_threshold": 35,
299
+ "position_pct": 10,
300
+ "min_confidence": 20,
301
+ }
302
+
303
+ rsi = indicators.get("RSI", 50)
304
+ macd = indicators.get("MACD", 0)
305
+ macd_signal = indicators.get("MACD_Signal", 0)
306
+ sma_20 = indicators.get("SMA_20", 0)
307
+ sma_50 = indicators.get("SMA_50", 0)
308
+ price = indicators.get("price", 0)
309
+
310
+ bull_signals = 0
311
+ bear_signals = 0
312
+
313
+ if rsi < 40:
314
+ bull_signals += 1
315
+ elif rsi > 65:
316
+ bear_signals += 1
317
+
318
+ if macd > macd_signal:
319
+ bull_signals += 1
320
+ else:
321
+ bear_signals += 1
322
+
323
+ if sma_20 > 0 and price > sma_20:
324
+ bull_signals += 1
325
+ elif sma_20 > 0:
326
+ bear_signals += 1
327
+
328
+ if sma_50 > 0 and price > sma_50:
329
+ bull_signals += 1
330
+ elif sma_50 > 0:
331
+ bear_signals += 1
332
+
333
+ if sma_20 > sma_50 > 0:
334
+ bull_signals += 1
335
+ elif sma_50 > sma_20 > 0:
336
+ bear_signals += 1
337
+
338
+ if bull_signals >= 4:
339
+ return {
340
+ "regime": "BULL",
341
+ "buy_threshold": 45,
342
+ "sell_threshold": 30,
343
+ "position_pct": 15,
344
+ "min_confidence": 15,
345
+ }
346
+ elif bear_signals >= 4:
347
+ return {
348
+ "regime": "BEAR",
349
+ "buy_threshold": 60,
350
+ "sell_threshold": 40,
351
+ "position_pct": 5,
352
+ "min_confidence": 30,
353
+ }
354
+ else:
355
+ return {
356
+ "regime": "NEUTRAL",
357
+ "buy_threshold": 52,
358
+ "sell_threshold": 35,
359
+ "position_pct": 10,
360
+ "min_confidence": 20,
361
+ }
362
+
363
+
364
+ def evaluate_trade_signal(
365
+ ticker: str,
366
+ current_price: float,
367
+ predicted_prices: list,
368
+ confidence: float,
369
+ indicators: dict | None = None,
370
+ sentiment_score: float | None = None,
371
+ ) -> dict:
372
  state = _load_state()
373
 
374
+ regime = detect_market_regime(indicators)
375
+ buy_threshold = regime["buy_threshold"]
376
+ sell_threshold = regime["sell_threshold"]
377
+
378
+ scores = compute_composite_score(
379
+ predicted_prices, current_price, confidence,
380
+ indicators, sentiment_score,
381
+ )
382
+ composite = scores["composite_score"]
383
+
384
  pred_day1 = predicted_prices[0]
385
  pred_day5 = predicted_prices[-1]
 
386
  pred_direction = "up" if pred_day5 > current_price else "down"
387
 
 
 
 
388
  signal = {
389
  "ticker": ticker,
390
  "current_price": current_price,
391
  "predicted_day1": round(pred_day1, 2),
392
  "predicted_day5": round(pred_day5, 2),
393
+ "pred_change_pct": scores["pred_change_pct"],
394
  "pred_direction": pred_direction,
395
+ "days_above_current": scores["days_above"],
396
  "confidence": confidence,
397
+ "composite_score": composite,
398
+ "market_regime": regime["regime"],
399
+ "scores": scores,
400
  }
401
 
 
402
  if ticker in state["positions"]:
403
  check = check_position(ticker, current_price)
404
  if check["action"] == "sell":
405
  result = execute_sell(ticker, current_price, check["reason"])
406
  signal["action"] = "SELL"
407
  signal["trade_result"] = result
408
+ elif composite <= sell_threshold:
409
+ result = execute_sell(ticker, current_price,
410
+ f"Bearish signal in {regime['regime']} market ({composite}/100)")
411
  signal["action"] = "SELL"
412
  signal["trade_result"] = result
413
  else:
414
  signal["action"] = "HOLD"
415
  signal["position"] = check
416
  else:
417
+ if composite >= buy_threshold and confidence >= regime["min_confidence"]:
418
+ result = execute_buy(ticker, current_price, predicted_prices, confidence)
419
+ signal["action"] = "BUY"
420
+ signal["trade_result"] = result
421
+ elif (scores["pred_change_pct"] > 2.0 and scores["days_above"] >= 3
422
+ and confidence >= 25):
423
  result = execute_buy(ticker, current_price, predicted_prices, confidence)
424
  signal["action"] = "BUY"
425
  signal["trade_result"] = result
426
  else:
427
  signal["action"] = "WAIT"
428
+ signal["reason"] = (
429
+ f"Score {composite}/100 ({regime['regime']} mode, "
430
+ f"need ≥{buy_threshold})"
431
+ )
432
 
433
+ return signal