Imports¶
This section gathers, in one place, the libraries the notebook depends on, so every later cell can rely on them being loaded.
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import talib
from plotly.subplots import make_subplots
Config¶
This section collects the study's fixed choices — the strategy's parameters, the markets and timeframes it runs on, the fee rate, and starting capital — as named constants, set once here and referenced by name throughout.
FEE_PCT = 0.02 / 100 # binance futures taker, per side
INITIAL_CASH = 100
WMA_PERIOD = 50
SYMBOLS = ["BTCUSDT", "ETHUSDT", "SOLUSDT", "BNBUSDT", "DOGEUSDT", "XRPUSDT"]
# Synthetic basket symbol — an equal-weight average of every symbol's
# normalized price history, measured like any other market.
BASKET_SYMBOL = "ALL"
# Resampled-history block length — whole stretches of real returns this long
# are drawn to build the resampled run; long enough to keep trends intact.
RESAMPLE_BLOCK_DAYS = 90
TIMEFRAMES = ["30m", "1h", "4h", "1d"]
DATA_DIR = "../data" # cached Binance klines, one CSV per symbol + timeframe
# Bars per year by timeframe — annualizes the Sharpe ratio.
BARS_PER_YEAR = {
"30m": 365 * 24 * 2,
"1h": 365 * 24,
"4h": 365 * 6,
"1d": 365,
}
# One colour per symbol, used for the overlaid lines in every chart.
SYMBOL_COLORS = {
"BTCUSDT": "#f7931a",
"ETHUSDT": "#627eea",
"SOLUSDT": "#14b8a6",
"BNBUSDT": "#f3ba2f",
"DOGEUSDT": "#9b59b6",
"XRPUSDT": "#0085c0",
BASKET_SYMBOL: "#333333",
}
Strategy¶
This section defines the strategy: the signal it watches, the precise conditions that open and close a position, and the intuition for why it may hold an edge. A short example on simulated prices shows the entry and exit markers in isolation, so the mechanics are clear before any real data or performance is considered.
The strategy reads a single weighted moving average of the close. A weighted moving average over 50 bars averages the last 50 closes with linearly rising weights — the most recent bar counts 50 times as much as the oldest — so it tracks price more closely than a plain average while still smoothing the noise:
$$\mathrm{WMA}_{50}(t) = \frac{\sum_{k=0}^{49}(50 - k)\,p_{t-k}} {\sum_{k=0}^{49}(50 - k)}.$$
A long position opens the moment the close crosses above the average, and closes when it crosses back below:
$$\text{open at } t \iff p_{t-1} \le \mathrm{WMA}_{50}(t-1) \;\land\; p_t > \mathrm{WMA}_{50}(t), \qquad \text{close at } t \iff p_{t-1} \ge \mathrm{WMA}_{50}(t-1) \;\land\; p_t < \mathrm{WMA}_{50}(t).$$
It is long-only and always fully in or fully out — a bet that price holding above its recent weighted average marks an up-trend worth riding until price falls back through it.
def strategy(prices, period):
wma = talib.WMA(prices, timeperiod=period)
above = (prices > wma).astype(np.int8)
change = np.diff(above)
opens = np.where(change == 1)[0] + 1
closes = np.where(change == -1)[0] + 1
return wma, opens, closes
An illustrative example on a synthetic price path, drawn as candles around its closes, so the entries (green) and exits (red) on the price can be read against the close crossing its weighted moving average.
rng = np.random.default_rng(3)
example_prices = 100 * np.cumprod(1 + rng.normal(0, 0.01, size=340))
example_wma, example_opens, example_closes = strategy(prices=example_prices, period=WMA_PERIOD)
# Candles are display-only, built around the close path the strategy reads:
# each bar opens at the prior close, with small simulated wicks.
candle_open_prices = np.concatenate(([example_prices[0]], example_prices[:-1]))
candle_high_prices = np.maximum(candle_open_prices, example_prices) * (
1 + rng.uniform(0, 0.004, size=example_prices.size)
)
candle_low_prices = np.minimum(candle_open_prices, example_prices) * (
1 - rng.uniform(0, 0.004, size=example_prices.size)
)
fig = go.Figure()
fig.add_trace(
go.Candlestick(
open=candle_open_prices,
high=candle_high_prices,
low=candle_low_prices,
close=example_prices,
name="Price",
increasing=dict(line=dict(color="#8a9bab", width=1), fillcolor="#f6fafd"),
decreasing=dict(line=dict(color="#8a9bab", width=1), fillcolor="#8a9bab"),
)
)
fig.add_trace(
go.Scatter(
y=example_wma,
mode="lines",
name="WMA 50",
line=dict(color="#7b68ee", width=1),
)
)
fig.add_trace(
go.Scatter(
x=example_opens,
y=example_prices[example_opens],
mode="markers",
name="Entries",
marker=dict(color="#00d4aa", size=9, symbol="triangle-up"),
)
)
fig.add_trace(
go.Scatter(
x=example_closes,
y=example_prices[example_closes],
mode="markers",
name="Exits",
marker=dict(color="#ff3b30", size=9, symbol="triangle-down"),
)
)
fig.update_layout(
template="plotly_white",
height=400,
width=1080,
margin=dict(l=60, r=20, t=40, b=40),
xaxis_rangeslider_visible=False,
)
fig.show()
Metrics¶
This section turns the strategy's trades into performance metrics, per-trade and cumulative. Each is defined with its formula below; equity is reported in both gross (before fees) and net (after fees) form, so the cost of trading is always visible.
- Symbol — the market this result belongs to (e.g. BTCUSDT); ALL is the equal-weight basket of every symbol, averaged from their normalized price histories over the common window.
- Price Change % — the close price as a percentage change from the start of the window (from the close series $p_0,\dots,p_T$); in the summary, the total change over the period — the buy-and-hold return.
- Weighted Moving Average — the 50-bar weighted moving average of the close (WMA 50), the trailing average the price is measured against; a long position is open whenever the close sits above it.
- Entries — bars where a position is opened.
- Exits — bars where a position is closed.
- Cumulative Win Rate % — running share of winning trades, $\frac{1}{n}\sum_{i=1}^{n}\mathbf{1}\{r_i > 1\}\cdot 100\%$, where $r_i = (1 - f)^2\,p^{\text{exit}}_i / p^{\text{entry}}_i$ and $f$ the per-side fee.
- Cumulative P&L % — the running sum of per-trade net returns, $\sum_{i=1}^{n}(r_i - 1)\cdot 100\%$.
- Equity — net equity curve, compounded all-in: $E_n = E_0 \prod_{i=1}^{n} r_i$; the gross variant drops the fee term.
- Cumulative Fees — the running total of fees paid, each proportional to capital at trade time.
- Rolling Sharpe — annualized Sharpe of net per-trade returns computed to-date after each trade, $S_n = \frac{\bar x}{\operatorname{std}(x)}\sqrt{T_\text{year}}$ over $x_1,\dots,x_n$, with $x_i = r_i - 1$ and $T_\text{year}$ the observed number of trades per year.
def analytics(symbol, prices, bars_per_year):
wma, opens, closes = strategy(prices=prices, period=WMA_PERIOD)
trade_count = min(len(opens), len(closes))
opens = opens[:trade_count]
closes = closes[:trade_count]
entry_prices = prices[opens]
exit_prices = prices[closes]
# Per-trade return factor: (1 - fee)^2 covers entry + exit fees,
# (exit / entry) is the raw price move.
factor = (1 - FEE_PCT) ** 2 * (exit_prices / entry_prices)
# Equity compounded with all-in sizing.
equity = INITIAL_CASH * np.cumprod(factor)
equity_no_fee = INITIAL_CASH * np.cumprod(exit_prices / entry_prices)
entry_capital = np.concatenate(([INITIAL_CASH], equity[:-1]))
# Fees in dollars — proportional to capital at trade time.
entry_fees = entry_capital * FEE_PCT
exit_fees = entry_capital * (1 - FEE_PCT) * (exit_prices / entry_prices) * FEE_PCT
fees = entry_fees + exit_fees
cum_fees = np.cumsum(fees)
pnls = equity - entry_capital
total_trades = pnls.size
cum_winrate = np.cumsum(pnls > 0) / np.arange(1, total_trades + 1) * 100
pct_cum_pnl = np.cumsum((factor - 1) * 100)
# Rolling (to-date) Sharpe after each trade: per-trade fractional returns,
# annualized by the observed trade frequency.
returns = factor - 1
with np.errstate(invalid="ignore", divide="ignore"):
cum_mean = np.cumsum(returns) / np.arange(1, total_trades + 1)
cum_var = (np.cumsum(returns**2) / np.arange(1, total_trades + 1)) - cum_mean**2
cum_std = np.sqrt(np.clip(cum_var, 0, None))
cum_sharpe_per_trade = np.where(cum_std > 0, cum_mean / cum_std, 0.0)
cum_sharpe = cum_sharpe_per_trade * np.sqrt(
np.arange(1, total_trades + 1) * bars_per_year / max(len(prices), 1)
)
return {
"symbol": symbol,
"prices": prices,
"wma": wma,
"opens": opens,
"closes": closes,
"cum_winrate": cum_winrate,
"pct_cum_pnl": pct_cum_pnl,
"equity": equity,
"equity_no_fee": equity_no_fee,
"cum_fees": cum_fees,
"cum_sharpe": cum_sharpe,
}
Visualization¶
This section visualises every metric over time, with one coloured line per symbol so the markets can be compared directly, shown across each timeframe. Each summary table below is also drawn as grouped bars — one panel per metric, one bar per symbol and timeframe — so the final results compare at a glance.
CHART_MAX_POINTS = 1500 # cap points per line so pages stay light; LTTB keeps the shape
def downsample(x_values, y_values, max_points):
total_points = len(x_values)
if total_points <= max_points or max_points < 3:
return x_values, y_values
x_values = np.asarray(x_values, dtype=float)
y_values = np.asarray(y_values, dtype=float)
bucket_size = (total_points - 2) / (max_points - 2)
sampled_x = np.empty(max_points)
sampled_y = np.empty(max_points)
sampled_x[0] = x_values[0]
sampled_y[0] = y_values[0]
sampled_x[-1] = x_values[-1]
sampled_y[-1] = y_values[-1]
previous = 0
for i in range(max_points - 2):
next_start = int((i + 1) * bucket_size) + 1
next_end = min(int((i + 2) * bucket_size) + 1, total_points)
average_x = x_values[next_start:next_end].mean()
average_y = y_values[next_start:next_end].mean()
bucket_start = int(i * bucket_size) + 1
bucket_end = int((i + 1) * bucket_size) + 1
anchor_x = x_values[previous]
anchor_y = y_values[previous]
triangle_areas = np.abs(
(anchor_x - average_x) * (y_values[bucket_start:bucket_end] - anchor_y)
- (anchor_x - x_values[bucket_start:bucket_end]) * (average_y - anchor_y)
)
chosen = bucket_start + int(np.argmax(triangle_areas))
sampled_x[i + 1] = x_values[chosen]
sampled_y[i + 1] = y_values[chosen]
previous = chosen
return sampled_x, sampled_y
def charts(results):
symbols = list(dict.fromkeys(symbol for symbol, _ in results))
metrics = [
("Price Change %", "pct_prices", None),
("Cumulative Win Rate %", "cum_winrate", None),
("Cumulative P&L %", "pct_cum_pnl", None),
("Equity", "equity", "equity_no_fee"),
("Cumulative Fees", "cum_fees", None),
("Rolling Sharpe", "cum_sharpe", None),
]
n_rows = len(metrics)
n_cols = len(TIMEFRAMES)
col_width = 600
row_height = 280
gap_px = 60
total_w = col_width * n_cols + gap_px * max(n_cols - 1, 0)
total_h = row_height * n_rows
h_spacing = gap_px / total_w if n_cols > 1 else 0
fig = make_subplots(
rows=n_rows,
cols=n_cols,
shared_xaxes=True,
vertical_spacing=0.025,
horizontal_spacing=h_spacing,
column_titles=list(TIMEFRAMES),
)
for row_idx, (title, key, gross_key) in enumerate(metrics, start=1):
for col_idx, timeframe in enumerate(TIMEFRAMES, start=1):
max_len = max(len(results[(s, timeframe)]["prices"]) for s in symbols)
for symbol in symbols:
result = results[(symbol, timeframe)]
offset = max_len - len(result["prices"])
if key == "pct_prices":
y_values = (result["prices"] / result["prices"][0] - 1) * 100
x_values = np.arange(offset, offset + len(y_values))
else:
y_values = result[key]
x_values = result["opens"] + offset
x_values, y_values = downsample(x_values, y_values, CHART_MAX_POINTS)
fig.add_trace(
go.Scatter(
x=x_values,
y=np.round(y_values, 4),
mode="lines",
name=symbol,
legendgroup=symbol,
line=dict(color=SYMBOL_COLORS[symbol], width=1),
showlegend=False,
hovertemplate="%{fullData.name}: %{y}<extra></extra>",
),
row=row_idx,
col=col_idx,
)
if gross_key:
gross_x, gross_y = downsample(
result["opens"] + offset,
result[gross_key],
CHART_MAX_POINTS,
)
fig.add_trace(
go.Scatter(
x=gross_x,
y=np.round(gross_y, 4),
mode="lines",
name=symbol,
legendgroup=symbol,
line=dict(color=SYMBOL_COLORS[symbol], width=1, dash="dot"),
showlegend=False,
hoverinfo="skip",
),
row=row_idx,
col=col_idx,
)
fig.update_yaxes(title_text=title, title_font=dict(size=13), row=row_idx, col=1)
# Dummy traces with thicker lines so the legend entries appear bold
# while the actual chart lines remain at width=1.
for symbol in symbols:
fig.add_trace(
go.Scatter(
x=[None],
y=[None],
mode="lines",
name=symbol,
legendgroup=symbol,
line=dict(color=SYMBOL_COLORS[symbol], width=3),
showlegend=True,
)
)
# Same pixel gap between the legend and the plot area in every figure —
# paper coordinates scale with figure height, so derive the offset from it.
legend_y = 1 + 75 / (total_h - 110) # 110 = top + bottom margins
fig.update_layout(
template="plotly_white",
height=total_h,
width=total_w,
font=dict(size=11),
hovermode="x unified",
hoverlabel=dict(bgcolor="white"),
legend=dict(
orientation="h",
yanchor="bottom",
y=legend_y,
xanchor="left",
x=0,
),
margin=dict(l=90, r=20, t=70, b=40),
)
fig.update_annotations(font=dict(size=13))
fig.update_xaxes(showgrid=True)
fig.update_yaxes(showgrid=True, zeroline=True)
fig.update_yaxes(range=[-3, 3], row=n_rows) # clamp Rolling Sharpe
fig.show()
def left_aligned_table(df):
def format_value(value):
if not isinstance(value, (int, float)):
return value
if value == int(value):
return f"{int(value):,}"
return f"{value:,.2f}".rstrip("0").rstrip(".")
return (
df.style.format(format_value)
.hide(axis="index")
.set_properties(**{"text-align": "left", "white-space": "nowrap"})
.set_table_styles(
[
{"selector": "th", "props": [("text-align", "left"), ("white-space", "nowrap")]},
{"selector": "", "props": [("min-width", "100%")]},
]
)
)
def summarize(results):
rows = []
for (symbol, timeframe), result in results.items():
equity = result["equity"]
equity_no_fee = result["equity_no_fee"]
prices = result["prices"]
has_trades = len(equity) > 0
rows.append(
{
"Symbol": symbol,
"Timeframe": timeframe,
"Price Change %": round(float(prices[-1] / prices[0] - 1) * 100, 1),
"Cumulative Win Rate %": (
round(float(result["cum_winrate"][-1]), 1) if has_trades else 0.0
),
"Cumulative P&L %": (
round(float(result["pct_cum_pnl"][-1]), 1) if has_trades else 0.0
),
"Equity Net": (round(float(equity[-1]), 2) if has_trades else float(INITIAL_CASH)),
"Equity Gross": (
round(float(equity_no_fee[-1]), 2) if has_trades else float(INITIAL_CASH)
),
"Cumulative Fees": (round(float(result["cum_fees"][-1]), 2) if has_trades else 0.0),
"Rolling Sharpe": (
round(float(result["cum_sharpe"][-1]), 2) if has_trades else 0.0
),
}
)
return pd.DataFrame(rows)
def summary_charts(summary):
symbols = list(dict.fromkeys(summary["Symbol"]))
metrics = [column for column in summary.columns if column not in ("Symbol", "Timeframe")]
n_cols = 4
n_rows = (len(metrics) + n_cols - 1) // n_cols
col_width = 600
row_height = 280
gap_px = 60
total_w = col_width * n_cols + gap_px * max(n_cols - 1, 0)
total_h = row_height * n_rows
h_spacing = gap_px / total_w if n_cols > 1 else 0
v_spacing = gap_px / total_h if n_rows > 1 else 0
fig = make_subplots(
rows=n_rows,
cols=n_cols,
vertical_spacing=v_spacing,
horizontal_spacing=h_spacing,
subplot_titles=metrics,
)
for metric_idx, metric in enumerate(metrics):
row_idx = metric_idx // n_cols + 1
col_idx = metric_idx % n_cols + 1
for symbol in symbols:
symbol_rows = summary[summary["Symbol"] == symbol]
fig.add_trace(
go.Bar(
x=symbol_rows["Timeframe"],
y=symbol_rows[metric],
name=symbol,
legendgroup=symbol,
marker_color=SYMBOL_COLORS[symbol],
showlegend=metric_idx == 0,
),
row=row_idx,
col=col_idx,
)
# Same pixel gap between the legend and the plot area in every figure —
# paper coordinates scale with figure height, so derive the offset from it.
legend_y = 1 + 75 / (total_h - 110) # 110 = top + bottom margins
fig.update_layout(
template="plotly_white",
height=total_h,
width=total_w,
font=dict(size=11),
barmode="group",
hovermode="x unified",
hoverlabel=dict(bgcolor="white"),
legend=dict(
orientation="h",
yanchor="bottom",
y=legend_y,
xanchor="left",
x=0,
),
margin=dict(l=90, r=20, t=70, b=40),
)
fig.update_annotations(font=dict(size=13))
fig.update_xaxes(showgrid=True)
fig.update_yaxes(showgrid=True, zeroline=True)
# Hide the axes of grid slots past the last metric so they stay blank.
for slot_idx in range(len(metrics), n_rows * n_cols):
row_idx = slot_idx // n_cols + 1
col_idx = slot_idx % n_cols + 1
fig.update_xaxes(visible=False, row=row_idx, col=col_idx)
fig.update_yaxes(visible=False, row=row_idx, col=col_idx)
fig.show()
Run on Real Data¶
This section runs the strategy on real market data: a basket of liquid symbols evaluated across several timeframes. Every metric is charted with one coloured line per symbol, so the markets can be compared directly.
The basket symbol ALL is an equal-weight portfolio of the whole set: every symbol's price history is normalized to its starting value over the common window, then averaged. It runs through the same strategy and metrics as any single market.
def basket_prices(symbol_prices):
common_len = min(len(prices) for prices in symbol_prices)
aligned = [prices[-common_len:] for prices in symbol_prices]
normalized = [prices / prices[0] for prices in aligned]
return np.mean(normalized, axis=0)
prices = {
(symbol, timeframe): pd.read_csv(f"{DATA_DIR}/{symbol}_{timeframe}.csv")["close"].to_numpy()
for symbol in SYMBOLS
for timeframe in TIMEFRAMES
}
for timeframe in TIMEFRAMES:
symbol_prices = [prices[(symbol, timeframe)] for symbol in SYMBOLS]
prices[(BASKET_SYMBOL, timeframe)] = basket_prices(symbol_prices=symbol_prices)
results = {
(symbol, timeframe): analytics(
symbol=symbol,
prices=prices[(symbol, timeframe)],
bars_per_year=BARS_PER_YEAR[timeframe],
)
for symbol in [*SYMBOLS, BASKET_SYMBOL]
for timeframe in TIMEFRAMES
}
charts(results=results)
summary = summarize(results=results)
left_aligned_table(df=summary)
| Symbol | Timeframe | Price Change % | Cumulative Win Rate % | Cumulative P&L % | Equity Net | Equity Gross | Cumulative Fees | Rolling Sharpe |
|---|---|---|---|---|---|---|---|---|
| BTCUSDT | 30m | 1,347.9 | 18.1 | -13.7 | 33 | 726.57 | 203.66 | -0.03 |
| BTCUSDT | 1h | 1,331.8 | 17.8 | 119.7 | 123.31 | 563.9 | 201.29 | 0.28 |
| BTCUSDT | 4h | 1,318 | 23.3 | 412 | 1,838.68 | 2,522.08 | 374.28 | 0.82 |
| BTCUSDT | 1d | 1,339.4 | 24.4 | 617 | 5,043.85 | 5,289.77 | 99.06 | 0.78 |
| ETHUSDT | 30m | 444.3 | 19.3 | 312 | 503.86 | 10,381.69 | 1,062.66 | 0.59 |
| ETHUSDT | 1h | 440.1 | 19.6 | 243.6 | 251.15 | 1,105.68 | 330.06 | 0.45 |
| ETHUSDT | 4h | 429.1 | 21.1 | 574.7 | 3,517.98 | 4,899.44 | 1,025.61 | 0.83 |
| ETHUSDT | 1d | 439.5 | 29.4 | 902.2 | 13,460.35 | 14,060.26 | 213.45 | 0.7 |
| SOLUSDT | 30m | 1,957.1 | 20.7 | 479.9 | 1,583.32 | 10,520.4 | 2,259.67 | 0.94 |
| SOLUSDT | 1h | 2,086.3 | 21.2 | 449 | 1,550.85 | 3,980.05 | 1,206.55 | 0.94 |
| SOLUSDT | 4h | 2,107.4 | 21.5 | 634 | 2,845.35 | 3,584.1 | 608.38 | 0.89 |
| SOLUSDT | 1d | 1,856.3 | 23.7 | 1,363.3 | 13,109.04 | 13,605.93 | 248.9 | 0.73 |
| BNBUSDT | 30m | 34,845.9 | 19.2 | 400.8 | 408.67 | 8,471.06 | 2,060.9 | 0.52 |
| BNBUSDT | 1h | 34,877.6 | 19.4 | 520.2 | 1,034.34 | 4,627.03 | 2,059.34 | 0.63 |
| BNBUSDT | 4h | 34,864.7 | 22.6 | 797.8 | 11,713.9 | 16,398.82 | 1,522.29 | 0.84 |
| BNBUSDT | 1d | 37,733.2 | 28.8 | 1,028.9 | 10,107.57 | 10,655.64 | 288.33 | 0.63 |
| DOGEUSDT | 30m | 2,106.6 | 16.8 | 118 | 1.62 | 21.36 | 22.46 | 0.09 |
| DOGEUSDT | 1h | 2,041.5 | 16.6 | 609 | 83.1 | 294.64 | 221.35 | 0.42 |
| DOGEUSDT | 4h | 2,148.9 | 17.8 | 933.6 | 3,877.82 | 5,149.51 | 720.85 | 0.69 |
| DOGEUSDT | 1d | 2,071.8 | 30.7 | 863.4 | 5,415.73 | 5,609.78 | 116.78 | 0.65 |
| XRPUSDT | 30m | 23 | 17.1 | -189.2 | 1.79 | 33.35 | 50.71 | -0.3 |
| XRPUSDT | 1h | 22.4 | 17 | 52.4 | 15.57 | 65.92 | 39.09 | 0.07 |
| XRPUSDT | 4h | 23.4 | 19.5 | 516.3 | 850.73 | 1,190.03 | 118.22 | 0.58 |
| XRPUSDT | 1d | 27 | 17.2 | 291.6 | 135.29 | 142.74 | 6.27 | 0.31 |
| ALL | 30m | 1,305.8 | 27.6 | 1,417.5 | 39,329,536.22 | 188,242,754.11 | 6,378,587.96 | 3.41 |
| ALL | 1h | 1,330.2 | 30.4 | 1,187.3 | 4,365,645.25 | 9,478,665.47 | 465,868.64 | 2.99 |
| ALL | 4h | 1,333.9 | 20.3 | 599.5 | 2,069.92 | 2,601.1 | 431.43 | 0.75 |
| ALL | 1d | 1,332.9 | 23.8 | 832.8 | 5,370.19 | 5,553.72 | 125.13 | 0.72 |
summary_charts(summary=summary)
Run on Resampled History¶
This section repeats the study on resampled prices — alternative histories assembled from the market's own behavior. Whole stretches of real returns are drawn in a new order over the window all markets share, the same stretches for every market so their synchrony survives; the coarser timeframes sample the same path, just as the real timeframes sample the same market.
Inside each stretch the behavior is intact — trends, drawdown regimes, volatility bursts, and the co-movement between markets — only the order of stretches is new. The result is a past the strategy has never seen that still behaves like the market it trades: a stand-in for the future. Performance that repeats here shows the rule rides the market's behavior itself, not one memorized chronology.
def resample_history(real_prices, block_starts, block_bars):
returns = np.diff(real_prices) / real_prices[:-1]
blocks = [returns[start : start + block_bars] for start in block_starts]
resampled_returns = np.concatenate(blocks)[: returns.size]
growth = np.concatenate(([1.0], np.cumprod(1 + resampled_returns)))
return real_prices[0] * growth
rng = np.random.default_rng(0)
base_timeframe = max(TIMEFRAMES, key=lambda timeframe: BARS_PER_YEAR[timeframe])
block_bars = RESAMPLE_BLOCK_DAYS * BARS_PER_YEAR[base_timeframe] // 365
common_len = min(len(prices[(symbol, base_timeframe)]) for symbol in SYMBOLS)
block_count = (common_len + block_bars - 1) // block_bars
block_starts = rng.integers(0, common_len - block_bars, size=block_count)
resampled_prices = {}
for symbol in SYMBOLS:
real_tail = prices[(symbol, base_timeframe)][-common_len:]
base_path = resample_history(
real_prices=real_tail,
block_starts=block_starts,
block_bars=block_bars,
)
for timeframe in TIMEFRAMES:
step = BARS_PER_YEAR[base_timeframe] // BARS_PER_YEAR[timeframe]
resampled_prices[(symbol, timeframe)] = base_path[step - 1 :: step]
for timeframe in TIMEFRAMES:
symbol_prices = [resampled_prices[(symbol, timeframe)] for symbol in SYMBOLS]
resampled_prices[(BASKET_SYMBOL, timeframe)] = basket_prices(symbol_prices=symbol_prices)
resampled_results = {
(symbol, timeframe): analytics(
symbol=symbol,
prices=resampled_prices[(symbol, timeframe)],
bars_per_year=BARS_PER_YEAR[timeframe],
)
for symbol in [*SYMBOLS, BASKET_SYMBOL]
for timeframe in TIMEFRAMES
}
charts(results=resampled_results)
resampled_summary = summarize(results=resampled_results)
left_aligned_table(df=resampled_summary)
| Symbol | Timeframe | Price Change % | Cumulative Win Rate % | Cumulative P&L % | Equity Net | Equity Gross | Cumulative Fees | Rolling Sharpe |
|---|---|---|---|---|---|---|---|---|
| BTCUSDT | 30m | 2,340.1 | 18.3 | 10.8 | 67.85 | 527.81 | 167.48 | 0.04 |
| BTCUSDT | 1h | 2,336.9 | 19.7 | 131.6 | 233.48 | 646.5 | 187.4 | 0.55 |
| BTCUSDT | 4h | 2,348.9 | 22.2 | 242.8 | 534.31 | 669.28 | 73.96 | 0.75 |
| BTCUSDT | 1d | 2,340.7 | 28.4 | 512.1 | 2,274.15 | 2,342.48 | 20.77 | 0.84 |
| ETHUSDT | 30m | 832 | 19.1 | 144.4 | 187.64 | 1,446.26 | 435.36 | 0.45 |
| ETHUSDT | 1h | 825 | 19.3 | 111.1 | 129.37 | 352.83 | 145.3 | 0.34 |
| ETHUSDT | 4h | 833.2 | 22.7 | 387.2 | 1,549.28 | 1,910.59 | 159.99 | 0.96 |
| ETHUSDT | 1d | 779.2 | 29.7 | 935.4 | 4,547.72 | 4,684.36 | 62.38 | 0.59 |
| SOLUSDT | 30m | 15,210.4 | 20.6 | 577.2 | 4,116.69 | 27,984.21 | 2,975.38 | 1.12 |
| SOLUSDT | 1h | 15,289 | 21.2 | 376.5 | 714.18 | 1,880.37 | 465.96 | 0.78 |
| SOLUSDT | 4h | 15,463.4 | 22.9 | 669 | 3,590.95 | 4,490.84 | 448.88 | 0.92 |
| SOLUSDT | 1d | 15,594.7 | 28.4 | 2,603.4 | 154,944.1 | 159,599.48 | 980.96 | 0.7 |
| BNBUSDT | 30m | 5,780.4 | 19.8 | 207.6 | 233.65 | 1,848.35 | 643.6 | 0.47 |
| BNBUSDT | 1h | 5,761.4 | 20.5 | 303.7 | 621.89 | 1,715.15 | 550.19 | 0.69 |
| BNBUSDT | 4h | 5,540.5 | 22.7 | 537.8 | 3,199.51 | 4,031.83 | 370.29 | 0.86 |
| BNBUSDT | 1d | 5,641.4 | 22.8 | 1,112.6 | 4,412.52 | 4,577.94 | 86.63 | 0.52 |
| DOGEUSDT | 30m | 15,851.6 | 17.7 | 787.5 | 336.2 | 2,695.99 | 1,297.45 | 0.56 |
| DOGEUSDT | 1h | 15,731.9 | 17.9 | 961.3 | 2,230.76 | 6,159.79 | 3,592.07 | 0.68 |
| DOGEUSDT | 4h | 15,847.8 | 20.8 | 924.5 | 13,998.93 | 17,556.14 | 1,798.24 | 0.94 |
| DOGEUSDT | 1d | 13,838.4 | 32.3 | 1,874.8 | 63,954.53 | 65,639.33 | 407.33 | 0.7 |
| XRPUSDT | 30m | 633.8 | 17.3 | -101.7 | 5.68 | 47.62 | 73.22 | -0.2 |
| XRPUSDT | 1h | 632.2 | 16.9 | 326.3 | 201.1 | 573.58 | 375.02 | 0.5 |
| XRPUSDT | 4h | 638 | 20.4 | 656.2 | 2,959.68 | 3,702.85 | 415.58 | 0.84 |
| XRPUSDT | 1d | 616.4 | 17.3 | 820.4 | 2,856.42 | 2,950.49 | 57.62 | 0.68 |
| ALL | 30m | 6,774.7 | 27 | 1,520.7 | 52,731,894.17 | 253,909,436.93 | 7,259,561.91 | 2.53 |
| ALL | 1h | 6,762.7 | 23 | 843.6 | 61,924.09 | 152,749.54 | 15,366.8 | 1.39 |
| ALL | 4h | 6,778.6 | 22.7 | 598.3 | 5,740.55 | 7,207.9 | 695.17 | 1.08 |
| ALL | 1d | 6,468.5 | 26.4 | 2,000.9 | 74,949.59 | 77,139.75 | 632.84 | 0.62 |
summary_charts(summary=resampled_summary)
Scoring¶
This section grades the strategy on a 0–100 scale. Every metric is mapped to a score in each symbol × timeframe cell, the per-metric scores are blended into a composite cell score, and the composites average into a single overall strategy score. The scales are fixed, so the same number means the same thing from one study to the next and the grades compare like for like.
- Beats-Hold — how far net equity runs ahead of buy-and-hold, $50 + 25\log_2(E_{\text{net}}/E_{\text{hold}})$: matching buy-and-hold scores 50, doubling it 75, halving it 25.
- Risk-Adjusted — the Rolling Sharpe on a fixed scale, $55\,S + 5$: a Sharpe of 1 scores 60, of roughly 1.7 reaches 100.
- Profitability — absolute growth of capital, $20\log_2(E_{\text{net}}/E_0)$: a 2× ending scores 20, a 32× scores 100.
- Win-Rate — the share of winning trades, $2.5\,(w - 20)$ for a win rate $w$ in percent: 40% scores 50, 60% scores 100.
- Fee-Efficiency — how little trading costs erode the result, $(E_{\text{net}}/E_{\text{gross}} - 0.4)/0.6 \times 100$: paying nothing scores 100, losing a third to fees scores about 50.
- Composite — the weighted blend, $0.35\,\text{Beats-Hold} + 0.30\,\text{Risk-Adjusted} + 0.15\,\text{Profitability} + 0.10\,\text{Win-Rate} + 0.10\,\text{Fee-Efficiency}$.
- Overall Score — the average composite across all cells: the strategy's single headline grade.
SCORE_WEIGHTS = {
"Beats-Hold": 0.35,
"Risk-Adjusted": 0.30,
"Profitability": 0.15,
"Win-Rate": 0.10,
"Fee-Efficiency": 0.10,
}
def clamp_score(value):
return float(max(0.0, min(100.0, value)))
def score_metrics(row):
hold_equity = INITIAL_CASH * (1 + row["Price Change %"] / 100)
net = row["Equity Net"]
gross = row["Equity Gross"]
if net > 0 and hold_equity > 0:
beats_hold = clamp_score(50 + 25 * np.log2(net / hold_equity))
else:
beats_hold = 0.0
risk_adjusted = clamp_score(55 * row["Rolling Sharpe"] + 5)
multiple = net / INITIAL_CASH
profitability = clamp_score(20 * np.log2(multiple)) if multiple > 0 else 0.0
win_rate = clamp_score(2.5 * (row["Cumulative Win Rate %"] - 20))
fee_efficiency = clamp_score((net / gross - 0.4) / 0.6 * 100) if gross > 0 else 0.0
return {
"Beats-Hold": beats_hold,
"Risk-Adjusted": risk_adjusted,
"Profitability": profitability,
"Win-Rate": win_rate,
"Fee-Efficiency": fee_efficiency,
}
def score_cell(row):
metric_scores = score_metrics(row=row)
composite = sum(metric_scores[name] * weight for name, weight in SCORE_WEIGHTS.items())
return composite, metric_scores
def strategy_score(summary):
rows = []
for _, row in summary.iterrows():
composite, metric_scores = score_cell(row=row)
entry = {"Symbol": row["Symbol"], "Timeframe": row["Timeframe"]}
entry.update({name: round(value, 1) for name, value in metric_scores.items()})
entry["Composite"] = round(composite, 1)
rows.append(entry)
score_table = pd.DataFrame(rows)
overall = int(round(score_table["Composite"].mean()))
return overall, score_table
def score_charts(score_table, overall):
metric_names = [
"Beats-Hold",
"Risk-Adjusted",
"Profitability",
"Win-Rate",
"Fee-Efficiency",
"Composite",
]
symbols = list(dict.fromkeys(score_table["Symbol"]))
n_cols = 3
n_rows = 2
col_width = 600
row_height = 300
gap_px = 70
total_w = col_width * n_cols + gap_px * max(n_cols - 1, 0)
total_h = row_height * n_rows
h_spacing = gap_px / total_w
v_spacing = gap_px / total_h
colorscale = [[0.0, "#eef0f2"], [0.5, "#bfe3d3"], [1.0, "#1d9e75"]]
fig = make_subplots(
rows=n_rows,
cols=n_cols,
subplot_titles=metric_names,
horizontal_spacing=h_spacing,
vertical_spacing=v_spacing,
)
for idx, metric in enumerate(metric_names):
row_idx = idx // n_cols + 1
col_idx = idx % n_cols + 1
pivot = score_table.pivot(index="Symbol", columns="Timeframe", values=metric)
pivot = pivot.reindex(index=symbols, columns=TIMEFRAMES)
values = pivot.to_numpy()
fig.add_trace(
go.Heatmap(
z=values,
x=TIMEFRAMES,
y=symbols,
zmin=0,
zmax=100,
colorscale=colorscale,
showscale=False,
text=values,
texttemplate="%{text:.0f}",
textfont=dict(size=11),
hovertemplate="%{y} · %{x}: %{z:.0f}<extra></extra>",
xgap=2,
ygap=2,
),
row=row_idx,
col=col_idx,
)
fig.update_layout(
template="plotly_white",
height=total_h,
width=total_w,
font=dict(size=11),
title=dict(text=f"Overall strategy score: {overall} / 100", x=0.5, font=dict(size=17)),
margin=dict(l=90, r=20, t=100, b=40),
)
fig.update_annotations(font=dict(size=13))
fig.update_yaxes(autorange="reversed")
fig.show()
overall_score, score_table = strategy_score(summary=summary)
score_charts(score_table=score_table, overall=overall_score)
left_aligned_table(df=score_table)
| Symbol | Timeframe | Beats-Hold | Risk-Adjusted | Profitability | Win-Rate | Fee-Efficiency | Composite |
|---|---|---|---|---|---|---|---|
| BTCUSDT | 30m | 0 | 3.4 | 0 | 0 | 0 | 1 |
| BTCUSDT | 1h | 0 | 20.4 | 6 | 0 | 0 | 7 |
| BTCUSDT | 4h | 59.4 | 50.1 | 84 | 8.3 | 54.8 | 54.7 |
| BTCUSDT | 1d | 95.2 | 47.9 | 100 | 11 | 92.3 | 73 |
| ETHUSDT | 30m | 47.2 | 37.4 | 46.7 | 0 | 0 | 34.8 |
| ETHUSDT | 1h | 22.4 | 29.8 | 26.6 | 0 | 0 | 20.7 |
| ETHUSDT | 4h | 100 | 50.6 | 100 | 2.8 | 53 | 70.8 |
| ETHUSDT | 1d | 100 | 43.5 | 100 | 23.5 | 92.9 | 74.7 |
| SOLUSDT | 30m | 40.6 | 56.7 | 79.7 | 1.7 | 0 | 43.3 |
| SOLUSDT | 1h | 37.6 | 56.7 | 79.1 | 3 | 0 | 42.3 |
| SOLUSDT | 4h | 59.2 | 54 | 96.6 | 3.8 | 65.6 | 58.3 |
| SOLUSDT | 1d | 100 | 45.1 | 100 | 9.2 | 93.9 | 73.9 |
| BNBUSDT | 30m | 0 | 33.6 | 40.6 | 0 | 0 | 16.2 |
| BNBUSDT | 1h | 0 | 39.6 | 67.4 | 0 | 0 | 22 |
| BNBUSDT | 4h | 10.6 | 51.2 | 100 | 6.5 | 52.4 | 39.9 |
| BNBUSDT | 1d | 2.4 | 39.6 | 100 | 22 | 91.4 | 39.1 |
| DOGEUSDT | 30m | 0 | 9.9 | 0 | 0 | 0 | 3 |
| DOGEUSDT | 1h | 0 | 28.1 | 0 | 0 | 0 | 8.4 |
| DOGEUSDT | 4h | 69.7 | 42.9 | 100 | 0 | 58.8 | 58.1 |
| DOGEUSDT | 1d | 83 | 40.8 | 100 | 26.8 | 94.2 | 68.4 |
| XRPUSDT | 30m | 0 | 0 | 0 | 0 | 0 | 0 |
| XRPUSDT | 1h | 0 | 8.9 | 0 | 0 | 0 | 2.7 |
| XRPUSDT | 4h | 100 | 36.9 | 61.8 | 0 | 52.5 | 60.6 |
| XRPUSDT | 1d | 52.3 | 22.1 | 8.7 | 0 | 91.3 | 35.4 |
| ALL | 30m | 100 | 100 | 100 | 19 | 0 | 81.9 |
| ALL | 1h | 100 | 100 | 100 | 26 | 10.1 | 83.6 |
| ALL | 4h | 63.2 | 46.2 | 87.4 | 0.8 | 66 | 55.8 |
| ALL | 1d | 97.7 | 44.6 | 100 | 9.5 | 94.5 | 73 |
Conclusion¶
This section judges the strategy. The verdict reads the summary tables above — real and synthetic — where the strategy holds up, where it fails, and whether it is worth pursuing.
Over each symbol's full available Binance history, going long while the close holds above its 50-bar weighted moving average and flat when it drops back is profitable after fees in 23 of 28 symbol × timeframe cells. The five losses are the fastest, whippiest cells — BTC, DOGE, and XRP at 30 minutes, and DOGE and XRP at 1 hour — where the cross fires thousands of times and fees plus whipsaw erode the result. ETH, SOL, BNB, and the basket are profitable at every timeframe.
Against buy-and-hold it wins in 14 of 28 cells — half the table — and the wins have structure: the 4-hour and daily rows of every market except BNB, plus all four basket cells. It loses to holding only where a single market's own drift was unbeatable; BNB rose several-hundred-fold, and the rule trails buy-and-hold in all four BNB cells even as it turns 100 into 409 to 11,714 there.
Risk-adjusted, the edge strengthens as the timeframe slows. Rolling Sharpe is mixed at 30 minutes (BTC −0.03, SOL 0.94, XRP −0.30) and settles into a steady 0.6–0.95 across the 4-hour and daily cells. The equal-weight basket is again the strongest market — averaging the six symbols cancels their noise, so a cross on the smoothed series marks a shared shift in trend rather than one market's flutter, and ALL earns the highest risk-adjusted scores (Rolling Sharpe 3.41 at 30 minutes, 2.99 at 1 hour). Its two fast cells reach six and seven figures, but those lean on all-in compounding and read as the least literal numbers in the table.
Fees remain the binding cost at speed, yet the 50-bar average turns over far less than a shorter one. The 30-minute and 1-hour cells still pay a large share of their gross result back in Cumulative Fees, but most cells clear the drag and the gross-to-net gap all but closes by the daily. Cumulative Win Rate % sits at 16–31% throughout — the trend-following shape where a few large winners carry many small losers.
On a resampled history the edge repeats — 26 of 28 cells profitable, the Rolling Sharpe ladder intact, and the basket again reaching six figures at 30 minutes. It still beats buy-and-hold in 9 of 28 reordered cells. Performance this durable on a history the rule has never seen is the signature of a signal that rides trend structure rather than one memorized chronology.
Caveats. Results come from one historical window with a single fixed averaging period; the basket is six liquid survivors and ALL inherits that survivorship; the strategy is long-only over a decade in which every symbol rose; the resampled run is a single alternative history, not a distribution; the large terminal figures come from compounding all-in; and prices are spot klines while the fee rate models the futures taker rate.
Call: test further. The 50-bar close-versus-average cross is broadly profitable after fees, beats buy-and-hold across a structured half of the table, strengthens under risk adjustment as the timeframe slows, and repeats on a resampled history that stands in for the future. Its weaknesses are contained and understood: the 30-minute single-market cells are fee-and-whipsaw losses to exclude, the win rate is low by design, and a parabolic single-market run like BNB's will always beat timing it. The credible engine is the 4-hour through daily cells and the basket; carry those forward with explicit position sizing and a parameter-robustness sweep before any further claim.