zman35 commited on
Commit
69918e4
Β·
verified Β·
1 Parent(s): da7978c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -199
app.py CHANGED
@@ -11,53 +11,47 @@ try:
11
  except:
12
  pass
13
 
14
- # πŸ” Strategy Presets
15
- strategy_presets = {
16
- "Aggressive Prop Trader": {
17
- "starting_balance": 2500, "trades_min": 5, "trades_max": 10, "weeks": 12,
18
- "tp1_prob": 0.25, "tp2_prob": 0.4, "tp1_r": 1.2, "tp2_r": 2.4,
19
- "base_risk_pct": 0.015, "profit_target": None,
20
- "fatigue": 0.0, "trump_vol": 0.0,
21
- "description": "High-frequency, high-risk with strong upside potential."
22
- },
23
- "Conservative Swing Trader": {
24
- "starting_balance": 2500, "trades_min": 2, "trades_max": 5, "weeks": 12,
25
- "tp1_prob": 0.35, "tp2_prob": 0.25, "tp1_r": 0.9, "tp2_r": 1.8,
26
- "base_risk_pct": 0.01, "profit_target": None,
27
- "fatigue": 0.0, "trump_vol": 0.0,
28
- "description": "Lower frequency, prioritizes preservation and steady returns."
29
- },
30
- "Momentum Scalper": {
31
- "starting_balance": 2500, "trades_min": 4, "trades_max": 8, "weeks": 12,
32
- "tp1_prob": 0.3, "tp2_prob": 0.35, "tp1_r": 1.0, "tp2_r": 2.2,
33
- "base_risk_pct": 0.012, "profit_target": None,
34
- "fatigue": 0.0, "trump_vol": 0.0,
35
- "description": "Intraday momentum strategy for fast-paced trading windows."
36
- },
37
- "Swing Sniper": {
38
- "starting_balance": 2500, "trades_min": 2, "trades_max": 4, "weeks": 12,
39
- "tp1_prob": 0.2, "tp2_prob": 0.5, "tp1_r": 1.1, "tp2_r": 3.0,
40
- "base_risk_pct": 0.008, "profit_target": None,
41
- "fatigue": 0.0, "trump_vol": 0.0,
42
- "description": "Selective entries with high RR setups. Less frequent."
43
- },
44
- "Intraday Prop Mode": {
45
- "starting_balance": 2500, "trades_min": 3, "trades_max": 7, "weeks": 12,
46
- "tp1_prob": 0.3, "tp2_prob": 0.3, "tp1_r": 1.0, "tp2_r": 2.0,
47
- "base_risk_pct": 0.02, "profit_target": None,
48
- "fatigue": 0.0, "trump_vol": 0.0,
49
- "description": "Intraday consistency with a balanced reward profile."
 
 
50
  }
51
- }
52
- def get_scaled_risk_pct(balance, base_risk_pct):
53
- if balance < 5000:
54
- return base_risk_pct
55
- elif balance < 10000:
56
- return base_risk_pct * 0.75
57
- elif balance < 20000:
58
- return base_risk_pct * 0.5
59
- else:
60
- return base_risk_pct * 0.25
61
 
62
  def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
63
  tp1_prob, tp2_prob, tp1_r, tp2_r, base_risk_pct,
@@ -74,19 +68,19 @@ def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
74
  cur_win_streak = cur_loss_streak = 0
75
  log = []
76
 
77
- fatigue_multiplier = 1.0 - fatigue * 0.4 # Reduce reward at high fatigue
78
- trump_vol_factor = np.random.normal(1.0, 0.2 * trump_vol) # Adds chaos
79
 
80
  for week in range(1, weeks + 1):
81
- if profit_target and balance >= profit_target: break
 
82
  week_start = balance
83
  num_trades = np.random.randint(trades_min, trades_max + 1)
84
  for _ in range(num_trades):
