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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -61
app.py CHANGED
@@ -7,12 +7,10 @@ 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,
@@ -92,8 +90,10 @@ def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
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()
@@ -102,80 +102,82 @@ def simulate_tp_strategy_full(starting_balance, trades_min, trades_max, weeks,
102
  score = balance / (1 + drawdown)
103
 
104
  summary = {
105
- "Final Balance": round(balance, 2),
106
- "TP1 Hits": tp1_hits,
107
- "TP2 Hits": tp2_hits,
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,
@@ -186,10 +188,10 @@ app = gr.TabbedInterface(
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"),
@@ -203,16 +205,13 @@ app = gr.TabbedInterface(
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"
 
7
 
8
  # Disable Gradio analytics
9
  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,
 
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()
 
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
  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"),
 
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"