Files
Alby96andClaude Opus 5.5 8def84e122 Add the risk engine, correctives and strategy stages (refs #41 #42 #43)
Every intent of a strategy now crosses a risk engine that only refuses or
shrinks: loss limits per world with the 24-hour block, the weekly halving,
the halving and the switch on the fall from the high, the size limits on
invested capital, single position, crypto share and trade risk, the
technical checks, no short sales and no leverage, the day-trade guard
(off by default). The switch, "Ferma tutto", "Ferma e chiudi", the STOP
file and the orders-per-minute anomaly stop the bot until the user
confirms a restart, and a restart after a trip measures the high from
then on.

The correctives of SPEC 8.5 (crypto regime, economic calendar) and the
risk rules also run inside the backtests of the base strategies, so the
reports show what would happen live. Each stage of a decision is written
to a new decisions table with reason codes.

The stage book is the only way to real money: an order on a real account
needs the startup consent, every requirement of SPEC 12.3 met, the typed
phrase and a fresh password and second factor. Order managers on real
accounts fail closed and ask again before each order leaves. A demoted or
revoked strategy keeps its real positions in exit only, with stops, until
they are at zero. The simulated twin stays out of totals and of the
reference equity.

Tests cover each rule of 9.1 and 9.2, with property tests for "never
larger than asked" and "never larger after a loss", and both proofs on a
fake real account: nothing reaches it without the procedure, and a
demoted strategy manages exits and stops down to zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:22:35 +01:00

456 lines
23 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Anubis.Backtest;
using Anubis.Data;
using Anubis.Risk;
using Anubis.Strategies;
namespace Anubis.Tests;
/// <summary>
/// The rules of the risk engine without a database (issues #41, #42; SPEC 8.5, 9.1, 9.2, 9.5): every size rule, the
/// monitor of losses with its blocks, warnings and switch, the scenarios, the correctives.
/// </summary>
[TestClass]
public sealed class RiskTests
{
private static readonly RiskLimits _limits = RiskLimits.Default;
// A Wednesday in November: 11:00 in Rome.
private static readonly DateTimeOffset _now = new(2026, 11, 11, 10, 0, 0, TimeSpan.Zero);
private static PurchaseRequest Request(decimal wanted, decimal price = 100m, decimal held = 0m, decimal? stop = 95m, decimal reference = 10_000m) => new()
{
Price = price,
Held = held,
Wanted = wanted,
Stop = stop,
WorldEquity = reference,
WorldInvested = 0m,
Reference = reference,
};
// ---- 9.2: each limit on the size of a purchase ----
[TestMethod]
[TestCategory(Category.Unit)]
public void TheInvestedCapitalLimitStopsPurchasesAtTheEquity()
{
var size = RiskRules.SizePurchase(Request(10m) with { WorldInvested = 9_700m }, _limits);
Assert.AreEqual(3m, size.Quantity);
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.InvestedLimit);
Assert.AreEqual(0m, RiskRules.SizePurchase(Request(10m) with { WorldInvested = 10_000m }, _limits).Quantity);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OnePositionNeverWeighsMoreThanTwentyPercentOfTheReference()
{
// 20% of 10 000 at 100 is 20 shares: 15 held, 5 more allowed.
var size = RiskRules.SizePurchase(Request(10m, held: 15m, stop: 99.5m), _limits);
Assert.AreEqual(5m, size.Quantity);
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.PositionLimit);
// Heavier than the threshold: the excess goes at the first chance.
Assert.AreEqual(10m, RiskRules.Excess(30m, 100m, 10_000m, _limits));
Assert.AreEqual(0m, RiskRules.Excess(20m, 100m, 10_000m, _limits));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void CryptoNeverGoesBeyondFortyPercentOfTheReference()
{
var size = RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { IsCrypto = true, CryptoValue = 3_900m }, _limits);
Assert.AreEqual(1m, size.Quantity);
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.CryptoLimit);
// The same purchase of a stock is not touched by the crypto share.
Assert.AreEqual(10m, RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { CryptoValue = 3_900m }, _limits).Quantity);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheRiskOfOneTradeIsAtMostOnePercentOnTheWholePosition()
{
// 1% of 10 000 is 100; with the stop 10 below the price that is 10 shares for the whole position.
var size = RiskRules.SizePurchase(Request(15m, stop: 90m), _limits);
Assert.AreEqual(10m, size.Quantity);
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.TradeRiskLimit);
Assert.AreEqual(6m, RiskRules.SizePurchase(Request(15m, held: 4m, stop: 90m), _limits).Quantity);
// Without a stop the whole value is at risk; a stop at or above the price buys nothing.
Assert.AreEqual(1m, RiskRules.SizePurchase(Request(15m, stop: null), _limits).Quantity);
var above = RiskRules.SizePurchase(Request(15m, stop: 100m), _limits);
Assert.AreEqual(0m, above.Quantity);
CollectionAssert.Contains(above.Reasons.ToList(), RiskReasons.StopAbovePrice);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AReductionMultipliesTheTargetAndNeverSellsWhatIsHeld()
{
var halved = RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { Multiplier = 0.5m }, _limits);
Assert.AreEqual(5m, halved.Quantity);
CollectionAssert.Contains(halved.Reasons.ToList(), RiskReasons.Reduction);
// 6 held towards a target of 10, halved to 5: nothing more is bought, nothing is sold.
Assert.AreEqual(0m, RiskRules.SizePurchase(Request(4m, held: 6m, stop: 99.5m) with { Multiplier = 0.5m }, _limits).Quantity);
}
// ---- 9.1 points 5 and 6, as properties ----
private sealed record Case(PurchaseRequest Request, decimal Loss, decimal Cut)
{
public override string ToString() => $"{Request} loss {Loss} cut {Cut}";
}
private static Case Generate(Gen g)
{
var price = (decimal)Math.Round(1 + (g.Double() * 1000), 2);
var reference = (decimal)Math.Round(1_000 + (g.Double() * 100_000), 2);
var request = new PurchaseRequest
{
Price = price,
Held = g.Bool() ? 0m : (decimal)Math.Round(g.Double() * 50, 4),
Wanted = (decimal)Math.Round(g.Double() * 100, 4),
Stop = g.Int(0, 4) switch
{
0 => null,
1 => price * 1.01m,
_ => Math.Round(price * (decimal)(0.5 + (g.Double() * 0.49)), 2),
},
Multiplier = g.Bool() ? 1m : (decimal)Math.Round(g.Double(), 2),
WorldEquity = reference,
WorldInvested = (decimal)Math.Round(g.Double() * (double)reference, 2),
Reference = reference,
IsCrypto = g.Bool(),
CryptoValue = (decimal)Math.Round(g.Double() * 0.5 * (double)reference, 2),
};
return new Case(request, (decimal)Math.Round(g.Double() * 0.5, 4), (decimal)Math.Round(g.Double(), 4));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void NoRuleEverEnlargesWhatTheStrategyAsked() =>
Property.ForAll(Generate, c =>
{
var size = RiskRules.SizePurchase(c.Request, _limits);
Assert.IsTrue(size.Quantity >= 0m && size.Quantity <= c.Request.Wanted, $"{size.Quantity} for {c.Request.Wanted}");
});
[TestMethod]
[TestCategory(Category.Unit)]
public void AfterALossNoPurchaseIsLarger() =>
Property.ForAll(Generate, c =>
{
// The same purchase after a loss: less equity, a lower reference, a multiplier no higher. No doubling, no recovery.
var before = RiskRules.SizePurchase(c.Request, _limits).Quantity;
var factor = 1m - c.Loss;
var after = RiskRules.SizePurchase(c.Request with
{
WorldEquity = c.Request.WorldEquity * factor,
Reference = c.Request.Reference * factor,
Multiplier = c.Request.Multiplier * (1m - (c.Cut / 2m)),
}, _limits).Quantity;
Assert.IsTrue(after <= before, $"{after} after the loss, {before} before");
});
[TestMethod]
[TestCategory(Category.Unit)]
public void NoCorrectiveRaisesAWeight()
{
var holdings = new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 90m, StrategyData.Start) };
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
var context = new StrategyContext(StrategyData.Start.AddDays(2), default, ["AAA", "BBB"], new PortfolioView(9_000m, 10_000m, holdings), _ => bars, _ => null);
Property.ForAll(g => (Symbol: g.Bool() ? "AAA" : "BBB", Target: (decimal)Math.Round(g.Double() * 0.5, 4), Multiplier: (decimal)Math.Round(g.Double() * 1.5, 4)), c =>
{
var intent = new Intent(c.Symbol, c.Target, "test") { Stop = 90m };
var reduced = BookWeights.Reduce(context, intent, c.Multiplier, CorrectiveReasons.CalendarEvent);
Assert.IsTrue(reduced.TargetWeight is null || reduced.TargetWeight <= c.Target, reduced.ToString());
});
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCodeCallsNoWithdrawalOrTransferEndpoint()
{
// SPEC 9.1 point 2: OKX withdrawals and transfers, Alpaca transfers and bank links, in any form.
var endpoint = new System.Text.RegularExpressions.Regex(@"asset/withdrawal|asset/transfer|/transfers\b|ach_relationships|recipient_banks|/withdraw",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var offenders = Repo.Files()
.Where(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal))
.Where(f => endpoint.IsMatch(File.ReadAllText(f.FullName)))
.Select(Repo.Relative)
.ToList();
Assert.IsEmpty(offenders, string.Join(", ", offenders));
Assert.IsTrue(Repo.Files().Count(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal)) > 50, "the scan sees the code");
}
// ---- 9.2: the monitor of losses ----
private static List<IndexPoint> Points(params (double HoursAgo, decimal Index)[] points) =>
[.. points.Select(p => new IndexPoint(_now - TimeSpan.FromHours(p.HoursAgo), p.Index)).OrderBy(p => p.At)];
[TestMethod]
[TestCategory(Category.Unit)]
public void TheDayStartsAtMidnightInItaly()
{
Assert.AreEqual(new DateTimeOffset(2026, 11, 10, 23, 0, 0, TimeSpan.Zero), RiskMonitor.ItalianMidnight(_now));
Assert.AreEqual(new DateTimeOffset(2026, 7, 10, 22, 0, 0, TimeSpan.Zero), RiskMonitor.ItalianMidnight(new DateTimeOffset(2026, 7, 11, 8, 0, 0, TimeSpan.Zero)));
// A fall at 23:30 in Rome of the day before belongs to yesterday.
var m = RiskMeasures.From(Points((24, 1.00m), (11.5, 0.97m), (0, 0.97m)), _now, null);
Assert.AreEqual(0m, m.DayChange);
Assert.AreEqual(-0.03m, m.Drawdown);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ALossOfTwoPercentInADayBlocksEntriesForTwentyFourHours()
{
var m = RiskMeasures.From(Points((12, 1.00m), (0, 0.975m)), _now, null);
var reading = RiskMonitor.Step(RiskMonitorState.Initial, m, _now, _limits);
Assert.AreEqual(_now + TimeSpan.FromHours(24), reading.State.DailyBlockUntil);
Assert.IsTrue(reading.Alerts.Any(a => a.Kind == RiskAlertKinds.DailyLoss));
Assert.IsTrue(RiskMonitor.EntriesBlocked(reading.State, _now + TimeSpan.FromHours(23)), "24 hours, not until midnight");
Assert.IsFalse(RiskMonitor.EntriesBlocked(reading.State, _now + TimeSpan.FromHours(25)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ALossOfFivePercentInAWeekHalvesRiskForSevenDays()
{
var m = RiskMeasures.From(Points((24 * 7.5, 1.00m), (24 * 6, 0.96m), (12, 0.95m), (0, 0.948m)), _now, null);
Assert.IsTrue(m.WeekChange <= -0.05m);
var reading = RiskMonitor.Step(RiskMonitorState.Initial, m, _now, _limits);
Assert.IsNull(reading.State.DailyBlockUntil);
Assert.AreEqual(0.5m, RiskMonitor.Multiplier(reading.State, RiskMeasures.None, _now + TimeSpan.FromDays(6), _limits));
Assert.AreEqual(1m, RiskMonitor.Multiplier(reading.State, RiskMeasures.None, _now + TimeSpan.FromDays(7.1), _limits));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFallFromTheHighHalvesAtTenAndTripsTheSwitchAtFifteen()
{
var half = RiskMonitor.Step(RiskMonitorState.Initial, new RiskMeasures(0m, 0m, -0.11m), _now, _limits);
Assert.AreEqual(0.5m, RiskMonitor.Multiplier(half.State, half.Measures, _now, _limits));
Assert.IsFalse(half.State.Tripped);
Assert.AreEqual(1, half.Alerts.Count(a => a.Kind == RiskAlertKinds.DrawdownHalf));
Assert.AreEqual(0, RiskMonitor.Step(half.State, half.Measures, _now, _limits).Alerts.Count(a => a.Kind == RiskAlertKinds.DrawdownHalf), "said once");
var stop = RiskMonitor.Step(half.State, new RiskMeasures(0m, 0m, -0.16m), _now, _limits);
Assert.IsTrue(stop.State.Tripped);
Assert.IsTrue(RiskMonitor.EntriesBlocked(stop.State, _now + TimeSpan.FromDays(30)), "only the user restarts it");
Assert.AreEqual(RiskSeverities.Critical, stop.Alerts.Single(a => a.Kind == RiskAlertKinds.DrawdownStop).Severity);
// With the week's halving too the purchases are a quarter.
var both = half.State with { WeeklyHalvingUntil = _now + TimeSpan.FromDays(3) };
Assert.AreEqual(0.25m, RiskMonitor.Multiplier(both, half.Measures, _now, _limits));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AtEightyPercentOfAThresholdOneWarningAndNoBlock()
{
var near = new RiskMeasures(-0.017m, 0m, -0.017m);
var first = RiskMonitor.Step(RiskMonitorState.Initial, near, _now, _limits);
Assert.AreEqual(1, first.Alerts.Count(a => a.Kind == RiskAlertKinds.Warning), "the day's loss; the fall is far from 8%");
Assert.IsFalse(RiskMonitor.EntriesBlocked(first.State, _now));
Assert.AreEqual(1m, RiskMonitor.Multiplier(first.State, near, _now, _limits));
Assert.AreEqual(0, RiskMonitor.Step(first.State, near, _now, _limits).Alerts.Count, "one for each crossing");
var back = RiskMonitor.Step(first.State, RiskMeasures.None, _now, _limits);
Assert.AreEqual(1, RiskMonitor.Step(back.State, near, _now, _limits).Alerts.Count, "a new crossing warns again");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ARestartAfterATripMeasuresTheHighFromNow()
{
var series = Points((48, 1.00m), (0, 0.84m));
var tripped = RiskMonitor.Step(RiskMonitorState.Initial, RiskMeasures.From(series, _now, null), _now, _limits).State;
Assert.IsTrue(tripped.Tripped);
Assert.AreEqual(1.00m, tripped.Peak);
var restarted = RiskMonitor.Restart(tripped, _now);
Assert.IsFalse(restarted.Tripped);
Assert.IsNull(restarted.Peak);
var later = _now + TimeSpan.FromHours(1);
var after = RiskMeasures.From([.. series, new IndexPoint(later, 0.84m)], later, restarted.PeakFrom, restarted.Peak);
Assert.AreEqual(0m, after.Drawdown, "otherwise the switch would trip again at once");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheHighIsRememberedBeyondTheSeriesRead() =>
Assert.AreEqual(Math.Round((1.0m / 1.2m) - 1m, 6), Math.Round(RiskMeasures.From(Points((1, 1.0m), (0, 1.0m)), _now, null, knownPeak: 1.2m).Drawdown, 6));
// ---- 9.2: technical checks ----
[TestMethod]
[TestCategory(Category.Unit)]
public void TechnicalChecksStopEntriesOnOldPricesFarLimitsAndAWrongClock()
{
Assert.IsNull(RiskRules.TechnicalRefusal(_now, _now - TimeSpan.FromSeconds(59), 100m, 100.9m, TimeSpan.FromSeconds(1), _limits));
Assert.AreEqual(RiskReasons.StalePrice, RiskRules.TechnicalRefusal(_now, _now - TimeSpan.FromSeconds(61), 100m, null, null, _limits));
Assert.AreEqual(RiskReasons.StalePrice, RiskRules.TechnicalRefusal(_now, null, null, null, null, _limits));
Assert.AreEqual(RiskReasons.PriceGap, RiskRules.TechnicalRefusal(_now, _now, 100m, 101.5m, null, _limits));
Assert.AreEqual(RiskReasons.ClockSkew, RiskRules.TechnicalRefusal(_now, _now, 100m, null, TimeSpan.FromSeconds(-3), _limits));
}
// ---- Settings of the limits ----
[TestMethod]
[TestCategory(Category.Unit)]
public void LimitsComeFromSettingsAndRaisingOneIsRecognised()
{
var values = RiskSettings.Limits.ToDictionary(d => d.Key, d => d.Default);
Assert.AreEqual(RiskLimits.Default, RiskSettings.From(k => values[k]));
values[RiskSettings.DailyLoss.Key] = "3";
var looser = RiskSettings.From(k => values[k]);
Assert.AreEqual(0.03m, looser.DailyLoss);
Assert.IsTrue(RiskLimits.Default.RaisedBy(looser));
Assert.IsFalse(looser.RaisedBy(RiskLimits.Default), "lowering a limit needs no confirmation");
Assert.IsNotNull(RiskSettings.DailyLoss.Check!("50"));
Assert.AreEqual("off", RiskSettings.PdtGuard.Default, "the day-trade guard is off by default");
}
// ---- 9.5: scenarios ----
[TestMethod]
[TestCategory(Category.Unit)]
public void ScenariosWithAndWithoutStops()
{
var positions = new[]
{
new ScenarioPosition(true, 2_000m, 1_800m),
new ScenarioPosition(false, 3_000m, 2_700m),
new ScenarioPosition(false, 1_000m, null),
};
var result = Scenarios.Compute(Scenarios.Default, positions, dollarAccountEur: 4_000m, equityEur: 10_000m);
Assert.AreEqual(-400m, result[0].WithoutStops);
Assert.AreEqual(-0.04m, result[0].WithoutStopsShare);
Assert.AreEqual(-200m, result[0].WithStops, "the stop limits the loss");
Assert.AreEqual(-280m, result[1].WithoutStops);
Assert.AreEqual(-280m, result[1].WithStops, "a 7% fall stays above the stop; without a stop the whole loss");
Assert.AreEqual(-680m, result[2].WithoutStops);
Assert.AreEqual(-200m, result[3].WithoutStops);
Assert.IsTrue(result[3].SameWithStops);
Assert.IsNull(result[3].WithStops, "stops do not reduce the dollar");
// Rounded to 5 euro.
Assert.AreEqual(-25m, Scenarios.Compute([new("x", -0.2m, 0m, 0m)], [new ScenarioPosition(true, 113m, null)], 0m, 1_000m)[0].WithStops);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ScenariosAreASettingTheUserCanWrite()
{
CollectionAssert.AreEqual(Scenarios.Default.ToList(), Scenarios.Parse(Scenarios.Setting.Default).ToList(), "round trip");
Assert.AreEqual(Scenarios.Default.Count, Scenarios.Parse(Scenarios.Setting.Default).Count);
var custom = Scenarios.Parse("Crollo; −30; −10,5; 0");
Assert.AreEqual(-0.105m, custom[0].Stocks);
Assert.IsNotNull(Scenarios.Setting.Check!("solo testo"));
Assert.IsNotNull(Scenarios.Setting.Check!("x; -200; 0; 0"));
Assert.IsNull(Scenarios.Setting.Check!(Scenarios.Setting.Default));
}
// ---- 8.5: correctives ----
private static CalendarEvent Event(string kind, DateTimeOffset at, string impact = "High", string currency = "USD") =>
new(kind, "evento", at, true, "test", kind + at.ToString("O", System.Globalization.CultureInfo.InvariantCulture)) { Currency = currency, Impact = impact };
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCalendarBlocksAroundImportantEvents()
{
var cpi = Event(CalendarEventKinds.Economic, _now);
Assert.AreEqual((_now - TimeSpan.FromMinutes(30), _now + TimeSpan.FromMinutes(30)), CalendarBlocks.Window(cpi));
Assert.IsNull(CalendarBlocks.Window(Event(CalendarEventKinds.Economic, _now, impact: "Medium")));
Assert.IsNull(CalendarBlocks.Window(Event(CalendarEventKinds.Economic, _now, currency: "EUR")));
Assert.AreEqual(_now + TimeSpan.FromMinutes(60), CalendarBlocks.Window(Event(CalendarEventKinds.CentralBank, _now, currency: "EUR"))!.Value.To);
// Two windows that overlap make one block; outside it the entry goes now.
var fed = Event(CalendarEventKinds.CentralBank, _now + TimeSpan.FromMinutes(45));
Assert.AreEqual(_now + TimeSpan.FromMinutes(105), CalendarBlocks.BlockedUntil(_now - TimeSpan.FromMinutes(10), [cpi, fed]));
Assert.IsNull(CalendarBlocks.BlockedUntil(_now - TimeSpan.FromHours(2), [cpi, fed]));
// Tried again at the end of the window, or dropped when the deadline comes first.
Assert.AreEqual(_now + TimeSpan.FromMinutes(30), CalendarBlocks.RetryAt(_now, [cpi], _now + TimeSpan.FromHours(1)));
Assert.IsNull(CalendarBlocks.RetryAt(_now, [cpi], _now + TimeSpan.FromMinutes(10)));
Assert.AreEqual(new DateTimeOffset(2026, 11, 11, 12, 0, 0, TimeSpan.Zero), CalendarBlocks.CryptoDeadline(_now));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCalendarStageTurnsEntriesIntoNothingButKeepsStops()
{
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
var holdings = new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 90m, StrategyData.Start) };
var context = new StrategyContext(StrategyData.Start.AddDays(2), _now, ["AAA", "BBB"], new PortfolioView(9_000m, 10_000m, holdings), _ => bars, _ => null);
var stage = new CalendarStage(_ => [Event(CalendarEventKinds.Economic, _now)]);
var result = stage.Apply(context, [new Intent("AAA", 0.3m, "more") { Stop = 92m }, new Intent("BBB", 0.1m, "new") { Stop = 90m }, new Intent("CCC", 0m, "exit")]);
Assert.IsNull(result[0].TargetWeight);
Assert.AreEqual(92m, result[0].Stop, "the stop of a held position still follows the strategy");
Assert.IsNull(result[1].TargetWeight);
Assert.IsNull(result[1].Stop);
CollectionAssert.Contains(result[1].Adjustments.ToList(), CorrectiveReasons.CalendarEvent);
Assert.AreEqual(0m, result[2].TargetWeight, "exits pass");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCryptoRegimeIsRiskyBelowTheAverageOrWithHighVolatility()
{
var settings = new CryptoRegimeSettings();
Assert.IsNull(CryptoRegime.Risky(StrategyData.Series(StrategyData.SteadyRise(400)), settings));
var falling = StrategyData.FromCloses([.. Enumerable.Range(0, 260).Select(i => i < 230 ? 100.0 + i : 330.0 - (5 * (i - 229)))]);
Assert.AreEqual(CorrectiveReasons.CryptoRegimeAverage, CryptoRegime.Risky(StrategyData.Series(falling), settings));
// Calm for two years, then a week of large swings while the price stays above its average.
var closes = Enumerable.Range(0, 800).Select(i => 100.0 * Math.Pow(1.002, i) * (1 + (0.002 * (i % 2)))).ToList();
for (var i = 790; i < 800; i++)
{
closes[i] = closes[789] * (i % 2 == 0 ? 1.08 : 1.0);
}
Assert.AreEqual(CorrectiveReasons.CryptoRegimeVolatility, CryptoRegime.Risky(StrategyData.Series(StrategyData.FromCloses(closes)), settings));
}
// ---- The risk engine inside the backtest ----
[TestMethod]
[TestCategory(Category.Unit)]
public void InTheBacktestAPositionTooHeavyComesBackToTheThreshold()
{
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
var holdings = new Dictionary<string, Holding> { ["AAA"] = new(30m, 100m, 90m, StrategyData.Start) };
var day = StrategyData.Start.AddDays(2);
var context = new StrategyContext(day, BacktestRisk.At(day), ["AAA"], new PortfolioView(7_000m, 10_000m, holdings), _ => bars, _ => StrategyData.Share("AAA"))
{
History = [new EquityMark(day, 10_000m, 3_000m)],
};
var result = new BacktestRisk().Apply(context, []);
var cut = result.Single();
Assert.AreEqual("AAA", cut.Symbol);
Assert.AreEqual(0.2m, cut.TargetWeight);
CollectionAssert.Contains(cut.Adjustments.ToList(), RiskReasons.PositionLimit);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void InTheBacktestNewEntriesStopAfterADayOfLosses()
{
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
var day = StrategyData.Start.AddDays(2);
var context = new StrategyContext(day, BacktestRisk.At(day), ["AAA"], new PortfolioView(9_700m, 9_700m, new Dictionary<string, Holding>()), _ => bars,
_ => StrategyData.Share("AAA"))
{
History = [new EquityMark(day.AddDays(-1), 10_000m, 0m), new EquityMark(day, 9_700m, 0m)],
};
var risk = new BacktestRisk();
var result = risk.Apply(context, [new Intent("AAA", 0.1m, "entry") { Stop = 95m }]);
Assert.IsNull(result[0].TargetWeight);
CollectionAssert.Contains(result[0].Adjustments.ToList(), RiskReasons.DailyLossBlock);
}
}