85
- risk_pct = get_scaled_risk_pct(balance, base_risk_pct)
86
- risk_amount = balance * risk_pct * np.random.uniform(0.9, 1.1) # Risk % w/ some variability
87
- risk_amount *= trump_vol_factor # 🟠 Vol boost
88
 
89
- # Fatigue loss streak logic
90
  if fatigue > 0.6 and cur_loss_streak >= 3 and np.random.rand() < fatigue * 0.25:
91
  outcome = "SL"
92
  else:
@@ -137,66 +131,14 @@ def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
137
  "Sharpe Ratio": round(sharpe_ratio, 2),
138
  "EdgeCast Score": round(score, 2)
139
  }
 
140
  return df, summary
141
- # πŸ“ˆ Plot
142
- def equity_curve_plot(df, label="Equity Curve"):
143
- fig = go.Figure()
144
- fig.add_trace(go.Scatter(x=df["Week"], y=df["End Balance"], mode='lines+markers', name=label))
145
- fig.update_layout(title=f'πŸ“ˆ {label}', xaxis_title='Week', yaxis_title='Balance ($)', height=400)
146
- return fig
147
-
148
- # 🎯 Preset Tab
149
- def run_preset_strategy(style, fatigue=0.0, trump_vol=0.0):
150
- if style not in strategy_presets:
151
- return pd.DataFrame(), {}, go.Figure(), "Please select a strategy to begin."
152
- config = strategy_presets[style]
153
- df, summary = simulate_tp_strategy_full(
154
- config["starting_balance"], config["trades_min"], config["trades_max"], config["weeks"],
155
- config["tp1_prob"], config["tp2_prob"], config["tp1_r"], config["tp2_r"],
156
- config["base_risk_pct"], config["profit_target"],
157
- fatigue=fatigue, trump_vol=trump_vol
158
- )
159
- return df, summary, equity_curve_plot(df, style), config["description"]
160
-
161
- # πŸ› οΈ Manual Tab
162
- def run_manual_sim(starting_balance, trades_min, trades_max, weeks,
163
- tp1_prob, tp2_prob, tp1_r, tp2_r, base_risk_pct, profit_target,
164
- fatigue, trump_vol):
165
- df, summary = simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
166
- tp1_prob, tp2_prob, tp1_r, tp2_r, base_risk_pct,
167
- profit_target, fatigue, trump_vol)
168
- chart = equity_curve_plot(df, "Manual Config")
169
- return df, summary, chart
170
-
171
- # βš”οΈ Manual Battle Mode (Dual Sim)
172
- def dual_manual_battle(
173
- sb1, tmin1, tmax1, w1, tp1a, tp2a, r1a, r2a, risk1, pt1, fat1, trump1,
174
- sb2, tmin2, tmax2, w2, tp1b, tp2b, r1b, r2b, risk2, pt2, fat2, trump2
175
- ):
176
- df1, s1 = simulate_tp_strategy_full(sb1, tmin1, tmax1, w1, tp1a, tp2a, r1a, r2a, risk1, pt1, fat1, trump1)
177
- df2, s2 = simulate_tp_strategy_full(sb2, tmin2, tmax2, w2, tp1b, tp2b, r1b, r2b, risk2, pt2, fat2, trump2)
178
-
179
- s1["Strategy"] = "Manual A"
180
- s2["Strategy"] = "Manual B"
181
-
182
- comparison_df = pd.DataFrame([s1, s2])
183
- comparison_df = comparison_df[["Strategy", "Final Balance", "Sharpe Ratio", "EdgeCast Score", "Max Drawdown %"]]
184
-
185
- # πŸ† Winners
186
- for col in ["Final Balance", "Sharpe Ratio", "EdgeCast Score"]:
187
- best_val = comparison_df[col].astype(float).max()
188
- comparison_df[col] = [
189
- f"{val} πŸ†" if float(val) == best_val else f"{val}" for val in comparison_df[col]
190
- ]
191
-
192
- # Chart
193
- fig = go.Figure()
194
- fig.add_trace(go.Scatter(x=df1["Week"], y=df1["End Balance"], name="Manual A"))
195
- fig.add_trace(go.Scatter(x=df2["Week"], y=df2["End Balance"], name="Manual B"))
196
- fig.update_layout(title="βš”οΈ Manual Strategy Battle", xaxis_title="Week", yaxis_title="Balance")
197
-
198
- return comparison_df, fig
199
- # πŸ“Š Leaderboard Tab
200
  def analytics_dashboard(rank_by="EdgeCast Score"):
