zman35 commited on
Commit
aa9279e
Β·
verified Β·
1 Parent(s): bec1080

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -126
app.py CHANGED
@@ -3,48 +3,49 @@ import gradio as gr
3
  import pandas as pd
4
  import numpy as np
5
  import plotly.graph_objs as go
 
6
 
7
- # Disable analytics
8
  os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
9
  try:
10
  gr.analytics_enabled = False
11
  except:
12
  pass
13
 
14
- # ===========================
15
- # Strategy Presets w/ Descriptions
16
- # ===========================
17
  strategy_presets = {
18
  "Aggressive Prop Trader": {
19
  "starting_balance": 2500, "trades_min": 5, "trades_max": 10, "weeks": 12,
20
- "tp1_prob": 0.25, "tp2_prob": 0.4, "tp1_r": 1.2, "tp2_r": 2.4, "base_risk_pct": 0.015, "profit_target": None,
21
- "description": "High-frequency strategy with elevated risk and reward. Suitable for advanced traders."
 
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, "base_risk_pct": 0.01, "profit_target": None,
26
- "description": "Steady long-term strategy with lower risk per trade. Capital preservation focused."
 
27
  },
28
  "Momentum Scalper": {
29
  "starting_balance": 2500, "trades_min": 4, "trades_max": 8, "weeks": 12,
30
- "tp1_prob": 0.3, "tp2_prob": 0.35, "tp1_r": 1.0, "tp2_r": 2.2, "base_risk_pct": 0.012, "profit_target": None,
31
- "description": "Short-term strategy targeting quick price bursts. Balanced risk-to-reward."
 
32
  },
33
  "Swing Sniper": {
34
  "starting_balance": 2500, "trades_min": 2, "trades_max": 4, "weeks": 12,
35
- "tp1_prob": 0.2, "tp2_prob": 0.5, "tp1_r": 1.1, "tp2_r": 3.0, "base_risk_pct": 0.008, "profit_target": None,
36
- "description": "Precision-based entries with high reward targets. Lower frequency, high efficiency."
 
37
  },
38
  "Intraday Prop Mode": {
39
  "starting_balance": 2500, "trades_min": 3, "trades_max": 7, "weeks": 12,
40
- "tp1_prob": 0.3, "tp2_prob": 0.3, "tp1_r": 1.0, "tp2_r": 2.0, "base_risk_pct": 0.02, "profit_target": None,
41
- "description": "Balanced intraday strategy used in prop firms. Prioritizes steady growth."
 
42
  }
43
  }
44
 
45
- # ===========================
46
- # Core Simulation Function
47
- # ===========================
48
  def get_scaled_risk_pct(balance, base_risk_pct):
49
  if balance < 5000: return base_risk_pct
50
  elif balance < 10000: return base_risk_pct * 0.75
@@ -64,26 +65,25 @@ def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
64
  log = []
65
 
66
  for week in range(1, weeks + 1):
67
- if profit_target and balance >= profit_target:
68
- break
69
  week_start = balance
70
- trades = np.random.randint(trades_min, trades_max + 1)
71
- for _ in range(trades):
72
  risk_pct = get_scaled_risk_pct(balance, base_risk_pct)
73
- risk = balance * risk_pct
74
  outcome = np.random.choice(["TP1", "TP2", "SL"], p=[tp1_prob, tp2_prob, sl_prob])
75
  if outcome == "TP1":
76
- balance += risk * tp1_r
77
  tp1_hits += 1
78
  cur_win_streak += 1
79
  cur_loss_streak = 0
80
  elif outcome == "TP2":
81
- balance += risk * tp2_r
82
  tp2_hits += 1
83
  cur_win_streak += 1
84
  cur_loss_streak = 0
85
  else:
86
- balance -= risk
87
  sl_hits += 1
88
  cur_loss_streak += 1
89
  cur_win_streak = 0
@@ -91,13 +91,15 @@ def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
91
  max_loss_streak = max(max_loss_streak, cur_loss_streak)
92
  peak = max(peak, balance)
93
  drawdown = max(drawdown, (peak - balance) / peak * 100)
94
-
95
  weekly_return = (balance - week_start) / week_start * 100
