zman35 commited on
Commit
3e25330
Β·
verified Β·
1 Parent(s): bc2fbb0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -106
app.py CHANGED
@@ -10,7 +10,7 @@ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
10
  try: gr.analytics_enabled = False
11
  except: pass
12
 
13
- # πŸ“Œ Strategy Presets
14
  strategy_presets = {
15
  "Aggressive Prop Trader": {
16
  "starting_balance": 2500, "trades_min": 5, "trades_max": 10, "weeks": 12,
@@ -53,131 +53,129 @@ def get_scaled_risk_pct(balance, base_risk_pct):
53
  def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
54
  tp1_prob, tp2_prob, tp1_r, tp2_r, base_risk_pct,
55
  profit_target=None):
56
- sl_prob = 1.0 - tp1_prob - tp2_prob
57
- balance = starting_balance
58
- peak = balance
59
- drawdown = 0
60
- tp1_hits = tp2_hits = sl_hits = 0
61
- max_win_streak = max_loss_streak = 0
62
- cur_win_streak = cur_loss_streak = 0
63
- log = []
64
-
65
- for week in range(1, weeks + 1):
66
- if profit_target and balance >= profit_target: break
67
- week_start = balance
68
- num_trades = np.random.randint(trades_min, trades_max + 1)
69
- for _ in range(num_trades):
70
- risk_pct = get_scaled_risk_pct(balance, base_risk_pct)
71
- risk_amount = balance * risk_pct
72
- outcome = np.random.choice(["TP1", "TP2", "SL"], p=[tp1_prob, tp2_prob, sl_prob])
73
- if outcome == "TP1":
74
- balance += risk_amount * tp1_r
75
- tp1_hits += 1
76
- cur_win_streak += 1
77
- cur_loss_streak = 0
78
- elif outcome == "TP2":
79
- balance += risk_amount * tp2_r
80
- tp2_hits += 1
81
- cur_win_streak += 1
82
- cur_loss_streak = 0
83
- else:
84
- balance -= risk_amount
85
- sl_hits += 1
86
- cur_loss_streak += 1
87
- cur_win_streak = 0
88
- max_win_streak = max(max_win_streak, cur_win_streak)
89
- max_loss_streak = max(max_loss_streak, cur_loss_streak)
90
- peak = max(peak, balance)
91
- drawdown = max(drawdown, (peak - balance) / peak * 100)
92
- weekly_return = (balance - week_start) / week_start * 100
93
- log.append({
94
- "Week": week, "Start Balance": round(week_start, 2),
95
- "End Balance": round(balance, 2), "Weekly Return (%)": round(weekly_return, 2)
96
- })
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), "TP1 Hits": tp1_hits,
106
- "TP2 Hits": tp2_hits, "SL Hits": sl_hits,
107
- "Max Drawdown %": round(drawdown, 2),
108
- "Max Win Streak": max_win_streak, "Max Loss Streak": max_loss_streak,
109
- "Sharpe": round(sharpe_ratio, 2), "EdgeCast Score": round(score, 2)
110
- }
111
-
112
- return df, summary
 
 
 
 
 
 
 
 
113
 
114
- # πŸ”Ή Preset Tab
115
  def run_preset_strategy(style):
116
  config = strategy_presets[style]
117
- config_copy = {k: config[k] for k in config if k not in ["description"]}
118
- df, summary = simulate_tp_strategy_full(**config_copy)
119
- fig = go.Figure()
120
- fig.add_trace(go.Scatter(x=df["Week"], y=df["End Balance"], mode='lines+markers', name='Equity Curve'))
121
- fig.update_layout(title='πŸ“ˆ Equity Curve', xaxis_title='Week', yaxis_title='Balance', height=400)
122
- return df, summary, fig, config["description"]
123
 
124
- # πŸ”Ή Battle Tab
125
  def battle_strategies(style1, style2):
126
- df1, s1 = simulate_tp_strategy_full(**{k: v for k, v in strategy_presets[style1].items() if k != "description"})
127
- df2, s2 = simulate_tp_strategy_full(**{k: v for k, v in strategy_presets[style2].items() if k != "description"})
128
  s1["Strategy"] = style1
