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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -121
app.py CHANGED
@@ -4,44 +4,47 @@ import pandas as pd
4
  import numpy as np
5
  import plotly.graph_objs as go
6
 
 
7
  os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
8
- try: gr.analytics_enabled = False
9
- except: pass
10
-
11
- # πŸ“˜ STRATEGY PRESETS
 
 
 
 
12
  strategy_presets = {
13
  "Aggressive Prop Trader": {
14
  "starting_balance": 2500, "trades_min": 5, "trades_max": 10, "weeks": 12,
15
- "tp1_prob": 0.25, "tp2_prob": 0.4, "tp1_r": 1.2, "tp2_r": 2.4,
16
- "base_risk_pct": 0.015, "profit_target": None,
17
- "description": "Aggressive Prop Trader – High-frequency with elevated risk. Seeks large returns on more trades."
18
  },
19
  "Conservative Swing Trader": {
20
  "starting_balance": 2500, "trades_min": 2, "trades_max": 5, "weeks": 12,
21
- "tp1_prob": 0.35, "tp2_prob": 0.25, "tp1_r": 0.9, "tp2_r": 1.8,
22
- "base_risk_pct": 0.01, "profit_target": None,
23
- "description": "Conservative Swing Trader – Lower frequency & risk. Prioritizes stability and capital preservation."
24
  },
25
  "Momentum Scalper": {
26
  "starting_balance": 2500, "trades_min": 4, "trades_max": 8, "weeks": 12,
27
- "tp1_prob": 0.3, "tp2_prob": 0.35, "tp1_r": 1.0, "tp2_r": 2.2,
28
- "base_risk_pct": 0.012, "profit_target": None,
29
- "description": "Momentum Scalper – Fast-paced intraday with micro-trend capture. Moderate risk and trade count."
30
  },
31
  "Swing Sniper": {
32
  "starting_balance": 2500, "trades_min": 2, "trades_max": 4, "weeks": 12,
33
- "tp1_prob": 0.2, "tp2_prob": 0.5, "tp1_r": 1.1, "tp2_r": 3.0,
34
- "base_risk_pct": 0.008, "profit_target": None,
35
- "description": "Swing Sniper – Patient setup sniper with high reward setups. Low frequency, higher R-multiple."
36
  },
37
  "Intraday Prop Mode": {
38
  "starting_balance": 2500, "trades_min": 3, "trades_max": 7, "weeks": 12,
39
- "tp1_prob": 0.3, "tp2_prob": 0.3, "tp1_r": 1.0, "tp2_r": 2.0,
40
- "base_risk_pct": 0.02, "profit_target": None,
41
- "description": "Intraday Prop Mode – Balanced risk & frequency. Good for consistent engagement without extremes."
42
  }
43
  }
44
 
 
 
 
45
  def get_scaled_risk_pct(balance, base_risk_pct):
46
  if balance < 5000: return base_risk_pct
47
  elif balance < 10000: return base_risk_pct * 0.75
@@ -64,23 +67,23 @@ def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
64
  if profit_target and balance >= profit_target:
65
  break
66
  week_start = balance
67
- num_trades = np.random.randint(trades_min, trades_max + 1)
68
- for _ in range(num_trades):
69
  risk_pct = get_scaled_risk_pct(balance, base_risk_pct)
70
- risk_amount = balance * risk_pct
71
  outcome = np.random.choice(["TP1", "TP2", "SL"], p=[tp1_prob, tp2_prob, sl_prob])
72
  if outcome == "TP1":
73
- balance += risk_amount * tp1_r
74
  tp1_hits += 1
75
  cur_win_streak += 1
76
  cur_loss_streak = 0
77
  elif outcome == "TP2":
78
- balance += risk_amount * tp2_r
79
  tp2_hits += 1
80
  cur_win_streak += 1
81
  cur_loss_streak = 0
82
  else:
83
- balance -= risk_amount
84
  sl_hits += 1
85
  cur_loss_streak += 1
86
  cur_win_streak = 0
@@ -88,119 +91,124 @@ def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
88
  max_loss_streak = max(max_loss_streak, cur_loss_streak)
89
  peak = max(peak, balance)
90
  drawdown = max(drawdown, (peak - balance) / peak * 100)
 
91
  weekly_return = (balance - week_start) / week_start * 100
92
- log.append({"Week": week, "Start Balance": round(week_start, 2), "End Balance": round(balance, 2),
93
- "Weekly Return (%)": round(weekly_return, 2)})
 
 
 
94
 
95
  summary = {
96
  "Final Balance": round(balance, 2),
97
- "TP1 Hits": tp1_hits, "TP2 Hits": tp2_hits, "SL Hits": sl_hits,
 
 
98
  "Max Drawdown %": round(drawdown, 2),
99
- "Max Win Streak": max_win_streak, "Max Loss Streak": max_loss_streak
 
100
  }
101
- return pd.DataFrame(log), summary
102
 
103
- def summary_to_plot(df, summary):
 
 
 
 
 
 
104
  fig = go.Figure()
105
- fig.add_trace(go.Scatter(x=df["Week"], y=df["End Balance"], mode='lines+markers', name='Equity'))
106
- fig.update_layout(title='πŸ“ˆ Equity Curve', xaxis_title='Week', yaxis_title='Balance', height=400)
 
107
  return fig
108
 
109
  def run_preset_strategy(style):