96
- log.append({
97
- "Week": week, "Start Balance": round(week_start, 2),
98
- "End Balance": round(balance, 2),
99
- "Weekly Return (%)": round(weekly_return, 2)
100
- })
 
 
 
101
 
102
  summary = {
103
  "Final Balance": round(balance, 2),
@@ -106,109 +108,114 @@ def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
106
  "SL Hits": sl_hits,
107
  "Max Drawdown %": round(drawdown, 2),
108
  "Max Win Streak": max_win_streak,
109
- "Max Loss Streak": max_loss_streak
 
 
110
  }
111
-
112
- df = pd.DataFrame(log)
113
  return df, summary
114
 
115
- # ===========================
116
- # Helpers
117
- # ===========================
118
- def equity_plot(df):
119
- fig = go.Figure()
120
- fig.add_trace(go.Scatter(x=df["Week"], y=df["End Balance"],
121
- mode="lines+markers", name="Balance"))
122
- fig.update_layout(title="Equity Curve", xaxis_title="Week", yaxis_title="Balance")
123
- return fig
124
-
125
  def run_preset_strategy(style):
126
- cfg = strategy_presets[style]
127
- df, summary = simulate_tp_strategy_full(**{k: v for k, v in cfg.items() if k != "description"})
128
- return df, equity_plot(df), cfg["description"]
 
 
 
 
 
 
 
 
 
129
 
 
 
 
 
 
 
 
 
 
130
  def analytics_dashboard():
131
- results = []
132
- for name, cfg in strategy_presets.items():
133
- df, s = simulate_tp_strategy_full(**{k: v for k, v in cfg.items() if k != "description"})
134
- returns = df["End Balance"].pct_change().dropna()
135
- volatility = returns.std() * np.sqrt(52)
136
- sharpe = returns.mean() / returns.std() * np.sqrt(52) if returns.std() else 0
137
- peak = df["End Balance"].cummax()
138
- dd = (peak - df["End Balance"]) / peak
139
- max_dd = dd.max() * 100 if not dd.empty else 0
140
- score = df["End Balance"].iloc[-1] / (1 + max_dd)
141
- results.append({
142
- "Strategy": name,
143
- "Final Balance": round(df["End Balance"].iloc[-1], 2),
144
- "Sharpe": round(sharpe, 2),
145
- "Max Drawdown %": round(max_dd, 2),
146
- "EdgeCast Score": round(score, 2)
147
- })
148
- df_all = pd.DataFrame(results).sort_values("EdgeCast Score", ascending=False).reset_index(drop=True)
149
- return df_all.style.apply(lambda x: ['background-color: #d4edda' if v == x.max() and x.name == 'Sharpe' else '' for v in x], axis=0)
150
-
151
- def strategy_descriptions():
152
- rows = [{"Strategy": k, "Description": v["description"]} for k, v in strategy_presets.items()]
153
- return pd.DataFrame(rows)
154
-
155
- def risk_matrix():
156
  rows = []
157
- for k, v in strategy_presets.items():
158
- rows.append({
159
- "Strategy": k,
160
- "Risk %": v["base_risk_pct"],
161
- "TP1 R": v["tp1_r"],
162
- "TP2 R": v["tp2_r"],
163
- "TP1 %": v["tp1_prob"],
164
- "TP2 %": v["tp2_prob"]
165
- })
166
- return pd.DataFrame(rows)
167
-
168
- # ===========================
169
- # UI Setup
170
- # ===========================
171
- preset_tab = gr.Interface(fn=run_preset_strategy,
172
- inputs=gr.Dropdown(list(strategy_presets.keys()), label="Select Strategy"),
173
- outputs=["dataframe", gr.Plot(), gr.Text()],
174
- title="🎯 Preset Mode"
175
- )
176
-
177
- manual_tab = gr.Interface(fn=simulate_tp_strategy_full,
178
- inputs=[
179
- gr.Slider(100, 20000, 2500, label="Start Balance"),
180
- gr.Slider(1, 10, 3, label="Trades Min"),
181
- gr.Slider(1, 15, 7, label="Trades Max"),
182
- gr.Slider(1, 52, 12, label="Weeks"),
183
- gr.Slider(0, 1, 0.3, step=0.05, label="TP1 %"),
184
- gr.Slider(0, 1, 0.3, step=0.05, label="TP2 %"),
185
- gr.Slider(0.1, 5, 1.0, step=0.1, label="TP1 R"),
186
- gr.Slider(0.1, 10, 2.0, step=0.1, label="TP2 R"),
187
- gr.Slider(0.001, 0.05, 0.01, step=0.001, label="Risk %"),
188
- gr.Slider(0, 100000, 0, step=500, label="Profit Target πŸ’°")
189
- ],
190
- outputs=["dataframe", "json"],
191
- title="πŸ› οΈ Manual Config"
192
- )
193
 
