crypto_trend follows nine breakout periods with Donchian-middle stops, volatility-targeted weights under the 35%/20% caps and a monthly top-10 universe. equity_momentum reviews on the last close of each week with the SPY filter, inverse-volatility weights and an ATR trailing stop. equity_meanrev buys RSI(2) dips above the 200-session average, sized for a fixed risk, and exits at the close. The engine gains what the rules need: exits at the same close, a stop set at a distance from the price obtained, data-only instruments such as SPY, the trading calendar, the reference equity of the strategy's share and the equity history. Every strategy passes the look-ahead check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
563 lines
28 KiB
C#
563 lines
28 KiB
C#
using Anubis.Backtest;
|
||
using Anubis.Data;
|
||
using Anubis.Strategies;
|
||
using Anubis.Trading;
|
||
|
||
namespace Anubis.Tests;
|
||
|
||
internal static class StrategyData
|
||
{
|
||
public static readonly DateOnly Start = new(2024, 1, 1);
|
||
|
||
public static InstrumentSpec Coin(string coin) => new(Venues.Okx, coin + "-EUR", coin, AssetClasses.Crypto, "EUR")
|
||
{
|
||
BaseCurrency = coin,
|
||
TickSize = 0.0001m,
|
||
LotSize = 0.00000001m,
|
||
MinSize = 0.00000001m,
|
||
MinNotional = 1m,
|
||
Status = "live",
|
||
};
|
||
|
||
public static InstrumentSpec Share(string symbol) => new(Venues.Alpaca, symbol, symbol, AssetClasses.Equity, "USD")
|
||
{
|
||
Fractionable = true,
|
||
Status = "active",
|
||
Exchange = "NASDAQ",
|
||
TickSize = 0.01m,
|
||
LotSize = 0.000000001m,
|
||
MinNotional = 1m,
|
||
};
|
||
|
||
/// <summary>Bars with the given closes on consecutive days; high and low a fixed distance around the close.</summary>
|
||
public static List<DailyBar> FromCloses(IReadOnlyList<double> closes, DateOnly? from = null, double range = 0, double volume = 10_000)
|
||
{
|
||
var day = from ?? Start;
|
||
return [.. closes.Select((c, i) => new DailyBar(day.AddDays(i), c, c + range, c - range, c, volume))];
|
||
}
|
||
|
||
/// <summary>Bars on business days (no weekends) from a Monday.</summary>
|
||
public static List<DailyBar> OnBusinessDays(IReadOnlyList<DailyBar> bars, DateOnly from)
|
||
{
|
||
var days = BusinessDays(from, bars.Count);
|
||
return [.. bars.Select((b, i) => b with { Day = days[i] })];
|
||
}
|
||
|
||
public static List<DateOnly> BusinessDays(DateOnly from, int count)
|
||
{
|
||
var result = new List<DateOnly>(count);
|
||
for (var d = from; result.Count < count; d = d.AddDays(1))
|
||
{
|
||
if (d.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
|
||
{
|
||
result.Add(d);
|
||
}
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
/// <summary>A steady rise with a tiny alternating wobble: every period of crypto_trend is on, volatility near 1%.</summary>
|
||
public static List<DailyBar> SteadyRise(int days, double start = 100, double volume = 10_000) =>
|
||
FromCloses([.. Enumerable.Range(0, days).Select(i => start * Math.Pow(1.001, i) * (1 + (0.0005 * (i % 2))))], volume: volume);
|
||
|
||
public static BarSeries Series(IReadOnlyList<DailyBar> bars, InstrumentSpec? spec = null) =>
|
||
new BacktestInstrument(spec ?? Coin("BTC"), bars).SeriesThrough(bars[^1].Day);
|
||
|
||
public static BacktestDataset Crypto(params (string Coin, IReadOnlyList<DailyBar> Bars)[] coins) =>
|
||
new(coins.Select(c => new BacktestInstrument(Coin(c.Coin), c.Bars)), "EUR");
|
||
}
|
||
|
||
/// <summary>Indicators and the three base strategies (issues #38, #39, #40; SPEC 8.1–8.3).</summary>
|
||
[TestClass]
|
||
public sealed class StrategyTests
|
||
{
|
||
// ---- Indicators, against values computed by hand ----
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void IndicatorsGiveTheValuesComputedByHand()
|
||
{
|
||
var closes = StrategyData.Series(StrategyData.FromCloses([1, 2, 3, 4, 5]));
|
||
Assert.AreEqual(4d, Indicators.Sma(closes, 3));
|
||
Assert.IsNull(Indicators.Sma(closes, 6));
|
||
|
||
// True ranges: max(11−9, |11−9|, |9−9|) = 2; max(3, |12−10|, |9−10|) = 3; max(4, |11−11|, |7−11|) = 4.
|
||
var bars = StrategyData.Series(
|
||
[
|
||
new DailyBar(StrategyData.Start, 9, 10, 8, 9, 1),
|
||
new DailyBar(StrategyData.Start.AddDays(1), 10, 11, 9, 10, 1),
|
||
new DailyBar(StrategyData.Start.AddDays(2), 11, 12, 9, 11, 1),
|
||
new DailyBar(StrategyData.Start.AddDays(3), 9, 11, 7, 8, 1),
|
||
]);
|
||
Assert.AreEqual(3d, Indicators.Atr(bars, 3));
|
||
Assert.AreEqual(3.5d, Indicators.Atr(bars, 2));
|
||
|
||
// RSI(2) on 10, 11, 10,5, 12: average gain 0,5 and loss 0,25 on the first two changes; then +1,5 gives
|
||
// gain (0,5 + 1,5) / 2 = 1 and loss 0,25 / 2 = 0,125: RS 8, RSI 100 − 100 / 9.
|
||
Assert.AreEqual(100 - (100 / 9d), Indicators.Rsi(StrategyData.Series(StrategyData.FromCloses([10, 11, 10.5, 12])), 2)!.Value, 1e-12);
|
||
|
||
// 121 / 100 − 1, skipping the last close.
|
||
Assert.AreEqual(0.21, Indicators.Momentum(StrategyData.Series(StrategyData.FromCloses([100, 110, 121, 133.1])), 2, 1)!.Value, 1e-12);
|
||
|
||
// Returns +10% and −10%: sample standard deviation √0,02, times √365.
|
||
Assert.AreEqual(Math.Sqrt(0.02) * Math.Sqrt(365), Indicators.Volatility(StrategyData.Series(StrategyData.FromCloses([100, 110, 99])), 2, 365)!.Value, 1e-12);
|
||
}
|
||
|
||
// ---- crypto_trend ----
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void ThePeriodsTurnOnAtANewHighAndOffBelowYesterdaysStop()
|
||
{
|
||
// Periods 2 and 3, flat bars (high = low = close) so only the closes count.
|
||
var settings = new CryptoTrendSettings { Periods = [2, 3], MaxStop = 0.15 };
|
||
var bars = StrategyData.FromCloses([10, 10, 10, 12, 13, 12.4, 12.6]);
|
||
bars[6] = bars[6] with { Low = 12.0 };
|
||
var tracker = new TrendTracker();
|
||
|
||
// Day 3, close 12: both periods beat their previous highs (10); stops at the middle of the last N closes, 11.
|
||
tracker.Advance(StrategyData.Series(bars[..4]), settings);
|
||
CollectionAssert.AreEqual(new[] { true, true }, tracker.Active.ToArray());
|
||
Assert.AreEqual(1d, tracker.Ensemble);
|
||
Assert.AreEqual(11d, tracker.ServerStop);
|
||
|
||
// Day 4, close 13: stops rise to 12,5 and 11,5; the server stop is the lowest, 11,5.
|
||
tracker.Advance(StrategyData.Series(bars[..5]), settings);
|
||
Assert.AreEqual(11.5d, tracker.ServerStop);
|
||
|
||
// Day 5, close 12,4: below the 2-day stop of yesterday (12,5), so that period turns off; the 3-day one stays,
|
||
// its stop rising to the middle of 12, 13, 12,4 = 12,5. e = 0,5.
|
||
tracker.Advance(StrategyData.Series(bars[..6]), settings);
|
||
CollectionAssert.AreEqual(new[] { false, true }, tracker.Active.ToArray());
|
||
Assert.AreEqual(0.5d, tracker.Ensemble);
|
||
Assert.AreEqual(12.5d, tracker.ServerStop);
|
||
|
||
// Day 6: the low (12) touches the server stop during the day. Every period goes back to 0, and the close of
|
||
// 12,6 is not a new high for either: no stop, no position.
|
||
tracker.Advance(StrategyData.Series(bars), settings);
|
||
CollectionAssert.AreEqual(new[] { false, false }, tracker.Active.ToArray());
|
||
Assert.AreEqual(0d, tracker.Ensemble);
|
||
Assert.IsNull(tracker.ServerStop);
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheServerStopRisesStaysWithin15PercentAndFallsOnlyWhenAPeriodTurnsOn()
|
||
{
|
||
var tracker = new TrendTracker();
|
||
|
||
// Never more than 15% below the close: the middle of 10 and 20 is 15, the cap 17.
|
||
tracker.Advance(StrategyData.Series(StrategyData.FromCloses([10, 10, 20])), new CryptoTrendSettings { Periods = [2] });
|
||
Assert.AreEqual(17d, tracker.ServerStop);
|
||
|
||
// With a loose cap: the 2-day period alone lifts the stop to 11, 13, 15; on day 5 the 5-day period turns on
|
||
// with its stop at the middle of 10…17 = 13,5, and the server stop comes down to it.
|
||
var loose = new CryptoTrendSettings { Periods = [2, 5], MaxStop = 0.5 };
|
||
var bars = StrategyData.FromCloses([10, 10, 12, 14, 16, 17]);
|
||
var stops = new List<double?>();
|
||
for (var n = 3; n <= bars.Count; n++)
|
||
{
|
||
stops.Add(new TrendTracker().Advance(StrategyData.Series(bars[..n]), loose).ServerStop);
|
||
}
|
||
|
||
CollectionAssert.AreEqual(new double?[] { 11, 13, 15, 13.5 }, stops);
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void WalkingTheBarsOnceOrDayByDayGivesTheSameState()
|
||
{
|
||
var bars = BacktestData.Walk(700, 11, start: 30_000, volatility: 0.04);
|
||
var settings = new CryptoTrendSettings();
|
||
var once = new TrendTracker().Advance(StrategyData.Series(bars), settings);
|
||
var stepwise = new TrendTracker();
|
||
for (var n = 1; n <= bars.Count; n++)
|
||
{
|
||
stepwise.Advance(StrategyData.Series([.. bars.Take(n)]), settings);
|
||
}
|
||
|
||
Assert.AreEqual(once.Ensemble, stepwise.Ensemble);
|
||
Assert.AreEqual(once.ServerStop, stepwise.ServerStop);
|
||
CollectionAssert.AreEqual(once.Active.ToArray(), stepwise.Active.ToArray());
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void WeightsFollowTheCapsThenShrinkTogether()
|
||
{
|
||
// Six coins in a steady rise: e = 1 and a volatility near 1%, so every raw weight hits its cap. 35% for BTC
|
||
// and ETH, 20% for the others: 150% in all, so everything shrinks by 1,5.
|
||
var coins = new[] { "BTC", "ETH", "SOL", "ADA", "XRP", "DOT" };
|
||
var data = StrategyData.Crypto([.. coins.Select(c => (c, (IReadOnlyList<DailyBar>)StrategyData.SteadyRise(450)))]);
|
||
var last = data.Sessions[^1];
|
||
var decision = BacktestEngine.DecideOnce(new CryptoTrend(), data, PortfolioState.OnlyCash(10_000m), last);
|
||
var weights = decision.Proposed.ToDictionary(i => i.Symbol, i => i.TargetWeight);
|
||
Assert.AreEqual(0.233333m, weights["BTC-EUR"]);
|
||
Assert.AreEqual(0.233333m, weights["ETH-EUR"]);
|
||
foreach (var other in new[] { "SOL-EUR", "ADA-EUR", "XRP-EUR", "DOT-EUR" })
|
||
{
|
||
Assert.AreEqual(0.133333m, weights[other]);
|
||
}
|
||
|
||
Assert.IsTrue(decision.Proposed.All(i => i.Reason == CryptoTrend.Reasons.Entry && i.Stop > 0m));
|
||
|
||
// Alone, bitcoin stops at its cap.
|
||
var alone = BacktestEngine.DecideOnce(new CryptoTrend(), StrategyData.Crypto(("BTC", StrategyData.SteadyRise(450))), PortfolioState.OnlyCash(10_000m), last);
|
||
Assert.AreEqual(0.35m, alone.Proposed.Single().TargetWeight);
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void APositionIsResizedOnlyBeyondTheThresholds()
|
||
{
|
||
var bars = StrategyData.SteadyRise(450);
|
||
var data = StrategyData.Crypto(("BTC", bars));
|
||
var last = data.Sessions[^1];
|
||
var close = Math.Round((decimal)bars[^1].Close, 8);
|
||
|
||
IReadOnlyList<Intent> At(decimal weight)
|
||
{
|
||
var quantity = weight * 10_000m / close;
|
||
var state = new PortfolioState(10_000m - (quantity * close), new Dictionary<string, Holding> { ["BTC-EUR"] = new(quantity, close, null, StrategyData.Start) });
|
||
return BacktestEngine.DecideOnce(new CryptoTrend(), data, state, last).Proposed;
|
||
}
|
||
|
||
// Target 35%. At 30% the gap (5 points) is within 20% of the target (7 points): only the stop moves.
|
||
var near = At(0.30m).Single();
|
||
Assert.IsNull(near.TargetWeight);
|
||
Assert.AreEqual(CryptoTrend.Reasons.StopMoved, near.Reason);
|
||
|
||
// At 25% the gap (10 points) is beyond both thresholds: back to 35%.
|
||
var far = At(0.25m).Single();
|
||
Assert.AreEqual(0.35m, far.TargetWeight);
|
||
Assert.AreEqual(CryptoTrend.Reasons.Increase, far.Reason);
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheUniverseIsTheTopTenOnTheFirstOfTheMonthWithoutStablecoinsOrYoungCoins()
|
||
{
|
||
// Twelve coins with growing traded value, a stablecoin with the largest of all, a coin listed 200 days ago.
|
||
var instruments = new List<BacktestInstrument>();
|
||
for (var k = 1; k <= 12; k++)
|
||
{
|
||
instruments.Add(new BacktestInstrument(StrategyData.Coin("C" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)), StrategyData.SteadyRise(450, volume: 10_000 * k)));
|
||
}
|
||
|
||
instruments.Add(new BacktestInstrument(StrategyData.Coin("USDC"), StrategyData.FromCloses([.. Enumerable.Repeat(1d, 450)], volume: 1e12)));
|
||
instruments.Add(new BacktestInstrument(StrategyData.Coin("NEW"), StrategyData.FromCloses([.. Enumerable.Repeat(100d, 200)], from: StrategyData.Start.AddDays(250), volume: 1e9)));
|
||
var data = new BacktestDataset(instruments, "EUR");
|
||
var strategy = new CryptoTrend();
|
||
var day = new DateOnly(2025, 3, 20);
|
||
UniverseContext Context(DateOnly d) => new(d, [.. data.Instruments.Select(i => i.Symbol)])
|
||
{
|
||
Bars = s => data[s]!.SeriesThrough(d),
|
||
Spec = s => data[s]?.Spec,
|
||
};
|
||
|
||
var universe = strategy.Universe(Context(day));
|
||
CollectionAssert.AreEqual(Enumerable.Range(3, 10).Reverse().Select(k => "C" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + "-EUR").ToList(), universe.ToList());
|
||
|
||
// Live, the spread is known: one too wide is out, and the 11th by value comes in.
|
||
var live = new CryptoTrend().Universe(Context(day) with { SpreadBp = s => s == "C12-EUR" ? 25 : 5 });
|
||
CollectionAssert.DoesNotContain(live.ToList(), "C12-EUR");
|
||
CollectionAssert.Contains(live.ToList(), "C02-EUR");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void ACoinThatLeftTheUniverseIsManagedButNeverBought()
|
||
{
|
||
// A young coin (not in the universe) held at 10% in a steady rise: its target would be its cap, 20%.
|
||
var data = StrategyData.Crypto(("BTC", StrategyData.SteadyRise(450)), ("NEW", StrategyData.SteadyRise(450).GetRange(150, 300)));
|
||
var last = data.Sessions[^1];
|
||
var close = Math.Round((decimal)data["NEW-EUR"]!.Bars[^1].Close, 8);
|
||
var quantity = 1_000m / close;
|
||
var state = new PortfolioState(9_000m, new Dictionary<string, Holding> { ["NEW-EUR"] = new(quantity, close, null, last.AddDays(-10)) });
|
||
var intents = BacktestEngine.DecideOnce(new CryptoTrend(), data, state, last).Proposed;
|
||
var coin = intents.Single(i => i.Symbol == "NEW-EUR");
|
||
Assert.IsNull(coin.TargetWeight, "No purchase for a coin out of the universe.");
|
||
Assert.IsNotNull(coin.Stop);
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void CryptoTrendDecidesOnTheMidnightUtcClose()
|
||
{
|
||
// The day's bar opens and closes at 00:00 UTC (trap 23): the decision comes at the close, at midnight.
|
||
var times = new List<DateTimeOffset>();
|
||
var data = StrategyData.Crypto(("BTC", BacktestData.Walk(30, 3, from: StrategyData.Start)));
|
||
BacktestEngine.Run(new Recording(new CryptoTrend(), times), data);
|
||
Assert.HasCount(30, times);
|
||
for (var i = 0; i < times.Count; i++)
|
||
{
|
||
Assert.AreEqual(new DateTimeOffset(StrategyData.Start.AddDays(i + 1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), times[i]);
|
||
}
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void CryptoTrendDoesNotLookAhead()
|
||
{
|
||
var data = StrategyData.Crypto(
|
||
("BTC", BacktestData.Walk(900, 21, start: 30_000, drift: 0.001, volatility: 0.035, from: StrategyData.Start)),
|
||
("ETH", BacktestData.Walk(900, 22, start: 2_000, drift: 0.0008, volatility: 0.045, from: StrategyData.Start)),
|
||
("SOL", BacktestData.Walk(900, 23, start: 50, drift: 0.0005, volatility: 0.06, from: StrategyData.Start)));
|
||
var result = LookAheadCheck.Run(_ => new CryptoTrend(new CryptoTrendSettings { MinAgeDays = 100, MinValue = 0 }), data);
|
||
Assert.IsTrue(result.Passed, string.Join("\n", result.Mismatches.Take(3)));
|
||
var run = BacktestEngine.Run(new CryptoTrend(new CryptoTrendSettings { MinAgeDays = 100, MinValue = 0 }), data);
|
||
Assert.IsGreaterThan(5, run.Fills.Count, "The check must look at a strategy that trades.");
|
||
}
|
||
|
||
// ---- equity_momentum ----
|
||
|
||
private static readonly DateOnly Monday = new(2022, 1, 3);
|
||
|
||
/// <summary>Thirty stocks with different drifts, SPY as data only, on business days.</summary>
|
||
private static BacktestDataset Stocks(int sessions, double spyDrift, int count = 30, ulong seed = 100)
|
||
{
|
||
var instruments = new List<BacktestInstrument>();
|
||
for (var k = 0; k < count; k++)
|
||
{
|
||
var bars = BacktestData.Walk(sessions, seed + (ulong)k, start: 50 + k, drift: 0.0002 * (k - 10), volatility: 0.015 + (0.0005 * k));
|
||
instruments.Add(new BacktestInstrument(StrategyData.Share("S" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)),
|
||
StrategyData.OnBusinessDays([.. bars.Select(b => b with { Volume = 100_000 })], Monday)));
|
||
}
|
||
|
||
var spy = BacktestData.Walk(sessions, seed + 999, start: 400, drift: spyDrift, volatility: 0.008);
|
||
instruments.Add(new BacktestInstrument(StrategyData.Share("SPY") with { IsFund = true }, StrategyData.OnBusinessDays([.. spy], Monday)));
|
||
return new BacktestDataset(instruments, "USD", dataOnly: ["SPY"]);
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void TheWeeklyReviewIsTheLastCloseBeforeANewWeek()
|
||
{
|
||
StrategyContext At(DateOnly day, DateOnly? next) => new(day, default, [], new PortfolioView(0m, 0m, new Dictionary<string, Holding>()), _ => BarSeries.Empty, _ => null)
|
||
{
|
||
NextSession = next,
|
||
};
|
||
|
||
var friday = new DateOnly(2026, 4, 3);
|
||
Assert.IsTrue(EquityMomentum.IsReview(At(friday, friday.AddDays(3))));
|
||
Assert.IsFalse(EquityMomentum.IsReview(At(friday.AddDays(-1), friday)));
|
||
// Good Friday closed: Thursday is the last session of the week.
|
||
Assert.IsTrue(EquityMomentum.IsReview(At(friday.AddDays(-1), friday.AddDays(3))));
|
||
// A Monday holiday: the review on Friday, orders on Tuesday.
|
||
Assert.IsTrue(EquityMomentum.IsReview(At(friday, friday.AddDays(4))));
|
||
Assert.IsFalse(EquityMomentum.IsReview(At(friday, null)));
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void MomentumBuysOnTheFirstSessionOfTheWeekOnlyWhileTheMarketRises()
|
||
{
|
||
var rising = BacktestEngine.Run(new EquityMomentum(), Stocks(520, 0.001));
|
||
var buys = rising.Fills.Where(f => f.Side == OrderSide.Buy && f.Reason == EquityMomentum.Reasons.Entry).ToList();
|
||
Assert.IsNotEmpty(buys);
|
||
// Every purchase at the open of the first session of its week (here always a Monday).
|
||
Assert.IsTrue(buys.All(f => f.Day.DayOfWeek == DayOfWeek.Monday), string.Join(", ", buys.Select(f => f.Day)));
|
||
Assert.IsFalse(rising.Fills.Any(f => f.Symbol == "SPY"), "SPY is data, never an instrument.");
|
||
|
||
// At most 12 positions, no target above the 15% cap.
|
||
var entries = rising.Decisions.SelectMany(d => d.Proposed).Where(i => i.TargetWeight > 0m).ToList();
|
||
Assert.IsTrue(entries.All(i => i.TargetWeight <= 0.15m));
|
||
Assert.IsTrue(rising.Decisions.All(d => d.Proposed.Count(i => i.Reason == EquityMomentum.Reasons.Entry) <= 12));
|
||
|
||
// SPY below its 200-day average: no purchase at all.
|
||
var falling = BacktestEngine.Run(new EquityMomentum(), Stocks(520, -0.002));
|
||
Assert.IsFalse(falling.Fills.Any(f => f.Side == OrderSide.Buy));
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void MomentumStopsOnlyRise()
|
||
{
|
||
var run = BacktestEngine.Run(new EquityMomentum(), Stocks(520, 0.001));
|
||
var stops = run.Decisions.SelectMany(d => d.Proposed.Where(i => i.Reason == EquityMomentum.Reasons.StopMoved).Select(i => (d.Day, i.Symbol, Stop: i.Stop!.Value))).ToList();
|
||
Assert.IsNotEmpty(stops);
|
||
foreach (var group in stops.GroupBy(s => s.Symbol))
|
||
{
|
||
var list = group.OrderBy(s => s.Day).ToList();
|
||
for (var i = 1; i < list.Count; i++)
|
||
{
|
||
// A new holding period may start lower; within one, every move is up.
|
||
var exited = run.Fills.Any(f => f.Symbol == group.Key && f.Side == OrderSide.Sell && f.Day > list[i - 1].Day && f.Day <= list[i].Day);
|
||
Assert.IsTrue(exited || list[i].Stop > list[i - 1].Stop, $"{group.Key} {list[i - 1]} → {list[i]}");
|
||
}
|
||
}
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void MomentumSellsAStockBelowItsAverageAtTheReview()
|
||
{
|
||
var data = Stocks(520, 0.001);
|
||
var friday = data.Sessions.Last(d => d.DayOfWeek == DayOfWeek.Friday && d < data.Sessions[^1]);
|
||
// S00 drifts down: it is below its 100-session average.
|
||
var bars = data["S00"]!.SeriesThrough(friday);
|
||
Assert.IsLessThan(Indicators.Sma(bars, 100)!.Value, bars.Close(bars.Count - 1));
|
||
var close = Math.Round((decimal)bars.Close(bars.Count - 1), 2);
|
||
var state = new PortfolioState(9_000m, new Dictionary<string, Holding> { ["S00"] = new(1_000m / close, close, null, friday.AddDays(-30)) });
|
||
var intent = BacktestEngine.DecideOnce(new EquityMomentum(), data, state, friday).Proposed.Single(i => i.Symbol == "S00");
|
||
Assert.AreEqual(0m, intent.TargetWeight);
|
||
Assert.IsTrue(intent.Reason is EquityMomentum.Reasons.ExitTrend or EquityMomentum.Reasons.ExitRank);
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void EquityMomentumDoesNotLookAhead()
|
||
{
|
||
var data = Stocks(520, 0.001);
|
||
var result = LookAheadCheck.Run(_ => new EquityMomentum(), data);
|
||
Assert.IsTrue(result.Passed, string.Join("\n", result.Mismatches.Take(3)));
|
||
}
|
||
|
||
// ---- equity_meanrev ----
|
||
|
||
/// <summary>
|
||
/// 320 sessions rising by 0,1 a day from 72,3, then three falls of 1: every true range is 2 (high and low one away
|
||
/// from the close), so ATR(14) = 2 and the stop distance 2,5 × 2 = 5. RSI(2) ends near 1, the close (101) is below
|
||
/// its 5-session average and above its 200-session one.
|
||
/// </summary>
|
||
private static List<DailyBar> Dip(double shift = 0)
|
||
{
|
||
var closes = Enumerable.Range(0, 317).Select(i => Math.Round(72.3 + (0.1 * i), 1) + shift).Concat([103 + shift, 102 + shift, 101 + shift]).ToList();
|
||
return StrategyData.OnBusinessDays(StrategyData.FromCloses(closes, range: 1, volume: 100_000), Monday);
|
||
}
|
||
|
||
private static BacktestDataset Shares(params (string Symbol, List<DailyBar> Bars)[] stocks) =>
|
||
new(stocks.Select(s => new BacktestInstrument(StrategyData.Share(s.Symbol), s.Bars)), "USD");
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void MeanrevSizesForARiskOfFourThousandthsCappedAtThirtyPercent()
|
||
{
|
||
var data = Shares(("AAA", Dip()));
|
||
var last = data.Sessions[^1];
|
||
|
||
// Reference equity = the strategy's 10.000 $: risk 40 $ over a 5 $ distance = 8 shares at 101 = 808 $, 8,08%.
|
||
var entry = BacktestEngine.DecideOnce(new EquityMeanrev(), data, PortfolioState.OnlyCash(10_000m), last).Proposed.Single();
|
||
Assert.AreEqual(EquityMeanrev.Reasons.Entry, entry.Reason);
|
||
Assert.AreEqual(0.0808m, entry.TargetWeight);
|
||
Assert.AreEqual(5m, entry.StopOffset);
|
||
|
||
// With the default share (15% of the bot) the reference is 66.666 $: 53,3 shares, more than the 30% cap.
|
||
var capped = BacktestEngine.DecideOnce(new EquityMeanrev(), data, PortfolioState.OnlyCash(10_000m), last, new BacktestOptions { ReferenceShare = 0.15m }).Proposed.Single();
|
||
Assert.AreEqual(0.3m, capped.TargetWeight);
|
||
|
||
// A position bought today holds 9.500 $, 500 $ stay free: not enough for the candidate (808 $), dropped.
|
||
var both = Shares(("AAA", Dip()), ("BBB", Dip()));
|
||
var poor = new PortfolioState(500m, new Dictionary<string, Holding> { ["BBB"] = new(9_500m / 101m, 101m, 96m, last) });
|
||
Assert.IsFalse(BacktestEngine.DecideOnce(new EquityMeanrev(), both, poor, last).Proposed.Any(i => i.Symbol == "AAA"));
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void MeanrevTakesAtMostThreeWithTheLowestRsi()
|
||
{
|
||
// Five dips; a deeper last fall gives a lower RSI. The three deepest are chosen.
|
||
var stocks = Enumerable.Range(0, 5).Select(k =>
|
||
{
|
||
var bars = Dip(k);
|
||
bars[^1] = bars[^1] with { Close = bars[^1].Close - (0.1 * k), Low = bars[^1].Low - (0.1 * k) };
|
||
return ("D" + k.ToString(System.Globalization.CultureInfo.InvariantCulture), bars);
|
||
}).ToArray();
|
||
var data = Shares(stocks);
|
||
var intents = BacktestEngine.DecideOnce(new EquityMeanrev(), data, PortfolioState.OnlyCash(100_000m), data.Sessions[^1]).Proposed;
|
||
CollectionAssert.AreEqual(new[] { "D4", "D3", "D2" }, intents.Select(i => i.Symbol).ToArray());
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void MeanrevExitsAtTheCloseOnTheRules()
|
||
{
|
||
var bars = Dip();
|
||
var data = Shares(("AAA", bars));
|
||
var last = data.Sessions[^1];
|
||
Intent Exit(DateOnly entered, DateOnly day)
|
||
{
|
||
var state = new PortfolioState(9_000m, new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 95m, entered) });
|
||
return BacktestEngine.DecideOnce(new EquityMeanrev(), data, state, day).Proposed.Single(i => i.Symbol == "AAA");
|
||
}
|
||
|
||
// In the rise the close is above its 5-session average: out at the close.
|
||
var rising = Exit(data.Sessions[^10], data.Sessions[^5]);
|
||
Assert.AreEqual(EquityMeanrev.Reasons.ExitAverage, rising.Reason);
|
||
Assert.IsTrue(rising.AtClose);
|
||
|
||
// In the dip none of the price rules says exit; held since the fifth session from the end: time is up.
|
||
var timed = Exit(data.Sessions[^5], last);
|
||
Assert.AreEqual(EquityMeanrev.Reasons.ExitTime, timed.Reason);
|
||
var state = new PortfolioState(9_000m, new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 95m, data.Sessions[^4]) });
|
||
Assert.IsFalse(BacktestEngine.DecideOnce(new EquityMeanrev(), data, state, last).Proposed.Any(i => i.Symbol == "AAA"), "Four sessions: still held.");
|
||
}
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void EquityMeanrevDoesNotLookAhead()
|
||
{
|
||
var instruments = Enumerable.Range(0, 12).Select(k => new BacktestInstrument(StrategyData.Share("M" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)),
|
||
StrategyData.OnBusinessDays([.. BacktestData.Walk(520, 300 + (ulong)k, start: 60 + k, drift: 0.0006, volatility: 0.02).Select(b => b with { Volume = 100_000 })], Monday)));
|
||
var data = new BacktestDataset(instruments, "USD");
|
||
var result = LookAheadCheck.Run(_ => new EquityMeanrev(), data);
|
||
Assert.IsTrue(result.Passed, string.Join("\n", result.Mismatches.Take(3)));
|
||
var run = BacktestEngine.Run(new EquityMeanrev(), data);
|
||
Assert.IsGreaterThan(5, run.Fills.Count, "The check must look at a strategy that trades.");
|
||
}
|
||
|
||
// ---- Engine features the strategies need ----
|
||
|
||
[TestMethod]
|
||
[TestCategory(Category.Unit)]
|
||
public void AnExitAtTheCloseIsFilledAtThatCloseAndAStopOffsetFollowsThePriceObtained()
|
||
{
|
||
var d1 = BacktestData.D1;
|
||
var bars = new List<DailyBar>
|
||
{
|
||
new(d1, 100, 101, 99, 100, 1000),
|
||
new(d1.AddDays(1), 100, 102, 99, 101, 1000),
|
||
new(d1.AddDays(2), 101, 103, 100, 102, 1000),
|
||
new(d1.AddDays(3), 102, 103, 90, 95, 1000),
|
||
};
|
||
var script = new ScriptedStrategy(new Dictionary<DateOnly, IReadOnlyList<Intent>>
|
||
{
|
||
[d1] = [new Intent("BTC-EUR", 0.5m, "enter") { StopOffset = 5m }],
|
||
[d1.AddDays(2)] = [new Intent("BTC-EUR", 0m, "exit") { AtClose = true }],
|
||
});
|
||
var run = BacktestEngine.Run(script, BacktestData.One(BacktestData.Btc(), bars));
|
||
// Bought at the open of day 2 (100 + 5 bp → 100,1); sold at the close of day 3 itself, 102 − 5 bp → 101,9.
|
||
Assert.AreEqual(d1.AddDays(1), run.Fills[0].Day);
|
||
Assert.AreEqual(d1.AddDays(2), run.Fills[1].Day);
|
||
Assert.AreEqual(101.9m, run.Fills[1].Price);
|
||
Assert.AreEqual("exit", run.Fills[1].Reason);
|
||
|
||
// Without the exit, the stop sits 5 below the price obtained (95,1) and the low of day 4 (90) takes it.
|
||
var held = BacktestEngine.Run(new ScriptedStrategy(new Dictionary<DateOnly, IReadOnlyList<Intent>> { [d1] = [new Intent("BTC-EUR", 0.5m, "enter") { StopOffset = 5m }] }),
|
||
BacktestData.One(BacktestData.Btc(), bars));
|
||
var stop = held.Fills.Single(f => f.Side == OrderSide.Sell);
|
||
Assert.AreEqual(BacktestReasons.Stop, stop.Reason);
|
||
Assert.AreEqual(d1.AddDays(3), stop.Day);
|
||
Assert.AreEqual(95.0m, stop.Price);
|
||
}
|
||
|
||
/// <summary>Records the moment each decision is taken.</summary>
|
||
private sealed class Recording(IStrategy inner, List<DateTimeOffset> times) : IStrategy
|
||
{
|
||
public string Id => inner.Id;
|
||
|
||
public string Version => inner.Version;
|
||
|
||
public IReadOnlyList<DecisionTime> Schedule() => inner.Schedule();
|
||
|
||
public IReadOnlyList<string> Universe(UniverseContext context) => inner.Universe(context);
|
||
|
||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||
{
|
||
times.Add(context.Now);
|
||
return inner.Decide(context);
|
||
}
|
||
}
|
||
}
|