201
  results = []
202
  for name, config in strategy_presets.items():
@@ -206,7 +148,6 @@ def analytics_dashboard(rank_by="EdgeCast Score"):
206
 
207
  df = pd.DataFrame(results)
208
 
209
- # Get numeric winners before formatting
210
  winner_vals = {
211
  "Final Balance": df["Final Balance"].max(),
212
  "Sharpe Ratio": df["Sharpe Ratio"].max(),
@@ -214,29 +155,15 @@ def analytics_dashboard(rank_by="EdgeCast Score"):
214
  "Max Drawdown %": df["Max Drawdown %"].min()
215
  }
216
 
217
- # Sort leaderboard by selected metric
218
  ascending = rank_by == "Max Drawdown %"
219
  df = df.sort_values(rank_by, ascending=ascending).reset_index(drop=True)
220
-
221
- # Rank column
222
  df.insert(0, "πŸ… Rank", [f"#{i+1}" for i in df.index])
223
 
224
- # πŸ† Emoji highlights
225
  for col in winner_vals:
226
  df[col] = df[col].apply(lambda x: f"{round(x, 2)} πŸ†" if x == winner_vals[col] else f"{round(x, 2)}")
227
 
228
  return df[["πŸ… Rank", "Strategy", "Final Balance", "Sharpe Ratio", "EdgeCast Score", "Max Drawdown %"]]
229
 
230
-
231
- # πŸ“˜ Description Tab
232
- def show_descriptions():
233
- return pd.DataFrame([
234
- {"Strategy": name, "Description": config["description"]}
235
- for name, config in strategy_presets.items()
236
- ])
237
-
238
-
239
- # πŸ”¬ Risk Matrix Heatmap
240
  def generate_risk_matrix():
241
  names = list(strategy_presets.keys())
242
  scores = {
@@ -261,58 +188,22 @@ def generate_risk_matrix():
261
  hovertemplate="<b>%{y}</b> vs <b>%{x}</b><br>Ξ” Score: %{z:.2f}<extra></extra>"
262
  )
263
  return fig