129
  s2["Strategy"] = style2
130
  df_compare = pd.DataFrame([s1, s2])
131
  winner = df_compare.loc[df_compare["EdgeCast Score"].idxmax(), "Strategy"]
132
 
133
  fig = go.Figure()
134
- fig.add_trace(go.Scatter(x=df1["Week"], y=df1["End Balance"], name=f"{style1} (Sharpe: {s1['Sharpe']})"))
135
- fig.add_trace(go.Scatter(x=df2["Week"], y=df2["End Balance"], name=f"{style2} (Sharpe: {s2['Sharpe']})"))
136
- fig.update_layout(title=f"πŸ“Š Strategy Battle – Sharpe Comparison", xaxis_title="Week", yaxis_title="Balance")
137
 
138
  df_compare["πŸ† Winner"] = df_compare["Strategy"] == winner
139
- return df_compare.style.apply(lambda r: ['background-color: #d4edda; font-weight: bold' if r["πŸ† Winner"] else '' for _ in r], axis=1), fig
140
 
141
- # πŸ”Ή Analytics
142
  def analytics_dashboard():
143
- results = []
144
  for name, config in strategy_presets.items():
145
- _, s = simulate_tp_strategy_full(**{k: config[k] for k in config if k != "description"})
146
  s["Strategy"] = name
147
- results.append(s)
148
- return pd.DataFrame(results).sort_values("EdgeCast Score", ascending=False)
149
 
150
- # πŸ”Ή Descriptions
151
  def show_descriptions():
152
  return pd.DataFrame([
153
- {"Strategy": name, "Description": config["description"]}
154
- for name, config in strategy_presets.items()
155
  ])
156
 
157
- # πŸ”Ή Risk Matrix Heatmap
158
  def generate_risk_matrix():
 
159
  scores = {}
160
- for name in strategy_presets:
161
- _, s = simulate_tp_strategy_full(**{k: v for k, v in strategy_presets[name].items() if k != "description"})
162
- scores[name] = s["EdgeCast Score"]
163
-
164
- strategies = list(scores.keys())
165
  matrix = np.zeros((len(strategies), len(strategies)))
166
  for i, a in enumerate(strategies):
167
  for j, b in enumerate(strategies):
168
  matrix[i, j] = abs(scores[a] - scores[b])
169
-
170
- fig = px.imshow(matrix, x=strategies, y=strategies, text_auto=True,
171
- color_continuous_scale="RdYlGn_r", title="πŸ”¬ Risk Matrix (Ξ” Score Heatmap)")
172
- fig.update_traces(hovertemplate="Ξ” Score: %{z}<extra></extra>")
173
  return fig
174
 
175
- # πŸ”§ Gradio Interface
176
- app = gr.TabbedInterface(
177
  interface_list=[
178
  gr.Interface(fn=run_preset_strategy,
179
  inputs=gr.Dropdown(choices=list(strategy_presets.keys()), label="Select Strategy"),
180
- outputs=["dataframe", "json", gr.Plot(), "text"],
181
  title="🎯 Preset Mode"),
182
 
183
  gr.Interface(fn=simulate_tp_strategy_full,
@@ -188,10 +186,10 @@ app = gr.TabbedInterface(
188
  gr.Slider(1, 52, 12, label="Weeks"),
189
  gr.Slider(0, 1, 0.3, step=0.05, label="TP1 %"),
190
  gr.Slider(0, 1, 0.3, step=0.05, label="TP2 %"),
191
- gr.Slider(0.1, 5.0, 1.2, step=0.1, label="TP1 R"),
192
- gr.Slider(0.1, 5.0, 2.4, step=0.1, label="TP2 R"),
193
- gr.Slider(0.001, 0.05, 0.015, step=0.001, label="Risk %"),
194
- gr.Slider(0, 100000, 0, step=500, label="Profit Target")
195
  ],
196
  outputs=["dataframe", "json"],
197
  title="πŸ› οΈ Manual Config"),
@@ -204,17 +202,12 @@ app = gr.TabbedInterface(
204
  outputs=["dataframe", gr.Plot()],
205
  title="πŸ₯Š Battle Mode"),
206
 
207
- gr.Interface(fn=analytics_dashboard,
208
- inputs=[], outputs="dataframe", title="πŸ“Š Analytics"),
209
 
210
- gr.Interface(fn=show_descriptions,
211
- inputs=[], outputs="dataframe", title="πŸ“˜ Descriptions"),
212
 
213
- gr.Interface(fn=generate_risk_matrix,
214
- inputs=[], outputs=gr.Plot(), title="🧠 Risk Matrix")
215
  ],
216
  tab_names=["Preset", "Manual", "Battle", "Analytics", "Descriptions", "Risk Matrix"],
217
  title="EdgeCast – Strategy Simulation Suite"
218
- )
219
-
220
- app.launch()
 
