examples: fix and harmonize the strategy backtests across all languages (#324)

The strategy_* examples were only syntax-smoked in CI, never run, which hid two
classes of problem:

1. Python strategy_macd_adx / strategy_bollinger_squeeze passed three separate
   arguments to the candle indicators ADX/ATR, whose .update() takes a single
   candle — a TypeError at runtime — and read the ADX tuple at index 0 (plus_di)
   instead of 2 (adx). Both fixed.

2. The Go / C# / R / Java strategies defaulted to synthetic data and used a
   different (annualised) one-line summary, so they printed wildly different
   numbers from the Rust/Python/Node/C/WASM suite. Rewrite them to the shared
   per-trade backtest (load the bundled BTCUSDT CSV by default, same entry/exit
   logic, same print_summary output).

All nine runnable bindings now print byte-identical backtest summaries on the
same data (MACD+ADX 246 trades / -47.19%, RSI 37 / -17.84%, Bollinger 1 / -7.82%),
verified by diffing each language's output against the Python reference. WASM
shares the same logic and bundled dataset (browser-rendered).
This commit is contained in:
kingchenc
2026-06-17 17:56:22 +02:00
committed by GitHub
parent 2e07c07a40
commit 75eefbbd08
20 changed files with 886 additions and 196 deletions
+71
View File
@@ -42,4 +42,75 @@ public static class Backtest
Console.WriteLine(
$"{name,-26} return={r.TotalReturnPct,8:F2}% sharpe={r.Sharpe,6:F2} maxDD={r.MaxDrawdownPct,6:F2}% trades={r.Trades}");
}
/// <summary>
/// Prints the per-trade backtest summary shared verbatim with the Rust,
/// Python, Node, Go and C example suites (same labels, same numbers).
/// </summary>
public static void PrintSummary(string name, double firstPrice, double lastPrice, int bars,
IReadOnlyList<double> closedTrades, double finalEquity, IReadOnlyList<double> equityCurve)
{
var ci = System.Globalization.CultureInfo.InvariantCulture;
var buyHold = lastPrice / firstPrice;
var stratReturn = finalEquity - 1.0;
var bhReturn = buyHold - 1.0;
int wins = 0, losses = 0;
double best = 0.0, worst = 0.0;
for (var i = 0; i < closedTrades.Count; i++)
{
var r = closedTrades[i];
if (r > 0)
{
wins++;
}
else if (r < 0)
{
losses++;
}
if (i == 0 || r > best)
{
best = r;
}
if (i == 0 || r < worst)
{
worst = r;
}
}
var n = closedTrades.Count;
var mean = n > 0 ? closedTrades.Average() : 0.0;
var variance = n > 1 ? closedTrades.Sum(x => (x - mean) * (x - mean)) / (n - 1) : 0.0;
var sharpe = variance > 0 ? mean / Math.Sqrt(variance) : 0.0;
var peak = equityCurve.Count > 0 ? equityCurve[0] : 1.0;
var maxDd = 0.0;
foreach (var eq in equityCurve)
{
if (eq > peak)
{
peak = eq;
}
var dd = (peak - eq) / peak;
if (dd > maxDd)
{
maxDd = dd;
}
}
Console.WriteLine($"=== {name} ===");
Console.WriteLine(string.Create(ci, $"{"Bars:",-23}{bars}"));
Console.WriteLine(string.Create(ci, $"{"Trades:",-23}{n} (W{wins} / L{losses})"));
Console.WriteLine(string.Create(ci, $"{"Strategy return:",-23}{stratReturn * 100:+0.00;-0.00}%"));
Console.WriteLine(string.Create(ci, $"{"Buy & Hold return:",-23}{bhReturn * 100:+0.00;-0.00}%"));
Console.WriteLine(string.Create(ci, $"{"Excess over BH:",-23}{(stratReturn - bhReturn) * 100:+0.00;-0.00}%"));
Console.WriteLine(string.Create(ci, $"{"Max drawdown:",-23}{maxDd * 100:0.00}%"));
Console.WriteLine(string.Create(ci, $"{"Per-trade Sharpe:",-23}{sharpe:0.00} (mean {mean:+0.0000;-0.0000}, stddev {Math.Sqrt(variance):0.0000})"));
Console.WriteLine(string.Create(ci, $"{"Best / worst trade:",-23}{best * 100:+0.00;-0.00}% / {worst * 100:+0.00;-0.00}%"));
Console.WriteLine();
Console.WriteLine("NOTE: Educational example — fees, slippage, funding costs and tax " +
"effects are simplified or omitted. Past performance is not " +
"indicative of future results.");
}
}
+11
View File
@@ -58,4 +58,15 @@ public static class MarketData
return bars;
}
/// <summary>
/// Loads one of the checked-in datasets under examples/data, resolved
/// relative to this source file so it works from any working directory.
/// </summary>
public static Bar[] BundledCandles(string filename,
[System.Runtime.CompilerServices.CallerFilePath] string self = "")
{
var dir = Path.GetDirectoryName(self)!;
return LoadOhlcvCsv(Path.Combine(dir, "..", "..", "data", filename));
}
}
@@ -1,46 +1,91 @@
using Wickra;
using Wickra.Examples;
// Breakout: when Bollinger bandwidth is tight (a "squeeze") and price closes above the
// upper band, go long with an ATR(14) trailing stop.
var bars = args.Length > 0 ? MarketData.LoadOhlcvCsv(args[0]) : MarketData.SyntheticCandles(2000);
// Strategy example: Bollinger-squeeze breakout with an ATR(14) trailing stop.
//
// Enters long when Bollinger bandwidth makes a new SqueezeLookback low (a
// volatility squeeze) and price closes above the upper band; exits on an ATR(14)
// trailing stop or when the upper band falls back below the entry. 0.1% fees per
// trade. The C# counterpart of examples/python/strategy_bollinger_squeeze.py,
// printing the same summary. Uses the checked-in examples/data/btcusdt-1d.csv
// dataset (pass a CSV path to override).
const double Fee = 0.001;
const double AtrStopMult = 2.0;
const int SqueezeLookback = 180;
var bars = args.Length > 0 ? MarketData.LoadOhlcvCsv(args[0]) : MarketData.BundledCandles("btcusdt-1d.csv");
using var bollinger = new BollingerBands(20, 2.0);
using var atr = new Atr(14);
var returns = new List<double>();
var trades = 0;
var inPosition = false;
var entry = 0.0;
var stop = 0.0;
var entryPrice = 0.0;
var stopLevel = 0.0;
var closedTrades = new List<double>();
var equity = 1.0;
var equityCurve = new List<double>();
var bwWindow = new Queue<double>();
foreach (var b in bars)
{
var bands = bollinger.Update(b.Close);
var atrValue = atr.Update(b.Open, b.High, b.Low, b.Close, b.Volume, b.Timestamp);
var price = b.Close;
equityCurve.Add(inPosition ? equity * (price / entryPrice) : equity);
if (bands is not { } band || !double.IsFinite(atrValue))
{
continue;
}
var bandwidth = band.Middle != 0.0 ? (band.Upper - band.Lower) / band.Middle : double.MaxValue;
if (!inPosition && bandwidth < 0.06 && b.Close > band.Upper)
if (Math.Abs(band.Middle) <= 1e-12)
{
inPosition = true;
entry = b.Close;
stop = b.Close - 2.0 * atrValue;
trades++;
continue;
}
else if (inPosition)
var bandwidth = (band.Upper - band.Lower) / band.Middle;
bwWindow.Enqueue(bandwidth);
if (bwWindow.Count > SqueezeLookback)
{
stop = Math.Max(stop, b.Close - 2.0 * atrValue); // trail the stop up
if (b.Close < stop)
bwWindow.Dequeue();
}
if (bwWindow.Count < SqueezeLookback)
{
continue;
}
var minBw = bwWindow.Min();
if (inPosition)
{
if (price < stopLevel || band.Upper < entryPrice)
{
returns.Add((b.Close - entry) / entry);
var tradeRet = price / entryPrice - 1.0;
closedTrades.Add(tradeRet);
equity *= (1.0 + tradeRet) * (1.0 - Fee);
inPosition = false;
}
}
else
{
var isNewLow = Math.Abs(bandwidth - minBw) < 1e-12;
if (isNewLow && price > band.Upper)
{
entryPrice = price;
stopLevel = price - AtrStopMult * atrValue;
equity *= 1.0 - Fee;
inPosition = true;
}
}
}
Backtest.Print("Bollinger squeeze", Backtest.Summarize(returns, trades));
if (inPosition)
{
var tradeRet = bars[^1].Close / entryPrice - 1.0;
closedTrades.Add(tradeRet);
equity *= (1.0 + tradeRet) * (1.0 - Fee);
}
Backtest.PrintSummary("Bollinger Squeeze Breakout (1d, BTCUSDT)",
bars[0].Close, bars[^1].Close, bars.Length, closedTrades, equity, equityCurve);
+40 -16
View File
@@ -1,42 +1,66 @@
using Wickra;
using Wickra.Examples;
// Trend follower: enter long on a MACD histogram cross up, but only when ADX(14) > 20
// confirms a trend; exit when the histogram crosses back below zero.
var bars = args.Length > 0 ? MarketData.LoadOhlcvCsv(args[0]) : MarketData.SyntheticCandles(2000);
// Strategy example: MACD crossover with ADX trend-strength filter.
//
// Enters long on a MACD histogram cross up (the histogram turns positive) while
// ADX(14) > 20 (a directional market); exits on the opposite MACD crossover
// regardless of ADX. 0.1% fees per trade. The C# counterpart of
// examples/python/strategy_macd_adx.py, printing the same summary. Uses the
// checked-in examples/data/btcusdt-1h.csv dataset (pass a CSV path to override).
const double Fee = 0.001;
const double AdxFloor = 20.0;
var bars = args.Length > 0 ? MarketData.LoadOhlcvCsv(args[0]) : MarketData.BundledCandles("btcusdt-1h.csv");
using var macd = new MacdIndicator(12, 26, 9);
using var adx = new Adx(14);
var returns = new List<double>();
var trades = 0;
var inPosition = false;
var entry = 0.0;
var prevHistogram = double.NaN;
var entryPrice = 0.0;
var closedTrades = new List<double>();
var equity = 1.0;
var equityCurve = new List<double>();
bool? prevSign = null;
foreach (var b in bars)
{
var m = macd.Update(b.Close);
var a = adx.Update(b.Open, b.High, b.Low, b.Close, b.Volume, b.Timestamp);
var price = b.Close;
equityCurve.Add(inPosition ? equity * (price / entryPrice) : equity);
if (m is not { } macdValue || a is not { } adxValue)
{
continue;
}
var trending = adxValue.Adx > 20.0;
if (!inPosition && trending && double.IsFinite(prevHistogram) && prevHistogram <= 0.0 && macdValue.Histogram > 0.0)
var histSign = macdValue.Histogram > 0.0;
var crossUp = prevSign == false && histSign;
var crossDown = prevSign == true && !histSign;
prevSign = histSign;
if (!inPosition && crossUp && adxValue.Adx > AdxFloor)
{
entryPrice = price;
equity *= 1.0 - Fee;
inPosition = true;
entry = b.Close;
trades++;
}
else if (inPosition && macdValue.Histogram < 0.0)
else if (inPosition && crossDown)
{
returns.Add((b.Close - entry) / entry);
var tradeRet = price / entryPrice - 1.0;
closedTrades.Add(tradeRet);
equity *= (1.0 + tradeRet) * (1.0 - Fee);
inPosition = false;
}
prevHistogram = macdValue.Histogram;
}
Backtest.Print("MACD + ADX trend", Backtest.Summarize(returns, trades));
if (inPosition)
{
var tradeRet = bars[^1].Close / entryPrice - 1.0;
closedTrades.Add(tradeRet);
equity *= (1.0 + tradeRet) * (1.0 - Fee);
}
Backtest.PrintSummary("MACD + ADX Trend Filter (1h, BTCUSDT)",
bars[0].Close, bars[^1].Close, bars.Length, closedTrades, equity, equityCurve);
@@ -1,34 +1,57 @@
using Wickra;
using Wickra.Examples;
// Mean reversion: go long when RSI(14) drops below 30, exit when it recovers above 50.
var bars = args.Length > 0 ? MarketData.LoadOhlcvCsv(args[0]) : MarketData.SyntheticCandles(2000);
// Strategy example: RSI(14) mean-reversion.
//
// Go long when RSI(14) drops below 30 (oversold), exit when it recovers above
// 70 (overbought). 0.1% fees per trade. The C# counterpart of
// examples/python/strategy_rsi_mean_reversion.py, printing the same summary.
// Uses the checked-in examples/data/btcusdt-1h.csv dataset (pass a CSV path to override).
const double Fee = 0.001;
const double Oversold = 30.0;
const double Overbought = 70.0;
var bars = args.Length > 0 ? MarketData.LoadOhlcvCsv(args[0]) : MarketData.BundledCandles("btcusdt-1h.csv");
using var rsi = new Rsi(14);
var returns = new List<double>();
var trades = 0;
var inPosition = false;
var entry = 0.0;
var entryPrice = 0.0;
var closedTrades = new List<double>();
var equity = 1.0;
var equityCurve = new List<double>();
foreach (var b in bars)
{
var value = rsi.Update(b.Close);
var price = b.Close;
equityCurve.Add(inPosition ? equity * (price / entryPrice) : equity);
if (!double.IsFinite(value))
{
continue;
}
if (!inPosition && value < 30.0)
if (!inPosition && value < Oversold)
{
entryPrice = price;
equity *= 1.0 - Fee;
inPosition = true;
entry = b.Close;
trades++;
}
else if (inPosition && value > 50.0)
else if (inPosition && value > Overbought)
{
returns.Add((b.Close - entry) / entry);
var tradeRet = price / entryPrice - 1.0;
closedTrades.Add(tradeRet);
equity *= (1.0 + tradeRet) * (1.0 - Fee);
inPosition = false;
}
}
Backtest.Print("RSI mean-reversion", Backtest.Summarize(returns, trades));
if (inPosition)
{
var tradeRet = bars[^1].Close / entryPrice - 1.0;
closedTrades.Add(tradeRet);
equity *= (1.0 + tradeRet) * (1.0 - Fee);
}
Backtest.PrintSummary("RSI Mean-Reversion (1h, BTCUSDT)",
bars[0].Close, bars[^1].Close, bars.Length, closedTrades, equity, equityCurve);