264
-
265
-
266
- # πŸ₯Š Battle Strategies (Preset vs Preset)
267
- def battle_strategies(style1, style2):
268
- if style1 == "None" or style2 == "None":
269
- return pd.DataFrame([{"⚠️ Error": "Please select two valid strategies."}]), go.Figure()
270
-
271
- if style1 == style2:
272
- return pd.DataFrame([{"⚠️ Error": "Please select two different strategies."}]), go.Figure()
273
-
274
- try:
275
- df1, s1 = simulate_tp_strategy_full(**{k: v for k, v in strategy_presets[style1].items() if k != "description"})
276
- df2, s2 = simulate_tp_strategy_full(**{k: v for k, v in strategy_presets[style2].items() if k != "description"})
277
-
278
- s1["Strategy"] = style1
279
- s2["Strategy"] = style2
280
-
281
- comparison_df = pd.DataFrame([s1, s2])
282
- comparison_df = comparison_df[["Strategy", "Final Balance", "Sharpe Ratio", "EdgeCast Score", "Max Drawdown %"]]
283
-
284
- for col in ["Final Balance", "Sharpe Ratio", "EdgeCast Score"]:
285
- best_val = comparison_df[col].astype(float).max()
286
- comparison_df[col] = [
287
- f"{val} πŸ†" if float(val) == best_val else val for val in comparison_df[col]
288
- ]
289
-
290
- fig = go.Figure()
291
- fig.add_trace(go.Scatter(x=df1["Week"], y=df1["End Balance"], name=style1))
292
- fig.add_trace(go.Scatter(x=df2["Week"], y=df2["End Balance"], name=style2))
293
- fig.update_layout(title=f"πŸ₯Š {style1} vs {style2}", xaxis_title="Week", yaxis_title="Balance")
294
-
295
- return comparison_df, fig
296
-
297
- except Exception as e:
298
- return pd.DataFrame([{"Error": str(e)}]), go.Figure()
299
-
300
- # πŸš€ App UI Launch
301
  app = gr.TabbedInterface(
302
  interface_list=[
303
- # 🎯 Preset Mode
 
304
  gr.Interface(
305
  fn=run_preset_strategy,
306
- inputs=gr.Dropdown(
307
- choices=["None"] + list(strategy_presets.keys()),
308
- value="None",
309
- label="Select Strategy"
310
- ),
311
  outputs=["dataframe", "json", gr.Plot(), "text"],
312
- title="🎯 Preset Mode"
313
  ),
314
 
315
- # πŸ› οΈ Manual Config
316
  gr.Interface(
317
  fn=run_manual_sim,
318
  inputs=[
@@ -330,32 +221,13 @@ app = gr.TabbedInterface(
330
  gr.Slider(0, 1, 0.0, step=0.1, label="Trump Volatility Index")
331
  ],
332
  outputs=["dataframe", "json", gr.Plot()],
333
- title="πŸ› οΈ Manual Config"
334
  ),
335
 
336
- # πŸ₯Š Battle Mode – Preset
337
- gr.Interface(
338
- fn=battle_strategies,
339
- inputs=[
340
- gr.Dropdown(choices=["None"] + list(strategy_presets.keys()), value="None", label="Strategy 1"),
341
- gr.Dropdown(choices=["None"] + list(strategy_presets.keys()), value="None", label="Strategy 2")
342
- ],
343
- outputs=["dataframe", gr.Plot()],
344
- title="πŸ₯Š Battle Mode"
345
- ),
346
-
347
- # πŸ§ͺ Manual Battle Mode
348
- gr.Interface(
349
- fn=dual_manual_battle,
350
- inputs=[
351
- gr.Textbox(label="Manual Config A (JSON format)"),
352
- gr.Textbox(label="Manual Config B (JSON format)")
353
- ],
354
- outputs=["dataframe", gr.Plot()],
355
- title="πŸ§ͺ Manual Battle Mode"
356
- ),
357
 
358
- # πŸ“Š Analytics Leaderboard
359
  gr.Interface(
360
  fn=analytics_dashboard,
361
  inputs=gr.Dropdown(
@@ -364,7 +236,7 @@ app = gr.TabbedInterface(
364
  label="Sort leaderboard by:"
365
  ),
366
  outputs="dataframe",
367
- title="πŸ“Š Analytics Leaderboard"
368
  ),
369
 
370
  # πŸ“˜ Strategy Descriptions
@@ -374,14 +246,14 @@ app = gr.TabbedInterface(
374
  title="πŸ“˜ Strategy Descriptions"
375
  ),
376
 
377
- # πŸ”¬ Risk Matrix Heatmap
378
  gr.Interface(
379
  fn=generate_risk_matrix,
380
  inputs=[], outputs=gr.Plot(),
381
- title="πŸ”¬ Risk Matrix"
382
  )
383
  ],
384
- tab_names=["Preset", "Manual", "Battle", "Manual Battle", "Analytics", "Descriptions", "Risk Matrix"],
385
  title="EdgeCast – Strategy Simulation Suite"
386
  )
387
 
 
11
  except:
12
  pass
13
 
14
+ # === PART 1: PRESETS + SIMULATION ENGINE ===
15
+ def get_strategy_presets():
16
+ return {
17
+ "Aggressive Prop Trader": {
18
+ "starting_balance": 2500, "trades_min": 5, "trades_max": 10, "weeks": 12,
19
+ "tp1_prob": 0.25, "tp2_prob": 0.4, "tp1_r": 1.2, "tp2_r": 2.4,
20
+ "base_risk_pct": 0.015, "profit_target": None,
21
+ "fatigue": 0.0, "trump_vol": 0.0,
22
+ "description": "High-frequency, high-risk with strong upside potential."
23
+ },
24
+ "Conservative Swing Trader": {
25
+ "starting_balance": 2500, "trades_min": 2, "trades_max": 5, "weeks": 12,
26
+ "tp1_prob": 0.35, "tp2_prob": 0.25, "tp1_r": 0.9, "tp2_r": 1.8,
27
+ "base_risk_pct": 0.01, "profit_target": None,
28
+ "fatigue": 0.0, "trump_vol": 0.0,
29
+ "description": "Lower frequency, prioritizes preservation and steady returns."
30
+ },
31
+ "Momentum Scalper": {
32
+ "starting_balance": 2500, "trades_min": 4, "trades_max": 8, "weeks": 12,
33
+ "tp1_prob": 0.3, "tp2_prob": 0.35, "tp1_r": 1.0, "tp2_r": 2.2,
34
+ "base_risk_pct": 0.012, "profit_target": None,
35
+ "fatigue": 0.0, "trump_vol": 0.0,
36
+ "description": "Intraday momentum strategy for fast-paced trading windows."
37
+ },
38
+ "Swing Sniper": {
39
+ "starting_balance": 2500, "trades_min": 2, "trades_max": 4, "weeks": 12,
40
+ "tp1_prob": 0.2, "tp2_prob": 0.5, "tp1_r": 1.1, "tp2_r": 3.0,
41
+ "base_risk_pct": 0.008, "profit_target": None,
42
+ "fatigue": 0.0, "trump_vol": 0.0,
43
+ "description": "Selective entries with high RR setups. Less frequent."
44
+ },
45
+ "Intraday Prop Mode": {
46
+ "starting_balance": 2500, "trades_min": 3, "trades_max": 7, "weeks": 12,
47
+ "tp1_prob": 0.3, "tp2_prob": 0.3, "tp1_r": 1.0, "tp2_r": 2.0,
48
+ "base_risk_pct": 0.02, "profit_target": None,
49
+ "fatigue": 0.0, "trump_vol": 0.0,
50
+ "description": "Intraday consistency with a balanced reward profile."
51
+ }
52
  }
53
+
54
+ strategy_presets = get_strategy_presets()
 
 
 
 
 
 
 
 
55
 
56
  def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
57
  tp1_prob, tp2_prob, tp1_r, tp2_r, base_risk_pct,
 
68
  cur_win_streak = cur_loss_streak = 0
69
  log = []
70
 
71
+ fatigue_multiplier = 1.0 - fatigue * 0.4
72
+ trump_vol_factor = np.random.normal(1.0, 0.2 * trump_vol)
73
 
74
  for week in range(1, weeks + 1):
75
+ if profit_target and balance >= profit_target:
76
+ break
77
  week_start = balance
78
  num_trades = np.random.randint(trades_min, trades_max + 1)
79
  for _ in range(num_trades):
80
+ risk_pct = base_risk_pct
81
+ risk_amount = balance * risk_pct * np.random.uniform(0.9, 1.1)
82
+ risk_amount *= trump_vol_factor
83
 
 
84
  if fatigue > 0.6 and cur_loss_streak >= 3 and np.random.rand() < fatigue * 0.25:
85
  outcome = "SL"
86
  else:
 
131
  "Sharpe Ratio": round(sharpe_ratio, 2),
132
  "EdgeCast Score": round(score, 2)
133
  }
134
+
135
  return df, summary
136
+ def show_descriptions():
137
+ return pd.DataFrame([
138
+ {"Strategy": name, "Description": config["description"]}
139
+ for name, config in strategy_presets.items()
140
+ ])
141
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  def analytics_dashboard(rank_by="EdgeCast Score"):
143
  results = []
144
  for name, config in strategy_presets.items():
 
148
 
149
  df = pd.DataFrame(results)
150
 
 
151
  winner_vals = {
152
  "Final Balance": df["Final Balance"].max(),
153
  "Sharpe Ratio": df["Sharpe Ratio"].max(),
 
155
  "Max Drawdown %": df["Max Drawdown %"].min()
156
  }
157
 
 
158
  ascending = rank_by == "Max Drawdown %"
159
  df = df.sort_values(rank_by, ascending=ascending).reset_index(drop=True)
 
 
160
  df.insert(0, "πŸ… Rank", [f"#{i+1}" for i in df.index])
161
 
 
162
  for col in winner_vals:
163
  df[col] = df[col].apply(lambda x: f"{round(x, 2)} πŸ†" if x == winner_vals[col] else f"{round(x, 2)}")
164
 
165
  return df[["πŸ… Rank", "Strategy", "Final Balance", "Sharpe Ratio", "EdgeCast Score", "Max Drawdown %"]]
166
 
 
 
 
 
 
 
 
 
 
 
167
  def generate_risk_matrix():
168
  names = list(strategy_presets.keys())
169
  scores = {
 
188
  hovertemplate="<b>%{y}</b> vs <b>%{x}</b><br>Ξ” Score: %{z:.2f}<extra></extra>"
189
  )
190
  return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  app = gr.TabbedInterface(
192
  interface_list=[
193
+
194
+ # 🎯 Preset Strategy Tab
195
  gr.Interface(
196
  fn=run_preset_strategy,
197
+ inputs=[
198
+ gr.Dropdown(choices=list(strategy_presets.keys()), label="Select Strategy"),
199
+ gr.Slider(0, 1, 0.0, step=0.1, label="Fatigue Level"),
200
+ gr.Slider(0, 1, 0.0, step=0.1, label="Trump Volatility Index")
201
+ ],
202
  outputs=["dataframe", "json", gr.Plot(), "text"],
203
+ title="🎯 Preset Strategy Mode"
204
  ),
205
 
206
+ # πŸ› οΈ Manual Config Tab (Single Simulation)
207
  gr.Interface(
208
  fn=run_manual_sim,
209
  inputs=[
 
221
  gr.Slider(0, 1, 0.0, step=0.1, label="Trump Volatility Index")
222
  ],
223
  outputs=["dataframe", "json", gr.Plot()],
224
+ title="πŸ› οΈ Manual Config Mode"
225
  ),
226
 
227
+ # πŸ§ͺ Manual Battle Mode (Dual Sliders + Histogram)
228
+ get_manual_battle_interface(),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
+ # πŸ“Š Leaderboard
231
  gr.Interface(
232
  fn=analytics_dashboard,
233
  inputs=gr.Dropdown(
 
236
  label="Sort leaderboard by:"
237
  ),
238
  outputs="dataframe",
239
+ title="πŸ“Š Strategy Leaderboard"
240
  ),
241
 
242
  # πŸ“˜ Strategy Descriptions
 
246
  title="πŸ“˜ Strategy Descriptions"
247
  ),
248
 
249
+ # πŸ”¬ Risk Matrix
250
  gr.Interface(
251
  fn=generate_risk_matrix,
252
  inputs=[], outputs=gr.Plot(),
253
+ title="πŸ”¬ Risk Matrix Heatmap"
254
  )
255
  ],
256
+ tab_names=["Preset", "Manual", "Battle", "Leaderboard", "Descriptions", "Risk Matrix"],
257
  title="EdgeCast – Strategy Simulation Suite"
258
  )
259