Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,7 +10,7 @@ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
|
| 10 |
try: gr.analytics_enabled = False
|
| 11 |
except: pass
|
| 12 |
|
| 13 |
-
#
|
| 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 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
# πΉ Preset Tab
|
| 115 |
def run_preset_strategy(style):
|
| 116 |
config = strategy_presets[style]
|
| 117 |
-
|
| 118 |
-
df, summary
|
| 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(**
|
| 127 |
-
df2, s2 = simulate_tp_strategy_full(**
|
| 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"
|
| 137 |
|
| 138 |
df_compare["π Winner"] = df_compare["Strategy"] == winner
|
| 139 |
-
return df_compare
|
| 140 |
|
| 141 |
-
# πΉ Analytics
|
| 142 |
def analytics_dashboard():
|
| 143 |
-
|
| 144 |
for name, config in strategy_presets.items():
|
| 145 |
-
_, s = simulate_tp_strategy_full(**
|
| 146 |
s["Strategy"] = name
|
| 147 |
-
|
| 148 |
-
return pd.DataFrame(
|
| 149 |
|
| 150 |
-
# πΉ Descriptions
|
| 151 |
def show_descriptions():
|
| 152 |
return pd.DataFrame([
|
| 153 |
-
{"Strategy":
|
| 154 |
-
for
|
| 155 |
])
|
| 156 |
|
| 157 |
-
# πΉ Risk Matrix Heatmap
|
| 158 |
def generate_risk_matrix():
|
|
|
|
| 159 |
scores = {}
|
| 160 |
-
for
|
| 161 |
-
_, s = simulate_tp_strategy_full(**
|
| 162 |
-
scores[
|
| 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 |
-
|
| 171 |
-
|
| 172 |
-
fig.
|
| 173 |
return fig
|
| 174 |
|
| 175 |
-
#
|
| 176 |
-
|
| 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",
|
| 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,
|
| 192 |
-
gr.Slider(0.1,
|
| 193 |
-
gr.Slider(0.001, 0.05, 0.
|
| 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()
|
|
|
|
|
|