110
- config = strategy_presets[style]
111
- df, summary = simulate_tp_strategy_full(**{k: v for k, v in config.items() if k != "description"})
112
- return df, summary_to_plot(df, summary), strategy_presets[style]["description"]
113
-
114
- def run_manual_strategy(starting_balance, trades_min, trades_max, weeks, tp1_prob, tp2_prob,
115
- tp1_r, tp2_r, base_risk_pct, profit_target):
116
- df, summary = simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
117
- tp1_prob, tp2_prob, tp1_r, tp2_r, base_risk_pct, profit_target)
118
- return df, summary_to_plot(df, summary)
119
-
120
- def battle_strategies(style1, style2):
121
- config1 = strategy_presets[style1]
122
- config2 = strategy_presets[style2]
123
- df1, s1 = simulate_tp_strategy_full(**{k: v for k, v in config1.items() if k != "description"})
124
- df2, s2 = simulate_tp_strategy_full(**{k: v for k, v in config2.items() if k != "description"})
125
-
126
- def compute_score(df, summary):
127
  returns = df["End Balance"].pct_change().dropna()
128
- sharpe = round((returns.mean() / returns.std()) * np.sqrt(52), 2) if returns.std() > 0 else 0
 
129
  peak = df["End Balance"].cummax()
130
  dd = (peak - df["End Balance"]) / peak
131
  max_dd = dd.max() * 100 if not dd.empty else 0
132
- score = summary["Final Balance"] / (1 + max_dd)
133
- summary["Sharpe"] = sharpe
134
- summary["EdgeCast Score"] = round(score, 2)
135
- return summary, sharpe
136
-
137
- s1, sharpe1 = compute_score(df1, s1)
138
- s2, sharpe2 = compute_score(df2, s2)
139
-
140
- winner = style1 if s1["EdgeCast Score"] > s2["EdgeCast Score"] else style2
141
-
142
- df_compare = pd.DataFrame({
143
- "Metric": list(s1.keys()) + ["πŸ† Winner"],
144
- style1: list(s1.values()) + ["βœ…" if winner == style1 else ""],
145
- style2: list(s2.values()) + ["βœ…" if winner == style2 else ""]
146
- })
147
-
148
- fig = go.Figure()
149
- fig.add_trace(go.Scatter(x=df1["Week"], y=df1["End Balance"], name=f"{style1} (Sharpe: {sharpe1})"))
150
- fig.add_trace(go.Scatter(x=df2["Week"], y=df2["End Balance"], name=f"{style2} (Sharpe: {sharpe2})"))
151
- fig.update_layout(title="πŸ“Š Strategy Battle – Sharpe Comparison", xaxis_title="Week", yaxis_title="Balance")
152
-
153
- return df_compare, fig
154
-
155
- def show_descriptions():
156
- return pd.DataFrame({
157
- "Strategy": list(strategy_presets.keys()),
158
- "Description": [v["description"] for v in strategy_presets.values()]
159
- })
160
 
161
  def risk_matrix():
162
- return pd.DataFrame({
163
- "Strategy": list(strategy_presets.keys()),
164
- "Risk %": [v["base_risk_pct"] for v in strategy_presets.values()],
165
- "TP1 R": [v["tp1_r"] for v in strategy_presets.values()],
166
- "TP2 R": [v["tp2_r"] for v in strategy_presets.values()],
167
- "TP1 %": [v["tp1_prob"] for v in strategy_presets.values()],
168
- "TP2 %": [v["tp2_prob"] for v in strategy_presets.values()],
169
- })
170
-
171
- # 🧠 Gradio Interface Tabs
 
 
 
 
 
172
  preset_tab = gr.Interface(fn=run_preset_strategy,
173
- inputs=gr.Dropdown(choices=list(strategy_presets.keys()), label="Select Strategy"),
174
- outputs=["dataframe", "plot", "text"],
175
- title="🎯 Preset Mode")
176
-
177
- manual_tab = gr.Interface(fn=run_manual_strategy,
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, 20, 1.2, step=0.1, label="TP1 R"),
186
- gr.Slider(0.1, 30, 2.4, 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", "plot"],
191
- title="πŸ› οΈ Manual Config")
192
-
193
- battle_tab = gr.Interface(fn=battle_strategies,
194
- inputs=[gr.Dropdown(choices=list(strategy_presets.keys()), label="Strategy 1"),
195
- gr.Dropdown(choices=list(strategy_presets.keys()), label="Strategy 2")],
196
- outputs=["dataframe", "plot"],
197
- title="πŸ₯Š Strategy Battle")
198
-
199
- desc_tab = gr.Interface(fn=show_descriptions, inputs=[], outputs="dataframe", title="πŸ“˜ Strategy Descriptions")
200
- matrix_tab = gr.Interface(fn=risk_matrix, inputs=[], outputs="dataframe", title="🧠 Risk Matrix Visualizer")
 
 
 
 
 
 
 
 
 
 
201
 
202
  gr.TabbedInterface(
203
- [preset_tab, manual_tab, battle_tab, desc_tab, matrix_tab],
204
- tab_names=["Preset", "Manual", "Battle", "Descriptions", "Risk Matrix"],
205
- title="EdgeCast – Strategy Simulation Suite"
206
- ).launch()
 
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
 
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
  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),
104
+ "TP1 Hits": tp1_hits,
105
+ "TP2 Hits": tp2_hits,
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()