10
  try: gr.analytics_enabled = False
11
  except: pass
12
 
13
+ # Strategy Presets
14
  strategy_presets = {
15
  "Aggressive Prop Trader": {
16
  "starting_balance": 2500, "trades_min": 5, "trades_max": 10, "weeks": 12,
 
53
  def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
54
  tp1_prob, tp2_prob, tp1_r, tp2_r, base_risk_pct,
55
  profit_target=None):
56
+ try:
57
+ sl_prob = 1.0 - tp1_prob - tp2_prob
58
+ balance = starting_balance
59
+ peak = balance
60
+ drawdown = 0
61
+ tp1_hits = tp2_hits = sl_hits = 0
62
+ max_win_streak = max_loss_streak = 0
63
+ cur_win_streak = cur_loss_streak = 0
64
+ log = []
65
+
66
+ for week in range(1, weeks + 1):
67
+ if profit_target and balance >= profit_target: break
68
+ week_start = balance
69
+ num_trades = np.random.randint(trades_min, trades_max + 1)
70
+ for _ in range(num_trades):
71
+ risk_pct = get_scaled_risk_pct(balance, base_risk_pct)
72
+ risk_amount = balance * risk_pct
73
+ outcome = np.random.choice(["TP1", "TP2", "SL"], p=[tp1_prob, tp2_prob, sl_prob])
74
+ if outcome == "TP1":
75
+ balance += risk_amount * tp1_r
76
+ tp1_hits += 1
77
+ cur_win_streak += 1
78
+ cur_loss_streak = 0
79
+ elif outcome == "TP2":
80
+ balance += risk_amount * tp2_r
81
+ tp2_hits += 1
82
+ cur_win_streak += 1
83
+ cur_loss_streak = 0
84
+ else:
85
+ balance -= risk_amount
86
+ sl_hits += 1
87
+ cur_loss_streak += 1
88
+ cur_win_streak = 0
89
+ max_win_streak = max(max_win_streak, cur_win_streak)
90
+ max_loss_streak = max(max_loss_streak, cur_loss_streak)
91
+ peak = max(peak, balance)
92
+ drawdown = max(drawdown, (peak - balance) / peak * 100)
93
+ weekly_return = (balance - week_start) / week_start * 100
94
+ log.append({
95
+ "Week": week,
96
+ "Start Balance": round(week_start, 2),
97
+ "End Balance": round(balance, 2),
98
+ "Weekly Return (%)": round(weekly_return, 2)
99
+ })
100
+
101
+ df = pd.DataFrame(log)
102
+ returns = df["End Balance"].pct_change().dropna()
103
+ volatility = returns.std() * np.sqrt(52)
104
+ sharpe = returns.mean() / volatility * np.sqrt(52) if volatility > 0 else 0
105
+ score = balance / (1 + drawdown)
106
+
107
+ summary = {
108
+ "Final Balance": round(balance, 2),
109
+ "TP1 Hits": tp1_hits,
110
+ "TP2 Hits": tp2_hits,
111
+ "SL Hits": sl_hits,
112
+ "Max Drawdown %": round(drawdown, 2),
113
+ "Max Win Streak": max_win_streak,
114
+ "Max Loss Streak": max_loss_streak,
115
+ "Sharpe Ratio": round(sharpe, 2),
116
+ "EdgeCast Score": round(score, 2)
117
+ }
118
+ return df, summary
119
+ except Exception as e:
120
+ return pd.DataFrame(), {"Error": str(e)}
121
 
 
122
  def run_preset_strategy(style):
123
  config = strategy_presets[style]
124
+ df, summary = simulate_tp_strategy_full(**{k: config[k] for k in config if k not in ["description"]})
125
+ return df, summary, config["description"]
 
 
 
 
126
 
 
127
  def battle_strategies(style1, style2):
128
+ df1, s1 = simulate_tp_strategy_full(**strategy_presets[style1])
129
+ df2, s2 = simulate_tp_strategy_full(**strategy_presets[style2])
130
  s1["Strategy"] = style1
131
  s2["Strategy"] = style2
132
  df_compare = pd.DataFrame([s1, s2])
133
  winner = df_compare.loc[df_compare["EdgeCast Score"].idxmax(), "Strategy"]
134
 
135
  fig = go.Figure()
136
+ fig.add_trace(go.Scatter(x=df1["Week"], y=df1["End Balance"], name=f"{style1} (Sharpe: {s1['Sharpe Ratio']})"))
137
+ fig.add_trace(go.Scatter(x=df2["Week"], y=df2["End Balance"], name=f"{style2} (Sharpe: {s2['Sharpe Ratio']})"))
138
+ fig.update_layout(title=f"Strategy Battle – Sharpe Comparison", xaxis_title="Week", yaxis_title="Balance")
139
 
140
  df_compare["πŸ† Winner"] = df_compare["Strategy"] == winner
141
+ return df_compare, fig
142
 
 
143
  def analytics_dashboard():
144
+ rows = []
145
  for name, config in strategy_presets.items():
146
+ _, s = simulate_tp_strategy_full(**config)
147
  s["Strategy"] = name
148
+ rows.append(s)
149
+ return pd.DataFrame(rows).sort_values("EdgeCast Score", ascending=False).reset_index(drop=True)
150
 
 
151
  def show_descriptions():
152
  return pd.DataFrame([
153
+ {"Strategy": k, "Description": v["description"]}
154
+ for k, v in strategy_presets.items()
155
  ])
156
 
 
157
  def generate_risk_matrix():
158
+ strategies = list(strategy_presets.keys())
159
  scores = {}
160
+ for strat in strategies:
161
+ _, s = simulate_tp_strategy_full(**strategy_presets[strat])
162
+ scores[strat] = s["EdgeCast Score"]
 
 
163
  matrix = np.zeros((len(strategies), len(strategies)))
164
  for i, a in enumerate(strategies):
165
  for j, b in enumerate(strategies):
166
  matrix[i, j] = abs(scores[a] - scores[b])
167
+ fig = px.imshow(matrix, x=strategies, y=strategies, color_continuous_scale="RdYlGn_r",
168
+ text_auto=".2f", labels=dict(color="Ξ” Score"))
169
+ fig.update_traces(hovertemplate="Ξ” = %{z:.2f} between %{x} and %{y}")
170
+ fig.update_layout(title="🧠 Risk Matrix (Ξ” Score Heatmap)", height=500)
171
  return fig
172
 
173
+ # πŸš€ Launch App
174
+ 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,
 
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, 20.0, 1.0, step=0.1, label="TP1 R (Risk:Reward)"),
190
+ gr.Slider(0.1, 20.0, 2.0, step=0.1, label="TP2 R (Risk:Reward)"),
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"),
 
202
  outputs=["dataframe", gr.Plot()],
203
  title="πŸ₯Š Battle Mode"),
204
 
205
+ gr.Interface(fn=analytics_dashboard, inputs=[], outputs="dataframe", title="πŸ“Š Analytics"),
 
206
 
207
+ gr.Interface(fn=show_descriptions, inputs=[], outputs="dataframe", title="πŸ“˜ Descriptions"),
 
208
 
209
+ gr.Interface(fn=generate_risk_matrix, inputs=[], outputs=gr.Plot(), title="πŸ”¬ Risk Matrix")
 
210
  ],
211
  tab_names=["Preset", "Manual", "Battle", "Analytics", "Descriptions", "Risk Matrix"],
212
  title="EdgeCast – Strategy Simulation Suite"
213
+ ).launch()