194
- battle_tab = gr.Interface(
195
- fn=lambda a, b: simulate_tp_strategy_full(**{k: v for k, v in strategy_presets[a].items() if k != "description"})[0].merge(
196
- simulate_tp_strategy_full(**{k: v for k, v in strategy_presets[b].items() if k != "description"})[0],
197
- on="Week", suffixes=(f" ({a})", f" ({b})")
198
- ),
199
- inputs=[
200
- gr.Dropdown(list(strategy_presets.keys()), label="Strategy 1"),
201
- gr.Dropdown(list(strategy_presets.keys()), label="Strategy 2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  ],
203
- outputs="dataframe",
204
- title="πŸ₯Š Strategy Battle"
205
  )
206
 
207
- analytics_tab = gr.Interface(fn=analytics_dashboard, inputs=[], outputs="dataframe", title="πŸ“Š Analytics")
208
- desc_tab = gr.Interface(fn=strategy_descriptions, inputs=[], outputs="dataframe", title="πŸ“˜ Descriptions")
209
- risk_tab = gr.Interface(fn=risk_matrix, inputs=[], outputs="dataframe", title="🧠 Risk Matrix Visualizer")
210
-
211
- gr.TabbedInterface(
212
- [preset_tab, manual_tab, battle_tab, analytics_tab, desc_tab, risk_tab],
213
- tab_names=["Preset", "Manual", "Battle", "Analytics", "Descriptions", "Risk Matrix"]
214
- ).launch()
 
3
  import pandas as pd
4
  import numpy as np
5
  import plotly.graph_objs as go
6
+ import plotly.express as px
7
 
8
+ # Disable Gradio analytics
9
  os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
10
  try:
11
  gr.analytics_enabled = False
12
  except:
13
  pass
14
 
15
+ # Strategy Presets
 
 
16
  strategy_presets = {
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
+ "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
+ "description": "Lower frequency, prioritizes preservation and steady returns."
28
  },
29
  "Momentum Scalper": {
30
  "starting_balance": 2500, "trades_min": 4, "trades_max": 8, "weeks": 12,
31
+ "tp1_prob": 0.3, "tp2_prob": 0.35, "tp1_r": 1.0, "tp2_r": 2.2,
32
+ "base_risk_pct": 0.012, "profit_target": None,
33
+ "description": "Intraday momentum strategy for fast-paced trading windows."
34
  },
35
  "Swing Sniper": {
36
  "starting_balance": 2500, "trades_min": 2, "trades_max": 4, "weeks": 12,
37
+ "tp1_prob": 0.2, "tp2_prob": 0.5, "tp1_r": 1.1, "tp2_r": 3.0,
38
+ "base_risk_pct": 0.008, "profit_target": None,
39
+ "description": "Selective entries with high RR setups. Less frequent."
40
  },
41
  "Intraday Prop Mode": {
42
  "starting_balance": 2500, "trades_min": 3, "trades_max": 7, "weeks": 12,
43
+ "tp1_prob": 0.3, "tp2_prob": 0.3, "tp1_r": 1.0, "tp2_r": 2.0,
44
+ "base_risk_pct": 0.02, "profit_target": None,
45
+ "description": "Intraday consistency with a balanced reward profile."
46
  }
47
  }
48
 
 
 
 
49
  def get_scaled_risk_pct(balance, base_risk_pct):
50
  if balance < 5000: return base_risk_pct
51
  elif balance < 10000: return base_risk_pct * 0.75
 
65
  log = []
66
 
67
  for week in range(1, weeks + 1):
68
+ if profit_target and balance >= profit_target: break
 
69
  week_start = balance
70
+ num_trades = np.random.randint(trades_min, trades_max + 1)
71
+ for _ in range(num_trades):
72
  risk_pct = get_scaled_risk_pct(balance, base_risk_pct)
73
+ risk_amount = balance * risk_pct
74
  outcome = np.random.choice(["TP1", "TP2", "SL"], p=[tp1_prob, tp2_prob, sl_prob])
75
  if outcome == "TP1":
76
+ balance += risk_amount * tp1_r
77
  tp1_hits += 1
78
  cur_win_streak += 1
79
  cur_loss_streak = 0
80
  elif outcome == "TP2":
81
+ balance += risk_amount * tp2_r
82
  tp2_hits += 1
83
  cur_win_streak += 1
84
  cur_loss_streak = 0
85
  else:
86
+ balance -= risk_amount
87
  sl_hits += 1
88
  cur_loss_streak += 1
89
  cur_win_streak = 0
 
91
  max_loss_streak = max(max_loss_streak, cur_loss_streak)
92
  peak = max(peak, balance)
93
  drawdown = max(drawdown, (peak - balance) / peak * 100)
 
94
  weekly_return = (balance - week_start) / week_start * 100
95
+ log.append({"Week": week, "Start Balance": round(week_start, 2),
96
+ "End Balance": round(balance, 2), "Weekly Return (%)": round(weekly_return, 2)})
97
+
98
+ df = pd.DataFrame(log)
99
+ returns = df["End Balance"].pct_change().dropna()
100
+ volatility = returns.std() * np.sqrt(52)
101
+ sharpe_ratio = returns.mean() / returns.std() * np.sqrt(52) if returns.std() > 0 else 0
102
+ score = balance / (1 + drawdown)
103
 
104
  summary = {
105
  "Final Balance": round(balance, 2),
 
108
  "SL Hits": sl_hits,
109
  "Max Drawdown %": round(drawdown, 2),
110
  "Max Win Streak": max_win_streak,
111
+ "Max Loss Streak": max_loss_streak,
112
+ "Sharpe Ratio": round(sharpe_ratio, 2),
113
+ "EdgeCast Score": round(score, 2)
114
  }
 
 
115
  return df, summary
116
 
117
+ # πŸ”˜ TAB: Preset Strategy
 
 
 
 
 
 
 
 
 
118
  def run_preset_strategy(style):
119
+ config = strategy_presets[style]
120
+ df, summary = simulate_tp_strategy_full(**{k: config[k] for k in config if k != "description"})
121
+ return df, summary, config["description"]
122
+
123
+ # πŸ”˜ TAB: Battle
124
+ def battle_strategies(style1, style2):
125
+ df1, s1 = simulate_tp_strategy_full(**strategy_presets[style1])
126
+ df2, s2 = simulate_tp_strategy_full(**strategy_presets[style2])
127
+ s1["Strategy"] = style1
128
+ s2["Strategy"] = style2
129
+ df_compare = pd.DataFrame([s1, s2])
130
+ df_compare = df_compare[["Strategy"] + [col for col in s1 if col != "Strategy"]]
131
 
132
+ winner = df_compare.loc[df_compare["EdgeCast Score"].idxmax(), "Strategy"]
133
+
134
+ fig = go.Figure()
135
+ fig.add_trace(go.Scatter(x=df1["Week"], y=df1["End Balance"], name=style1))
136
+ fig.add_trace(go.Scatter(x=df2["Week"], y=df2["End Balance"], name=style2))
137
+ fig.update_layout(title=f"πŸ“Š Battle Mode – Winner: {winner} πŸ₯‡", xaxis_title="Week", yaxis_title="Balance")
138
+ return df_compare.style.apply(lambda row: ['font-weight: bold; background-color: #d4edda' if row.Strategy == winner else '' for _ in row], axis=1), fig
139
+
140
+ # πŸ”˜ TAB: Analytics Leaderboard
141
  def analytics_dashboard():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  rows = []
143
+ for name, config in strategy_presets.items():
144
+ _, s = simulate_tp_strategy_full(**config)
145
+ s["Strategy"] = name
146
+ rows.append(s)
147
+ df = pd.DataFrame(rows)
148
+ return df.sort_values("EdgeCast Score", ascending=False).reset_index(drop=True)
149
+
150
+ # πŸ”˜ TAB: Descriptions
151
+ def show_descriptions():
152
+ descs = [{"Strategy": k, "Description": v["description"]} for k, v in strategy_presets.items()]
153
+ return pd.DataFrame(descs)
154
+
155
+ # πŸ”˜ TAB: Risk Matrix Heatmap
156
+ def generate_risk_matrix():
157
+ strat_names = list(strategy_presets.keys())
158
+ scores = {}
159
+ for name in strat_names:
160
+ _, s = simulate_tp_strategy_full(**strategy_presets[name])
161
+ scores[name] = s["EdgeCast Score"]
162
+ heatmap_data = np.zeros((len(strat_names), len(strat_names)))
163
+ for i, a in enumerate(strat_names):
164
+ for j, b in enumerate(strat_names):
165
+ heatmap_data[i, j] = abs(scores[a] - scores[b])
166
+ fig = px.imshow(heatmap_data,
167
+ x=strat_names, y=strat_names, color_continuous_scale="RdYlGn_r",
168
+ labels=dict(color="Score Ξ”"),
169
+ title="🧠 Risk Matrix (Strategy Divergence)")
170
+ fig.update_traces(hovertemplate="From %{y} β†’ %{x}: Ξ”=%{z}<extra></extra>")
171
+ return fig
 
 
 
 
 
 
 
172
 
173
+ # βœ… Gradio App Tabs
174
+ app = gr.TabbedInterface(
175
+ interface_list=[
176
+ gr.Interface(fn=run_preset_strategy,
177
+ inputs=gr.Dropdown(choices=list(strategy_presets.keys()), label="Select Strategy"),
178
+ outputs=["dataframe", "json", "text"],
179
+ title="🎯 Preset Mode"),
180
+
181
+ gr.Interface(fn=simulate_tp_strategy_full,
182
+ inputs=[
183
+ gr.Slider(100, 20000, 2500, label="Start Balance"),
184
+ gr.Slider(1, 10, 3, label="Trades Min"),
185
+ gr.Slider(1, 15, 7, label="Trades Max"),
186
+ gr.Slider(1, 52, 12, label="Weeks"),
187
+ gr.Slider(0, 1, 0.3, step=0.05, label="TP1 %"),
188
+ gr.Slider(0, 1, 0.3, step=0.05, label="TP2 %"),
189
+ gr.Slider(0.1, 5.0, 1.0, step=0.1, label="TP1 R"),
190
+ gr.Slider(0.1, 10.0, 2.0, step=0.1, label="TP2 R"),
191
+ gr.Slider(0.001, 0.05, 0.01, step=0.001, label="Risk %"),
192
+ gr.Slider(0, 100000, 0, step=500, label="Profit Target πŸ’°")
193
+ ],
194
+ outputs=["dataframe", "json"],
195
+ title="πŸ› οΈ Manual Config"),
196
+
197
+ gr.Interface(fn=battle_strategies,
198
+ inputs=[
199
+ gr.Dropdown(choices=list(strategy_presets.keys()), label="Strategy 1"),
200
+ gr.Dropdown(choices=list(strategy_presets.keys()), label="Strategy 2")
201
+ ],
202
+ outputs=["dataframe", gr.Plot()],
203
+ title="πŸ₯Š Battle Mode"),
204
+
205
+ gr.Interface(fn=analytics_dashboard,
206
+ inputs=[], outputs="dataframe",
207
+ title="πŸ“Š Analytics Leaderboard"),
208
+
209
+ gr.Interface(fn=show_descriptions,
210
+ inputs=[], outputs="dataframe",
211
+ title="πŸ“˜ Strategy Descriptions"),
212
+
213
+ gr.Interface(fn=generate_risk_matrix,
214
+ inputs=[], outputs=gr.Plot(),
215
+ title="πŸ”¬ Risk Matrix")
216
  ],
217
+ tab_names=["Preset", "Manual", "Battle", "Analytics", "Descriptions", "Risk Matrix"],
218
+ title="EdgeCast – Strategy Simulation Suite"
219
  )
220
 
221
+ app.launch()