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>
This commit is contained in:
1 parent
a6227793c3
commit
2409e74b26
10 files changed
+2051
-19
No files matched your search
@@ -102,14 +102,20 @@ public sealed class BacktestDataset
|
||||
{
|
||||
private readonly Dictionary<string, BacktestInstrument> _bySymbol;
|
||||
|
||||
public BacktestDataset(IEnumerable<BacktestInstrument> instruments, string currency)
|
||||
/// <param name="instruments">Every instrument, the tradable ones and those used only as data.</param>
|
||||
/// <param name="currency">The one currency of the backtest.</param>
|
||||
/// <param name="calendar">The market's sessions, which may go beyond the bars; null means the days with bars.</param>
|
||||
/// <param name="dataOnly">Instruments the strategy reads but never trades, such as SPY for the market filter.</param>
|
||||
public BacktestDataset(IEnumerable<BacktestInstrument> instruments, string currency, IEnumerable<DateOnly>? calendar = null, IEnumerable<string>? dataOnly = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instruments);
|
||||
Instruments = [.. instruments.OrderBy(i => i.Symbol, StringComparer.Ordinal)];
|
||||
Currency = currency;
|
||||
_bySymbol = Instruments.ToDictionary(i => i.Symbol, StringComparer.Ordinal);
|
||||
Sessions = [.. Instruments.SelectMany(i => i.Bars.Select(b => b.Day)).Distinct().Order()];
|
||||
var wrong = Instruments.FirstOrDefault(i => i.Spec.QuoteCurrency != currency);
|
||||
Calendar = [.. (calendar ?? []).Concat(Sessions).Distinct().Order()];
|
||||
DataOnly = new SortedSet<string>(dataOnly ?? [], StringComparer.Ordinal);
|
||||
var wrong = Instruments.FirstOrDefault(i => i.Spec.QuoteCurrency != currency && !DataOnly.Contains(i.Symbol));
|
||||
if (wrong is not null)
|
||||
{
|
||||
throw new ArgumentException($"{wrong.Symbol} is in {wrong.Spec.QuoteCurrency}, the backtest is in {currency}", nameof(instruments));
|
||||
@@ -118,11 +124,47 @@ public sealed class BacktestDataset
|
||||
|
||||
public IReadOnlyList<BacktestInstrument> Instruments { get; }
|
||||
|
||||
/// <summary>The instruments the strategy may trade: every one but those used only as data.</summary>
|
||||
public IEnumerable<BacktestInstrument> Tradable => Instruments.Where(i => !DataOnly.Contains(i.Symbol));
|
||||
|
||||
public IReadOnlySet<string> DataOnly { get; }
|
||||
|
||||
public string Currency { get; }
|
||||
|
||||
public IReadOnlyList<DateOnly> Sessions { get; }
|
||||
|
||||
public bool IsCrypto => Instruments.Count > 0 && Instruments.All(i => i.Spec.AssetClass == AssetClasses.Crypto);
|
||||
/// <summary>
|
||||
/// The market calendar: the sessions with bars and, when given, the later ones. Cutting the data keeps it whole,
|
||||
/// because a calendar is known in advance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<DateOnly> Calendar { get; }
|
||||
|
||||
/// <summary>The next session after <paramref name="day"/>: every day for crypto, the calendar for stocks.</summary>
|
||||
public DateOnly? NextSession(DateOnly day)
|
||||
{
|
||||
if (IsCrypto)
|
||||
{
|
||||
return day.AddDays(1);
|
||||
}
|
||||
|
||||
int lo = 0, hi = Calendar.Count;
|
||||
while (lo < hi)
|
||||
{
|
||||
var mid = (lo + hi) / 2;
|
||||
if (Calendar[mid] <= day)
|
||||
{
|
||||
lo = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
|
||||
return lo < Calendar.Count ? Calendar[lo] : null;
|
||||
}
|
||||
|
||||
public bool IsCrypto => Instruments.Count > 0 && Tradable.All(i => i.Spec.AssetClass == AssetClasses.Crypto);
|
||||
|
||||
/// <summary>Sessions in a year, to annualise: crypto trades every day, stocks about 252 days.</summary>
|
||||
public int PeriodsPerYear => IsCrypto ? 365 : 252;
|
||||
@@ -130,13 +172,15 @@ public sealed class BacktestDataset
|
||||
public BacktestInstrument? this[string symbol] => _bySymbol.GetValueOrDefault(symbol);
|
||||
|
||||
/// <summary>The same data cut after <paramref name="day"/>: what was known on that day (SPEC 12.2, step 2).</summary>
|
||||
public BacktestDataset Through(DateOnly day) => new(Instruments.Select(i => i.Through(day)), Currency);
|
||||
public BacktestDataset Through(DateOnly day) => new(Instruments.Select(i => i.Through(day)), Currency, Calendar, DataOnly);
|
||||
|
||||
/// <summary>The same data between two days, both included.</summary>
|
||||
public BacktestDataset Between(DateOnly from, DateOnly to) => new(
|
||||
Instruments.Select(i => new BacktestInstrument(i.Spec, [.. i.Bars.Where(b => b.Day >= from && b.Day <= to)], [.. i.Actions.Where(a => a.ExDate > from && a.ExDate <= to)], i.Source))
|
||||
.Where(i => i.Bars.Count > 0),
|
||||
Currency);
|
||||
Currency,
|
||||
Calendar.Where(d => d >= from),
|
||||
DataOnly);
|
||||
|
||||
/// <summary>
|
||||
/// A SHA-256 of every bar, action and rule used: two reports with the same fingerprint and the same plan were
|
||||
@@ -146,10 +190,16 @@ public sealed class BacktestDataset
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
text.Append(Currency).Append('\n');
|
||||
if (Calendar.Count > Sessions.Count)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $"calendar {Calendar.Count} {Calendar[^1]:yyyy-MM-dd}\n");
|
||||
}
|
||||
|
||||
foreach (var i in Instruments)
|
||||
{
|
||||
var s = i.Spec;
|
||||
text.Append(CultureInfo.InvariantCulture, $"{s.Venue}|{s.Symbol}|{s.AssetClass}|{s.QuoteCurrency}|{s.TickSize}|{s.LotSize}|{s.MinSize}|{s.MinNotional}|{s.Fractionable}\n");
|
||||
text.Append(CultureInfo.InvariantCulture, $"{s.Venue}|{s.Symbol}|{s.AssetClass}|{s.QuoteCurrency}|{s.TickSize}|{s.LotSize}|{s.MinSize}|{s.MinNotional}|{s.Fractionable}");
|
||||
text.Append(DataOnly.Contains(i.Symbol) ? "|data\n" : "\n");
|
||||
foreach (var b in i.Bars)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $"{b.Day:yyyy-MM-dd},{b.Open:R},{b.High:R},{b.Low:R},{b.Close:R},{b.Volume:R}\n");
|
||||
|
||||
@@ -22,6 +22,12 @@ public sealed record BacktestOptions
|
||||
|
||||
/// <summary>The risk engine of SPEC 9. Until Phase 5 it lets everything through.</summary>
|
||||
public IIntentStage Risk { get; init; } = PassThroughStage.Risk;
|
||||
|
||||
/// <summary>
|
||||
/// The strategy's share of the bot's total capital (SPEC 8.6, 9.2): the reference equity is the strategy's equity
|
||||
/// divided by it. Null means the strategy is the whole bot.
|
||||
/// </summary>
|
||||
public decimal? ReferenceShare { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>A book to start from: a state recorded live, for the one-step comparison of SPEC 12.3.</summary>
|
||||
@@ -203,7 +209,10 @@ public static class BacktestEngine
|
||||
public decimal Fees { get; set; }
|
||||
}
|
||||
|
||||
private sealed record Pending(string Symbol, OrderSide Side, decimal Quantity, bool Exit, decimal? Stop, string Reason);
|
||||
private sealed record Pending(string Symbol, OrderSide Side, decimal Quantity, bool Exit, decimal? Stop, string Reason)
|
||||
{
|
||||
public decimal? StopOffset { get; init; }
|
||||
}
|
||||
|
||||
private sealed class Simulation
|
||||
{
|
||||
@@ -216,6 +225,7 @@ public static class BacktestEngine
|
||||
private readonly Dictionary<string, decimal> _lastClose = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, DateOnly> _actionsDoneThrough = new(StringComparer.Ordinal);
|
||||
private readonly List<EquityPoint> _equity = [];
|
||||
private readonly List<EquityMark> _history = [];
|
||||
private readonly List<BacktestFill> _fills = [];
|
||||
private readonly List<BacktestTrade> _trades = [];
|
||||
private readonly List<DecisionRecord> _decisions = [];
|
||||
@@ -358,19 +368,36 @@ public static class BacktestEngine
|
||||
MarkOn(day);
|
||||
var invested = Invested();
|
||||
_equity.Add(new EquityPoint(day, _cash + invested, _cash, invested));
|
||||
_history.Add(new EquityMark(day, _cash + invested, invested));
|
||||
var record = Decide(day, at);
|
||||
_decisions.Add(record);
|
||||
Plan(day, record.Final);
|
||||
// Exits asked for at this close go now (equity_meanrev's 15:55); the rest waits for the next open.
|
||||
foreach (var exit in record.Final.Where(i => i.AtClose && i.TargetWeight == 0m))
|
||||
{
|
||||
if (_positions.TryGetValue(exit.Symbol, out var p) && _lastClose.TryGetValue(exit.Symbol, out var close))
|
||||
{
|
||||
Sell(day, exit.Symbol, p.Quantity, close, exit.Reason, exit: true);
|
||||
_pending.Remove(exit.Symbol);
|
||||
}
|
||||
}
|
||||
|
||||
Plan(day, [.. record.Final.Where(i => !(i.AtClose && i.TargetWeight == 0m))]);
|
||||
}
|
||||
|
||||
public DecisionRecord Decide(DateOnly day, DateTimeOffset at)
|
||||
{
|
||||
var available = _data.Instruments.Where(i => i.CountThrough(day) > 0).Select(i => i.Symbol).ToList();
|
||||
var universe = _strategy.Universe(new UniverseContext(day, available));
|
||||
var available = _data.Tradable.Where(i => i.CountThrough(day) > 0).Select(i => i.Symbol).ToList();
|
||||
BarSeries Bars(string s) => _data[s]?.SeriesThrough(day) ?? BarSeries.Empty;
|
||||
var universe = _strategy.Universe(new UniverseContext(day, available) { Bars = Bars, Spec = s => _data[s]?.Spec });
|
||||
var equity = _cash + Invested();
|
||||
var holdings = _positions.ToDictionary(p => p.Key, p => new Holding(p.Value.Quantity, p.Value.AveragePrice, p.Value.Stop, p.Value.EnteredOn), StringComparer.Ordinal);
|
||||
var context = new StrategyContext(day, at, universe, new PortfolioView(_cash, equity, holdings),
|
||||
s => _data[s]?.SeriesThrough(day) ?? BarSeries.Empty, s => _data[s]?.Spec);
|
||||
var context = new StrategyContext(day, at, universe, new PortfolioView(_cash, equity, holdings), Bars, s => _data[s]?.Spec)
|
||||
{
|
||||
NextSession = _data.NextSession(day),
|
||||
ReferenceEquity = _options.ReferenceShare is > 0m and var share ? equity / share : equity,
|
||||
PeriodsPerYear = _data.PeriodsPerYear,
|
||||
History = _history,
|
||||
};
|
||||
var proposed = _strategy.Decide(context);
|
||||
var final = proposed;
|
||||
foreach (var stage in _options.Correctives)
|
||||
@@ -438,7 +465,7 @@ public static class BacktestEngine
|
||||
var difference = target - current;
|
||||
if (difference > 0m)
|
||||
{
|
||||
_pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Buy, difference, Exit: false, stop, intent.Reason);
|
||||
_pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Buy, difference, Exit: false, stop, intent.Reason) { StopOffset = intent.StopOffset };
|
||||
}
|
||||
else if (difference < 0m)
|
||||
{
|
||||
@@ -480,6 +507,11 @@ public static class BacktestEngine
|
||||
p.AveragePrice = DbValues.Money(((p.Quantity * p.AveragePrice) + fill.Gross) / (p.Quantity + fill.Quantity));
|
||||
p.Quantity += fill.Quantity;
|
||||
p.Stop = order.Stop ?? p.Stop;
|
||||
if (p.Stop is null && order.StopOffset is > 0m and var offset && price - offset > 0m)
|
||||
{
|
||||
// A distance from the price obtained: the stop of a new position (SPEC 8.2, 8.3).
|
||||
p.Stop = OrderRules.StopPrice(price - offset, OrderRules.TickOf(spec, price - offset));
|
||||
}
|
||||
p.Trade.Bought += fill.Gross;
|
||||
p.Trade.CashFlow += fill.CashDelta;
|
||||
p.Trade.Fees += fill.FeeValue;
|
||||
|
||||
@@ -62,7 +62,7 @@ public static class LookAheadCheck
|
||||
/// <summary>Intents as text, with stops to nine significant digits: adjusted prices may differ in the last bit.</summary>
|
||||
private static string Describe(IReadOnlyList<Intent> intents) => string.Join(" | ", intents.Select(i => string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"{i.Symbol} {i.TargetWeight?.ToString(CultureInfo.InvariantCulture) ?? "keep"} {(i.Stop is { } s ? ((double)s).ToString("G9", CultureInfo.InvariantCulture) : "-")} {i.Reason}")));
|
||||
$"{i.Symbol} {(i.TargetWeight is { } w ? ((double)w).ToString("G9", CultureInfo.InvariantCulture) : "keep")} {(i.Stop is { } s ? ((double)s).ToString("G9", CultureInfo.InvariantCulture) : "-")} {(i.StopOffset is { } o ? ((double)o).ToString("G9", CultureInfo.InvariantCulture) : "-")}{(i.AtClose ? " close" : "")} {i.Reason}")));
|
||||
}
|
||||
|
||||
/// <summary>How the live intent and the backtest intent for one instrument compare (SPEC 12.3).</summary>
|
||||
|
||||
@@ -142,7 +142,7 @@ public static class TrialRunner
|
||||
costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees));
|
||||
}
|
||||
|
||||
var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Instruments.Count), data, options);
|
||||
var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Tradable.Count()), data, options);
|
||||
var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear);
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.Strategies;
|
||||
|
||||
/// <summary>The fixed rules of <c>crypto_trend</c> (SPEC 8.1). Only the two family parameters move in a test.</summary>
|
||||
public sealed record CryptoTrendSettings
|
||||
{
|
||||
public IReadOnlyList<int> Periods { get; init; } = [5, 10, 20, 30, 60, 90, 150, 250, 360];
|
||||
|
||||
/// <summary>Volatility each coin is sized to: raw weight = e × this / its volatility.</summary>
|
||||
public double CoinVolatility { get; init; } = 0.15;
|
||||
|
||||
/// <summary>Above this estimated volatility of the whole strategy, every weight shrinks by one factor.</summary>
|
||||
public double StrategyVolatility { get; init; } = 0.20;
|
||||
|
||||
/// <summary>The server stop is never further than this below the last close.</summary>
|
||||
public double MaxStop { get; init; } = 0.15;
|
||||
|
||||
public decimal MajorCap { get; init; } = 0.35m;
|
||||
|
||||
public decimal OtherCap { get; init; } = 0.20m;
|
||||
|
||||
public IReadOnlySet<string> Majors { get; init; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "BTC", "ETH" };
|
||||
|
||||
public int VolatilityWindow { get; init; } = 90;
|
||||
|
||||
/// <summary>A position is resized only when it is this far from its target, relative to the target…</summary>
|
||||
public decimal RebalanceRelative { get; init; } = 0.20m;
|
||||
|
||||
/// <summary>…and this far in share of the strategy's capital.</summary>
|
||||
public decimal RebalanceMinimum { get; init; } = 0.005m;
|
||||
|
||||
public int UniverseSize { get; init; } = CryptoUniverse.Size;
|
||||
|
||||
public int MinAgeDays { get; init; } = CryptoUniverse.MinAgeDays;
|
||||
|
||||
public double MinValue { get; init; } = CryptoUniverse.MinValueEur;
|
||||
|
||||
public double MaxSpreadBp { get; init; } = CryptoUniverse.MaxSpreadBp;
|
||||
|
||||
public int ValueWindow { get; init; } = CryptoUniverse.Window;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>crypto_trend</c> (SPEC 8.1): Donchian channels on nine periods. A period turns on when a close beats the highest
|
||||
/// of its previous N closes, with a trailing stop at the middle of the last N closes that can only rise, and turns off
|
||||
/// when a close ends below yesterday's stop. The average of the nine states, <c>e</c>, sizes each coin against its
|
||||
/// volatility. The state depends on the whole history: it is rebuilt by walking the daily bars with the backtest's
|
||||
/// rules, and kept between decisions so each bar is walked once.
|
||||
/// </summary>
|
||||
public sealed class CryptoTrend(CryptoTrendSettings? settings = null) : IStrategy
|
||||
{
|
||||
private readonly CryptoTrendSettings _settings = settings ?? new CryptoTrendSettings();
|
||||
private readonly Dictionary<string, TrendTracker> _trackers = new(StringComparer.Ordinal);
|
||||
private (string Key, IReadOnlyList<string> Members)? _universe;
|
||||
|
||||
public string Id => CryptoTrendFamily.FamilyId;
|
||||
|
||||
public string Version => CryptoTrendFamily.FamilyVersion;
|
||||
|
||||
public CryptoTrendSettings Settings => _settings;
|
||||
|
||||
/// <summary>Once a day on the 00:00 UTC close (SPEC 8.1); orders go right after.</summary>
|
||||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||
|
||||
/// <summary>
|
||||
/// The 10 coins with the highest median traded value over 30 days on the first day of the month, among those
|
||||
/// listed for 400 days, above the minimum value and, live, below the maximum spread; no stablecoins, wrapped or
|
||||
/// leveraged tokens. The same for the whole month.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Universe(UniverseContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var month = new DateOnly(context.Day.Year, context.Day.Month, 1);
|
||||
if (context.Members?.Invoke(Id, month) is { } saved)
|
||||
{
|
||||
return saved;
|
||||
}
|
||||
|
||||
var key = month.ToString("yyyy-MM", CultureInfo.InvariantCulture) + "|" + string.Join(',', context.Available);
|
||||
if (_universe is { } cached && cached.Key == key)
|
||||
{
|
||||
return cached.Members;
|
||||
}
|
||||
|
||||
var ranked = new List<(string Symbol, double Value)>();
|
||||
foreach (var symbol in context.Available)
|
||||
{
|
||||
if (context.Spec(symbol) is not { } spec || spec.AssetClass != AssetClasses.Crypto || CryptoUniverse.Excluded(Symbols.BaseOf(spec)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var bars = context.Bars(symbol);
|
||||
var index = bars.IndexThrough(month);
|
||||
if (index < _settings.ValueWindow - 1 || bars.Day(index) < month.AddDays(-3))
|
||||
{
|
||||
continue; // Too little history, or not trading any more on that day.
|
||||
}
|
||||
|
||||
var listed = spec.ListedAt is { } at ? DateOnly.FromDateTime(at.UtcDateTime) : bars.FirstDay!.Value;
|
||||
if (listed > month.AddDays(-_settings.MinAgeDays))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var value = Indicators.MedianValue(bars, _settings.ValueWindow, index) ?? 0;
|
||||
if (value <= _settings.MinValue)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (context.SpreadBp is { } spread && (spread(symbol) is not { } bp || bp >= _settings.MaxSpreadBp))
|
||||
{
|
||||
continue; // Live only: an unknown spread counts as too wide.
|
||||
}
|
||||
|
||||
ranked.Add((symbol, value));
|
||||
}
|
||||
|
||||
var members = ranked.OrderByDescending(r => r.Value).ThenBy(r => r.Symbol, StringComparer.Ordinal)
|
||||
.Take(_settings.UniverseSize).Select(r => r.Symbol).ToList();
|
||||
_universe = (key, members);
|
||||
return members;
|
||||
}
|
||||
|
||||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var equity = context.Portfolio.Equity;
|
||||
if (equity <= 0m)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
// Coins of the universe, and coins held that left it: those stay managed until their signal exits.
|
||||
var inUniverse = new HashSet<string>(context.Universe, StringComparer.Ordinal);
|
||||
var symbols = context.Universe.Concat(context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).Select(h => h.Key))
|
||||
.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList();
|
||||
|
||||
var rows = new List<Row>();
|
||||
foreach (var symbol in symbols)
|
||||
{
|
||||
var bars = context.Bars(symbol);
|
||||
if (bars.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var tracker = Tracker(symbol).Advance(bars, _settings);
|
||||
var close = bars.Close(bars.Count - 1);
|
||||
var holding = context.Portfolio.Of(symbol);
|
||||
var current = holding is { Quantity: > 0m } h && close > 0 ? h.Quantity * (decimal)close / equity : 0m;
|
||||
var weight = 0d;
|
||||
var volatility = Indicators.Volatility(bars, _settings.VolatilityWindow, 365);
|
||||
if (tracker.Ensemble > 0 && volatility is > 0)
|
||||
{
|
||||
var cap = _settings.Majors.Contains(Symbols.BaseOf(context.Spec(symbol), symbol)) ? _settings.MajorCap : _settings.OtherCap;
|
||||
weight = Math.Min(tracker.Ensemble * _settings.CoinVolatility / volatility.Value, (double)cap);
|
||||
}
|
||||
|
||||
rows.Add(new Row(symbol, bars, tracker, holding, current, weight, inUniverse.Contains(symbol)));
|
||||
}
|
||||
|
||||
// Caps first; then, if the weights add up to more than everything, all shrink in proportion; then one factor
|
||||
// for the volatility of the whole strategy. What is cut stays cash.
|
||||
var total = rows.Sum(r => r.Weight);
|
||||
if (total > 1)
|
||||
{
|
||||
foreach (var r in rows)
|
||||
{
|
||||
r.Weight /= total;
|
||||
}
|
||||
}
|
||||
|
||||
var portfolio = Indicators.PortfolioVolatility([.. rows.Where(r => r.Weight > 0).Select(r => (r.Bars, r.Weight))], _settings.VolatilityWindow, 365);
|
||||
if (portfolio is > 0 && portfolio.Value > _settings.StrategyVolatility)
|
||||
{
|
||||
var factor = _settings.StrategyVolatility / portfolio.Value;
|
||||
foreach (var r in rows)
|
||||
{
|
||||
r.Weight *= factor;
|
||||
}
|
||||
}
|
||||
|
||||
var intents = new List<Intent>();
|
||||
foreach (var r in rows)
|
||||
{
|
||||
var target = Math.Round((decimal)r.Weight, 6, MidpointRounding.ToZero);
|
||||
if (!r.InUniverse)
|
||||
{
|
||||
target = Math.Min(target, r.Current); // Out of the universe: managed, never bought.
|
||||
}
|
||||
|
||||
var stop = r.Tracker.ServerStop is { } s ? (decimal?)Math.Round((decimal)s, 8) : null;
|
||||
var held = r.Holding is { Quantity: > 0m };
|
||||
if (held && target <= 0m)
|
||||
{
|
||||
intents.Add(new Intent(r.Symbol, 0m, Reasons.Exit));
|
||||
}
|
||||
else if (!held && target > 0m)
|
||||
{
|
||||
if (target > _settings.RebalanceMinimum)
|
||||
{
|
||||
intents.Add(new Intent(r.Symbol, target, Reasons.Entry) { Stop = stop });
|
||||
}
|
||||
}
|
||||
else if (held)
|
||||
{
|
||||
var gap = Math.Abs(target - r.Current);
|
||||
if (gap > _settings.RebalanceRelative * target && gap > _settings.RebalanceMinimum)
|
||||
{
|
||||
intents.Add(new Intent(r.Symbol, target, target > r.Current ? Reasons.Increase : Reasons.Reduce) { Stop = stop });
|
||||
}
|
||||
else if (stop is not null && stop != r.Holding!.Stop)
|
||||
{
|
||||
intents.Add(new Intent(r.Symbol, null, Reasons.StopMoved) { Stop = stop });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return intents;
|
||||
}
|
||||
|
||||
/// <summary>The state of a coin as of its last bar walked: the nine periods, <c>e</c>, the server stop.</summary>
|
||||
public TrendTracker Tracker(string symbol)
|
||||
{
|
||||
if (!_trackers.TryGetValue(symbol, out var tracker))
|
||||
{
|
||||
tracker = new TrendTracker();
|
||||
_trackers[symbol] = tracker;
|
||||
}
|
||||
|
||||
return tracker;
|
||||
}
|
||||
|
||||
public static class Reasons
|
||||
{
|
||||
public const string Entry = "trend_entry";
|
||||
public const string Increase = "trend_increase";
|
||||
public const string Reduce = "trend_reduce";
|
||||
public const string Exit = "trend_exit";
|
||||
public const string StopMoved = "trend_stop";
|
||||
}
|
||||
|
||||
private sealed class Row(string symbol, BarSeries bars, TrendTracker tracker, Holding? holding, decimal current, double weight, bool inUniverse)
|
||||
{
|
||||
public string Symbol { get; } = symbol;
|
||||
|
||||
public BarSeries Bars { get; } = bars;
|
||||
|
||||
public TrendTracker Tracker { get; } = tracker;
|
||||
|
||||
public Holding? Holding { get; } = holding;
|
||||
|
||||
public decimal Current { get; } = current;
|
||||
|
||||
public double Weight { get; set; } = weight;
|
||||
|
||||
public bool InUniverse { get; } = inUniverse;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Donchian states of one coin (SPEC 8.1), walked one daily bar at a time. Walking the same bars always gives the
|
||||
/// same state: from scratch on the first start, or from the saved state and the bars missing since.
|
||||
/// </summary>
|
||||
public sealed class TrendTracker
|
||||
{
|
||||
private bool[] _active = [];
|
||||
private double[] _stops = [];
|
||||
private int _walked;
|
||||
private DateOnly? _first;
|
||||
private DateOnly? _last;
|
||||
|
||||
/// <summary>The average of the period states, between 0 and 1.</summary>
|
||||
public double Ensemble { get; private set; }
|
||||
|
||||
/// <summary>The level of the stop on the broker; null when no period is on.</summary>
|
||||
public double? ServerStop { get; private set; }
|
||||
|
||||
/// <summary>The day of the last bar walked.</summary>
|
||||
public DateOnly? LastDay => _last;
|
||||
|
||||
public IReadOnlyList<bool> Active => _active;
|
||||
|
||||
/// <summary>Walks the bars not walked yet. A history that does not continue the one walked starts again.</summary>
|
||||
public TrendTracker Advance(BarSeries bars, CryptoTrendSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
if (_active.Length != settings.Periods.Count || bars.Count < _walked || (_walked > 0 && (bars.FirstDay != _first || bars.Day(_walked - 1) != _last)))
|
||||
{
|
||||
Reset(settings);
|
||||
}
|
||||
|
||||
for (var i = _walked; i < bars.Count; i++)
|
||||
{
|
||||
Step(bars, i, settings);
|
||||
}
|
||||
|
||||
_walked = bars.Count;
|
||||
_first = bars.FirstDay;
|
||||
_last = bars.LastDay;
|
||||
return this;
|
||||
}
|
||||
|
||||
private void Reset(CryptoTrendSettings settings)
|
||||
{
|
||||
_active = new bool[settings.Periods.Count];
|
||||
_stops = new double[settings.Periods.Count];
|
||||
_walked = 0;
|
||||
_first = null;
|
||||
_last = null;
|
||||
Ensemble = 0;
|
||||
ServerStop = null;
|
||||
}
|
||||
|
||||
private void Step(BarSeries bars, int i, CryptoTrendSettings settings)
|
||||
{
|
||||
var close = bars.Close(i);
|
||||
// The stop on the broker, touched by the low of the day: every period of the coin goes back to 0 and a new
|
||||
// high is needed to come back. The backtest applies the same rule (SPEC 8.1).
|
||||
if (Ensemble > 0 && ServerStop is { } server && bars.Low(i) <= server)
|
||||
{
|
||||
Array.Clear(_active);
|
||||
Ensemble = 0;
|
||||
ServerStop = null;
|
||||
}
|
||||
|
||||
var activated = false;
|
||||
for (var k = 0; k < settings.Periods.Count; k++)
|
||||
{
|
||||
var n = settings.Periods[k];
|
||||
if (i < n)
|
||||
{
|
||||
continue; // Not N previous closes yet.
|
||||
}
|
||||
|
||||
if (_active[k])
|
||||
{
|
||||
if (close < _stops[k])
|
||||
{
|
||||
_active[k] = false; // A close below yesterday's stop.
|
||||
continue;
|
||||
}
|
||||
|
||||
_stops[k] = Math.Max(_stops[k], Middle(bars, i, n));
|
||||
}
|
||||
else if (close > HighestBefore(bars, i, n))
|
||||
{
|
||||
_active[k] = true;
|
||||
_stops[k] = Middle(bars, i, n);
|
||||
activated = true;
|
||||
}
|
||||
}
|
||||
|
||||
var on = 0;
|
||||
var lowest = double.MaxValue;
|
||||
for (var k = 0; k < _active.Length; k++)
|
||||
{
|
||||
if (_active[k])
|
||||
{
|
||||
on++;
|
||||
lowest = Math.Min(lowest, _stops[k]);
|
||||
}
|
||||
}
|
||||
|
||||
Ensemble = (double)on / _active.Length;
|
||||
if (on == 0)
|
||||
{
|
||||
ServerStop = null;
|
||||
return;
|
||||
}
|
||||
|
||||
// Where every active period would have left, but never more than the maximum below the close. It can only rise,
|
||||
// except when a period turns on and brings a lower stop with it.
|
||||
var candidate = Math.Max(lowest, close * (1 - settings.MaxStop));
|
||||
ServerStop = ServerStop is { } previous && !activated ? Math.Max(previous, candidate) : candidate;
|
||||
}
|
||||
|
||||
/// <summary>The highest of the N closes before bar i.</summary>
|
||||
private static double HighestBefore(BarSeries bars, int i, int n)
|
||||
{
|
||||
var high = double.MinValue;
|
||||
for (var j = i - n; j < i; j++)
|
||||
{
|
||||
high = Math.Max(high, bars.Close(j));
|
||||
}
|
||||
|
||||
return high;
|
||||
}
|
||||
|
||||
/// <summary>The middle between the highest and the lowest of the last N closes, bar i included.</summary>
|
||||
private static double Middle(BarSeries bars, int i, int n)
|
||||
{
|
||||
double high = double.MinValue, low = double.MaxValue;
|
||||
for (var j = i - n + 1; j <= i; j++)
|
||||
{
|
||||
var c = bars.Close(j);
|
||||
high = Math.Max(high, c);
|
||||
low = Math.Min(low, c);
|
||||
}
|
||||
|
||||
return (high + low) / 2;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CryptoTrendFamily : IStrategyFamily
|
||||
{
|
||||
public const string FamilyId = "crypto_trend";
|
||||
|
||||
public const string FamilyVersion = "1";
|
||||
|
||||
public static CryptoTrendFamily Instance { get; } = new();
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => FamilyVersion;
|
||||
|
||||
public string Name => "Trend crypto";
|
||||
|
||||
public string Description =>
|
||||
"Segue la tendenza delle 10 crypto più scambiate in euro. Compra quando il prezzo supera i massimi recenti su nove orizzonti, da 5 a 360 giorni, " +
|
||||
"e più orizzonti sono d'accordo più compra; pesa meno le monete più agitate. Esce quando il prezzo scende sotto lo stop, che sale con il prezzo.";
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters =>
|
||||
[
|
||||
new("coin_vol", "Volatilità obiettivo per moneta (%)", 15m, [10m, 15m, 20m], 1m, 100m, Whole: true),
|
||||
new("max_stop", "Stop al massimo sotto la chiusura (%)", 15m, [10m, 15m, 20m], 2m, 50m, Whole: true),
|
||||
];
|
||||
|
||||
public IStrategy Create(StrategyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
return new CryptoTrend(new CryptoTrendSettings
|
||||
{
|
||||
CoinVolatility = (double)parameters["coin_vol"] / 100,
|
||||
MaxStop = (double)parameters["max_stop"] / 100,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reading the coin or company behind a symbol.</summary>
|
||||
public static class Symbols
|
||||
{
|
||||
private static readonly string[] Quotes = ["USDT", "USDC", "EUR", "USD", "BTC"];
|
||||
|
||||
/// <summary>The base currency of a pair: <c>BTC</c> for <c>BTC-EUR</c> and for <c>BTCUSDT</c>.</summary>
|
||||
public static string BaseOf(InstrumentSpec spec)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
return spec.BaseCurrency ?? BaseOf(spec.Symbol);
|
||||
}
|
||||
|
||||
public static string BaseOf(InstrumentSpec? spec, string symbol) => spec is null ? BaseOf(symbol) : BaseOf(spec);
|
||||
|
||||
public static string BaseOf(string symbol)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(symbol);
|
||||
var dash = symbol.IndexOf('-', StringComparison.Ordinal);
|
||||
if (dash > 0)
|
||||
{
|
||||
return symbol[..dash];
|
||||
}
|
||||
|
||||
foreach (var quote in Quotes)
|
||||
{
|
||||
if (symbol.Length > quote.Length && symbol.EndsWith(quote, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return symbol[..^quote.Length];
|
||||
}
|
||||
}
|
||||
|
||||
return symbol;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.Strategies;
|
||||
|
||||
/// <summary>
|
||||
/// The stock universe of SPEC 8.2 computed from the bars known on the day: common shares on NYSE and Nasdaq,
|
||||
/// fractionable, no funds, real close above 10 $, at least 300 sessions, ranked by the median traded value of the last
|
||||
/// 60 sessions. Live, the universe saved "as of the date" is used instead (SPEC 6.7).
|
||||
/// </summary>
|
||||
public static class EquityUniverseRanking
|
||||
{
|
||||
public static IReadOnlyList<string> Rank(UniverseContext context, int size)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var ranked = new List<(string Symbol, double Value)>();
|
||||
foreach (var symbol in context.Available)
|
||||
{
|
||||
if (context.Spec(symbol) is not { } spec || !EquityUniverse.Eligible(spec))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var bars = context.Bars(symbol);
|
||||
var last = bars.Count - 1;
|
||||
if (bars.Count < EquityUniverse.MinSessions || bars.Day(last) < context.Day.AddDays(-7) || bars.RealClose(last) <= EquityUniverse.MinPrice)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ranked.Add((symbol, Indicators.MedianValue(bars, EquityUniverse.Window, last) ?? 0));
|
||||
}
|
||||
|
||||
return [.. ranked.OrderByDescending(r => r.Value).ThenBy(r => r.Symbol, StringComparer.Ordinal).Take(size).Select(r => r.Symbol)];
|
||||
}
|
||||
|
||||
/// <summary>Monday of the week of a day: two days are in the same week when their Mondays match.</summary>
|
||||
public static DateOnly WeekOf(DateOnly day) => day.AddDays(-(((int)day.DayOfWeek + 6) % 7));
|
||||
}
|
||||
|
||||
/// <summary>The fixed rules of <c>equity_momentum</c> (SPEC 8.2).</summary>
|
||||
public sealed record EquityMomentumSettings
|
||||
{
|
||||
public int UniverseSize { get; init; } = EquityUniverse.Size;
|
||||
|
||||
public IReadOnlyList<int> Lookbacks { get; init; } = [63, 126, 252];
|
||||
|
||||
/// <summary>The returns skip the last sessions (short-term reversal).</summary>
|
||||
public int Skip { get; init; } = 5;
|
||||
|
||||
/// <summary>New entries among the first of the ranking…</summary>
|
||||
public int Top { get; init; } = 12;
|
||||
|
||||
/// <summary>…and a stock held leaves when it falls out of these.</summary>
|
||||
public int Keep { get; init; } = 30;
|
||||
|
||||
public int MaxPositions { get; init; } = 12;
|
||||
|
||||
/// <summary>Each stock must close above its own average of these sessions.</summary>
|
||||
public int Trend { get; init; } = 100;
|
||||
|
||||
/// <summary>The market filter: SPY above its average of these sessions.</summary>
|
||||
public int MarketTrend { get; init; } = 200;
|
||||
|
||||
public string MarketSymbol { get; init; } = "SPY";
|
||||
|
||||
public int AtrLength { get; init; } = 20;
|
||||
|
||||
public double AtrMultiple { get; init; } = 3;
|
||||
|
||||
public int VolatilityWindow { get; init; } = 60;
|
||||
|
||||
public double StrategyVolatility { get; init; } = 0.20;
|
||||
|
||||
public decimal Cap { get; init; } = 0.15m;
|
||||
|
||||
/// <summary>A position already open is resized only when this far from its target, relative to the target.</summary>
|
||||
public decimal Rebalance { get; init; } = 0.25m;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>equity_momentum</c> (SPEC 8.2): the strongest US stocks, only while the market rises. The weekly review runs on
|
||||
/// the close of the last session before a new week, so its orders go at the open of the first session of the week
|
||||
/// (live: 09:35 of that session, on the same data). Every close moves the trailing stops.
|
||||
/// </summary>
|
||||
public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IStrategy
|
||||
{
|
||||
private readonly EquityMomentumSettings _settings = settings ?? new EquityMomentumSettings();
|
||||
|
||||
public string Id => EquityMomentumFamily.FamilyId;
|
||||
|
||||
public string Version => EquityMomentumFamily.FamilyVersion;
|
||||
|
||||
public EquityMomentumSettings Settings => _settings;
|
||||
|
||||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||
|
||||
public IReadOnlyList<string> Universe(UniverseContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return context.Members?.Invoke(Id, context.Day) ?? EquityUniverseRanking.Rank(context, _settings.UniverseSize);
|
||||
}
|
||||
|
||||
/// <summary>True when the next session opens a new week: the close of today is the time of the weekly review.</summary>
|
||||
public static bool IsReview(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return context.NextSession is { } next && EquityUniverseRanking.WeekOf(next) != EquityUniverseRanking.WeekOf(context.Day);
|
||||
}
|
||||
|
||||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var equity = context.Portfolio.Equity;
|
||||
var held = context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).Select(h => h.Key).Order(StringComparer.Ordinal).ToList();
|
||||
var stops = new Dictionary<string, decimal>(StringComparer.Ordinal);
|
||||
foreach (var symbol in held)
|
||||
{
|
||||
if (TrailingStop(context, symbol) is { } stop)
|
||||
{
|
||||
stops[symbol] = stop;
|
||||
}
|
||||
}
|
||||
|
||||
var intents = new SortedDictionary<string, Intent>(StringComparer.Ordinal);
|
||||
foreach (var (symbol, stop) in stops)
|
||||
{
|
||||
intents[symbol] = new Intent(symbol, null, Reasons.StopMoved) { Stop = stop };
|
||||
}
|
||||
|
||||
if (!IsReview(context) || equity <= 0m)
|
||||
{
|
||||
return [.. intents.Values];
|
||||
}
|
||||
|
||||
// The ranking: average of the 63, 126 and 252 session returns, each skipping the last 5 sessions.
|
||||
var scores = new List<(string Symbol, double Score)>();
|
||||
foreach (var symbol in context.Universe)
|
||||
{
|
||||
var bars = context.Bars(symbol);
|
||||
var parts = _settings.Lookbacks.Select(n => Indicators.Momentum(bars, n, _settings.Skip)).ToList();
|
||||
if (parts.All(p => p is not null))
|
||||
{
|
||||
scores.Add((symbol, parts.Average(p => p!.Value)));
|
||||
}
|
||||
}
|
||||
|
||||
var ranking = scores.OrderByDescending(s => s.Score).ThenBy(s => s.Symbol, StringComparer.Ordinal).Select(s => s.Symbol).ToList();
|
||||
var rank = ranking.Select((s, i) => (s, i)).ToDictionary(x => x.s, x => x.i, StringComparer.Ordinal);
|
||||
bool AboveTrend(string symbol)
|
||||
{
|
||||
var bars = context.Bars(symbol);
|
||||
return Indicators.Sma(bars, _settings.Trend) is { } average && bars.Count > 0 && bars.Close(bars.Count - 1) > average;
|
||||
}
|
||||
|
||||
var market = context.Bars(_settings.MarketSymbol);
|
||||
var marketUp = Indicators.Sma(market, _settings.MarketTrend) is { } spyAverage && market.Close(market.Count - 1) > spyAverage;
|
||||
|
||||
var keep = new List<string>();
|
||||
foreach (var symbol in held)
|
||||
{
|
||||
if (!rank.TryGetValue(symbol, out var r) || r >= _settings.Keep)
|
||||
{
|
||||
intents[symbol] = new Intent(symbol, 0m, Reasons.ExitRank);
|
||||
}
|
||||
else if (!AboveTrend(symbol))
|
||||
{
|
||||
intents[symbol] = new Intent(symbol, 0m, Reasons.ExitTrend);
|
||||
}
|
||||
else
|
||||
{
|
||||
keep.Add(symbol);
|
||||
}
|
||||
}
|
||||
|
||||
// New entries only while SPY is above its average, and only among the first 12.
|
||||
var entries = new List<string>();
|
||||
if (marketUp)
|
||||
{
|
||||
foreach (var symbol in ranking.Take(_settings.Top))
|
||||
{
|
||||
if (keep.Count + entries.Count >= _settings.MaxPositions)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (!held.Contains(symbol) && AboveTrend(symbol))
|
||||
{
|
||||
entries.Add(symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var weights = Weights(context, [.. keep, .. entries]);
|
||||
foreach (var symbol in entries)
|
||||
{
|
||||
if (weights.GetValueOrDefault(symbol) is > 0m and var weight && Indicators.Atr(context.Bars(symbol), _settings.AtrLength) is { } atr)
|
||||
{
|
||||
intents[symbol] = new Intent(symbol, weight, Reasons.Entry) { StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8) };
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var symbol in keep)
|
||||
{
|
||||
var bars = context.Bars(symbol);
|
||||
var holding = context.Portfolio.Of(symbol)!;
|
||||
var current = holding.Quantity * (decimal)bars.Close(bars.Count - 1) / equity;
|
||||
var target = weights.GetValueOrDefault(symbol, current);
|
||||
if (!marketUp)
|
||||
{
|
||||
target = Math.Min(target, current); // With SPY below its average the strategy can only sell.
|
||||
}
|
||||
|
||||
if (Math.Abs(target - current) > _settings.Rebalance * target)
|
||||
{
|
||||
intents[symbol] = new Intent(symbol, target, target > current ? Reasons.Increase : Reasons.Reduce) { Stop = stops.GetValueOrDefault(symbol, holding.Stop ?? 0m) is > 0m and var s ? s : null };
|
||||
}
|
||||
}
|
||||
|
||||
return [.. intents.Values];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Weights in inverse proportion to the 60-session volatility, the 15% cap (what it cuts stays cash), then one
|
||||
/// factor, never above 1, when the strategy's estimated volatility is above 20% a year.
|
||||
/// </summary>
|
||||
private Dictionary<string, decimal> Weights(StrategyContext context, IReadOnlyList<string> members)
|
||||
{
|
||||
var inverse = new Dictionary<string, double>(StringComparer.Ordinal);
|
||||
foreach (var symbol in members)
|
||||
{
|
||||
if (Indicators.Volatility(context.Bars(symbol), _settings.VolatilityWindow, 252) is > 0 and var vol)
|
||||
{
|
||||
inverse[symbol] = 1 / vol;
|
||||
}
|
||||
}
|
||||
|
||||
var sum = inverse.Values.Sum();
|
||||
var raw = inverse.ToDictionary(p => p.Key, p => Math.Min(p.Value / sum, (double)_settings.Cap), StringComparer.Ordinal);
|
||||
var portfolio = Indicators.PortfolioVolatility([.. raw.Select(p => (context.Bars(p.Key), p.Value))], _settings.VolatilityWindow, 252);
|
||||
var factor = portfolio is > 0 && portfolio.Value > _settings.StrategyVolatility ? _settings.StrategyVolatility / portfolio.Value : 1;
|
||||
return raw.ToDictionary(p => p.Key, p => Math.Round((decimal)(p.Value * factor), 6, MidpointRounding.ToZero), StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>3 ATR(20) below the highest close since the entry; it can only rise.</summary>
|
||||
private decimal? TrailingStop(StrategyContext context, string symbol)
|
||||
{
|
||||
var holding = context.Portfolio.Of(symbol)!;
|
||||
var bars = context.Bars(symbol);
|
||||
if (Indicators.Atr(bars, _settings.AtrLength) is not { } atr || Indicators.HighestCloseSince(bars, holding.EnteredOn) is not { } high)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var candidate = Math.Round((decimal)(high - (_settings.AtrMultiple * atr)), 8);
|
||||
if (candidate <= 0m || (holding.Stop is { } current && candidate <= current))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return candidate;
|
||||
}
|
||||
|
||||
public static class Reasons
|
||||
{
|
||||
public const string Entry = "momentum_entry";
|
||||
public const string Increase = "momentum_increase";
|
||||
public const string Reduce = "momentum_reduce";
|
||||
public const string ExitRank = "momentum_exit_rank";
|
||||
public const string ExitTrend = "momentum_exit_trend";
|
||||
public const string StopMoved = "momentum_stop";
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class EquityMomentumFamily : IStrategyFamily
|
||||
{
|
||||
public const string FamilyId = "equity_momentum";
|
||||
|
||||
public const string FamilyVersion = "1";
|
||||
|
||||
public static EquityMomentumFamily Instance { get; } = new();
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => FamilyVersion;
|
||||
|
||||
public string Name => "Momentum azioni";
|
||||
|
||||
public string Description =>
|
||||
"Ogni settimana compra le azioni americane salite di più nell'ultimo anno, fino a 12, ma solo quando il mercato nel suo insieme sale. " +
|
||||
"Vende quelle che perdono forza o scendono sotto la loro media; ognuna ha uno stop che sale con il prezzo.";
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters =>
|
||||
[
|
||||
new("positions", "Numero massimo di titoli", 12m, [8m, 12m, 16m], 3m, 30m, Whole: true),
|
||||
new("stop_atr", "Stop in ATR sotto il massimo", 3m, [2m, 3m, 4m], 1m, 10m, Whole: true),
|
||||
];
|
||||
|
||||
public IStrategy Create(StrategyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
var positions = parameters.Whole("positions");
|
||||
return new EquityMomentum(new EquityMomentumSettings
|
||||
{
|
||||
Top = positions,
|
||||
MaxPositions = positions,
|
||||
AtrMultiple = (double)parameters["stop_atr"],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The fixed rules of <c>equity_meanrev</c> (SPEC 8.3).</summary>
|
||||
public sealed record EquityMeanrevSettings
|
||||
{
|
||||
public int UniverseSize { get; init; } = 100;
|
||||
|
||||
public int Trend { get; init; } = 200;
|
||||
|
||||
public int RsiLength { get; init; } = 2;
|
||||
|
||||
public double EntryRsi { get; init; } = 10;
|
||||
|
||||
public double ExitRsi { get; init; } = 70;
|
||||
|
||||
public int Fast { get; init; } = 5;
|
||||
|
||||
public int MaxPositions { get; init; } = 3;
|
||||
|
||||
/// <summary>The entry session is the first: the time exit comes at the close of the fifth.</summary>
|
||||
public int MaxSessions { get; init; } = 5;
|
||||
|
||||
public int AtrLength { get; init; } = 14;
|
||||
|
||||
public double AtrMultiple { get; init; } = 2.5;
|
||||
|
||||
/// <summary>Risk of one operation, as a share of the reference equity of SPEC 9.2.</summary>
|
||||
public decimal RiskPerTrade { get; init; } = 0.004m;
|
||||
|
||||
public decimal Cap { get; init; } = 0.30m;
|
||||
|
||||
/// <summary>The day-trade guard of SPEC 9.2, off by default: never exit on the entry day.</summary>
|
||||
public bool PdtGuard { get; init; }
|
||||
|
||||
/// <summary>Sessions after the entry in which an earnings report keeps the strategy out.</summary>
|
||||
public int EarningsSessions { get; init; } = 3;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>equity_meanrev</c> (SPEC 8.3): buys the short dips of solid stocks. On the close, RSI(2) below 10 and the close
|
||||
/// below its 5-session average; buys at the next open the lowest RSI, up to 3 positions. It exits at 15:55 (in the
|
||||
/// backtest: the close) above the 5-session average, with RSI(2) above 70, before earnings, or at the fifth session.
|
||||
/// </summary>
|
||||
public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStrategy
|
||||
{
|
||||
private readonly EquityMeanrevSettings _settings = settings ?? new EquityMeanrevSettings();
|
||||
|
||||
public string Id => EquityMeanrevFamily.FamilyId;
|
||||
|
||||
public string Version => EquityMeanrevFamily.FamilyVersion;
|
||||
|
||||
public EquityMeanrevSettings Settings => _settings;
|
||||
|
||||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||
|
||||
/// <summary>The first 100 stocks of the universe of 8.2, in its order, that close above their 200-session average.</summary>
|
||||
public IReadOnlyList<string> Universe(UniverseContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var ranked = context.Members?.Invoke(EquityMomentumFamily.FamilyId, context.Day) ?? EquityUniverseRanking.Rank(context, EquityUniverse.Size);
|
||||
return [.. ranked.Where(s =>
|
||||
{
|
||||
var bars = context.Bars(s);
|
||||
return Indicators.Sma(bars, _settings.Trend) is { } average && bars.Close(bars.Count - 1) > average;
|
||||
}).Take(_settings.UniverseSize)];
|
||||
}
|
||||
|
||||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var equity = context.Portfolio.Equity;
|
||||
var intents = new List<Intent>();
|
||||
var freeCash = context.Portfolio.Cash;
|
||||
var open = 0;
|
||||
foreach (var (symbol, holding) in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).OrderBy(h => h.Key, StringComparer.Ordinal))
|
||||
{
|
||||
var bars = context.Bars(symbol);
|
||||
if (bars.Count == 0)
|
||||
{
|
||||
open++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var close = bars.Close(bars.Count - 1);
|
||||
var sessions = Indicators.SessionsSince(bars, holding.EnteredOn);
|
||||
var reason = ExitReason(context, symbol, bars, close, sessions);
|
||||
if (reason is not null && !(_settings.PdtGuard && sessions <= 1))
|
||||
{
|
||||
intents.Add(new Intent(symbol, 0m, reason) { AtClose = true });
|
||||
freeCash += holding.Quantity * (decimal)close; // Sold at this close, before tomorrow's entries.
|
||||
}
|
||||
else
|
||||
{
|
||||
open++;
|
||||
}
|
||||
}
|
||||
|
||||
var slots = _settings.MaxPositions - open;
|
||||
if (slots <= 0 || equity <= 0m)
|
||||
{
|
||||
return intents;
|
||||
}
|
||||
|
||||
var candidates = new List<(string Symbol, double Rsi, double Close, double Atr)>();
|
||||
foreach (var symbol in context.Universe)
|
||||
{
|
||||
if (context.Portfolio.Holds(symbol) || context.Restricted?.Invoke(symbol) == true || EarningsAhead(context, symbol))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var bars = context.Bars(symbol);
|
||||
if (Indicators.Rsi(bars, _settings.RsiLength) is not { } rsi || Indicators.Sma(bars, _settings.Fast) is not { } fast
|
||||
|| Indicators.Atr(bars, _settings.AtrLength) is not { } atr)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var close = bars.Close(bars.Count - 1);
|
||||
if (rsi < _settings.EntryRsi && close < fast)
|
||||
{
|
||||
candidates.Add((symbol, rsi, close, atr));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var c in candidates.OrderBy(c => c.Rsi).ThenBy(c => c.Symbol, StringComparer.Ordinal))
|
||||
{
|
||||
if (slots == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// Risk of 0.4% of the reference equity at the stop distance, capped at 30% of the strategy's capital.
|
||||
var distance = Math.Round((decimal)(c.Atr * _settings.AtrMultiple), 8);
|
||||
if (distance <= 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var value = _settings.RiskPerTrade * context.ReferenceEquity / distance * (decimal)c.Close;
|
||||
value = Math.Min(value, _settings.Cap * equity);
|
||||
if (value > freeCash)
|
||||
{
|
||||
continue; // Not enough free capital for this candidate: it is dropped.
|
||||
}
|
||||
|
||||
intents.Add(new Intent(c.Symbol, Math.Round(value / equity, 6, MidpointRounding.ToZero), Reasons.Entry) { StopOffset = distance });
|
||||
freeCash -= value;
|
||||
slots--;
|
||||
}
|
||||
|
||||
return intents;
|
||||
}
|
||||
|
||||
private string? ExitReason(StrategyContext context, string symbol, BarSeries bars, double close, int sessions)
|
||||
{
|
||||
if (Indicators.Sma(bars, _settings.Fast) is { } fast && close > fast)
|
||||
{
|
||||
return Reasons.ExitAverage;
|
||||
}
|
||||
|
||||
if (Indicators.Rsi(bars, _settings.RsiLength) is > 0 and var rsi && rsi > _settings.ExitRsi)
|
||||
{
|
||||
return Reasons.ExitRsi;
|
||||
}
|
||||
|
||||
if (context.NextEarnings?.Invoke(symbol) is { } earnings && context.NextSession is { } next && earnings <= next)
|
||||
{
|
||||
return Reasons.ExitEarnings; // The report comes out by the close of the next session.
|
||||
}
|
||||
|
||||
return sessions >= _settings.MaxSessions ? Reasons.ExitTime : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Earnings in the entry session or the three after it, or out after today's close (live only: the backtest has no
|
||||
/// earnings calendar, SPEC 8.3).
|
||||
/// </summary>
|
||||
private bool EarningsAhead(StrategyContext context, string symbol)
|
||||
{
|
||||
if (context.NextEarnings?.Invoke(symbol) is not { } earnings || context.NextSession is not { } entry)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var last = entry;
|
||||
for (var i = 0; i < _settings.EarningsSessions; i++)
|
||||
{
|
||||
last = last.AddDays(last.DayOfWeek == DayOfWeek.Friday ? 3 : 1);
|
||||
}
|
||||
|
||||
return earnings >= context.Day && earnings <= last;
|
||||
}
|
||||
|
||||
public static class Reasons
|
||||
{
|
||||
public const string Entry = "meanrev_entry";
|
||||
public const string ExitAverage = "meanrev_exit_average";
|
||||
public const string ExitRsi = "meanrev_exit_rsi";
|
||||
public const string ExitEarnings = "meanrev_exit_earnings";
|
||||
public const string ExitTime = "meanrev_exit_time";
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class EquityMeanrevFamily : IStrategyFamily
|
||||
{
|
||||
public const string FamilyId = "equity_meanrev";
|
||||
|
||||
public const string FamilyVersion = "1";
|
||||
|
||||
public static EquityMeanrevFamily Instance { get; } = new();
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => FamilyVersion;
|
||||
|
||||
public string Name => "Mean reversion azioni";
|
||||
|
||||
public string Description =>
|
||||
"Compra le azioni solide, sopra la loro media di 200 giorni, dopo un calo di pochi giorni, e le rivende al primo rimbalzo o dopo cinque sedute. " +
|
||||
"Al massimo 3 posizioni, ognuna con un rischio piccolo e uno stop fisso.";
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters =>
|
||||
[
|
||||
new("entry_rsi", "RSI a 2 giorni per entrare (sotto)", 10m, [5m, 10m, 15m], 1m, 50m, Whole: true),
|
||||
new("max_sessions", "Sedute al massimo in portafoglio", 5m, [3m, 5m, 7m], 1m, 20m, Whole: true),
|
||||
];
|
||||
|
||||
public IStrategy Create(StrategyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
return new EquityMeanrev(new EquityMeanrevSettings
|
||||
{
|
||||
EntryRsi = (double)parameters["entry_rsi"],
|
||||
MaxSessions = parameters.Whole("max_sessions"),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
namespace Anubis.Strategies;
|
||||
|
||||
/// <summary>
|
||||
/// The indicators of the strategies (SPEC 8), written in house (SPEC 2.7). Each reads a <see cref="BarSeries"/> up to
|
||||
/// its last bar, so it cannot look ahead. They return null when the history is too short: a strategy then does not
|
||||
/// act on that instrument.
|
||||
/// </summary>
|
||||
public static class Indicators
|
||||
{
|
||||
/// <summary>Simple average of the last <paramref name="length"/> closes.</summary>
|
||||
public static double? Sma(BarSeries bars, int length) => Sma(bars, length, bars?.Count - 1 ?? -1);
|
||||
|
||||
/// <summary>Simple average of the <paramref name="length"/> closes ending at <paramref name="end"/>, included.</summary>
|
||||
public static double? Sma(BarSeries bars, int length, int end)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
if (length <= 0 || end < length - 1 || end >= bars.Count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var sum = 0d;
|
||||
for (var i = end - length + 1; i <= end; i++)
|
||||
{
|
||||
sum += bars.Close(i);
|
||||
}
|
||||
|
||||
return sum / length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Average true range: the simple average of the last <paramref name="length"/> true ranges, each the largest of
|
||||
/// high − low, |high − previous close| and |low − previous close|. A plain average, so the value depends only on
|
||||
/// those bars and not on where the history starts.
|
||||
/// </summary>
|
||||
public static double? Atr(BarSeries bars, int length)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
var end = bars.Count - 1;
|
||||
if (length <= 0 || end < length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var sum = 0d;
|
||||
for (var i = end - length + 1; i <= end; i++)
|
||||
{
|
||||
var previous = bars.Close(i - 1);
|
||||
var high = bars.High(i);
|
||||
var low = bars.Low(i);
|
||||
sum += Math.Max(high - low, Math.Max(Math.Abs(high - previous), Math.Abs(low - previous)));
|
||||
}
|
||||
|
||||
return sum / length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wilder's relative strength index on the closes. The smoothing starts from a plain average of the first
|
||||
/// <paramref name="length"/> changes of a window of <see cref="RsiWarmUp"/> × length bars: older bars weigh less
|
||||
/// than one part in a million, and the value does not depend on where the history starts.
|
||||
/// </summary>
|
||||
public static double? Rsi(BarSeries bars, int length)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
if (length <= 0 || bars.Count < length + 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var start = Math.Max(0, bars.Count - (RsiWarmUp * length) - 1);
|
||||
double gain = 0, loss = 0;
|
||||
for (var i = start + 1; i <= start + length; i++)
|
||||
{
|
||||
var change = bars.Close(i) - bars.Close(i - 1);
|
||||
gain += Math.Max(change, 0);
|
||||
loss += Math.Max(-change, 0);
|
||||
}
|
||||
|
||||
gain /= length;
|
||||
loss /= length;
|
||||
for (var i = start + length + 1; i < bars.Count; i++)
|
||||
{
|
||||
var change = bars.Close(i) - bars.Close(i - 1);
|
||||
gain = ((gain * (length - 1)) + Math.Max(change, 0)) / length;
|
||||
loss = ((loss * (length - 1)) + Math.Max(-change, 0)) / length;
|
||||
}
|
||||
|
||||
if (loss == 0)
|
||||
{
|
||||
return gain == 0 ? 50 : 100;
|
||||
}
|
||||
|
||||
return 100 - (100 / (1 + (gain / loss)));
|
||||
}
|
||||
|
||||
/// <summary>Bars of history the RSI reads, in multiples of its length.</summary>
|
||||
public const int RsiWarmUp = 50;
|
||||
|
||||
/// <summary>The last <paramref name="count"/> simple daily returns, oldest first; null when the history is shorter.</summary>
|
||||
public static double[]? Returns(BarSeries bars, int count)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
if (count <= 0 || bars.Count < count + 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var result = new double[count];
|
||||
var first = bars.Count - count;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var before = bars.Close(first + i - 1);
|
||||
result[i] = before > 0 ? (bars.Close(first + i) / before) - 1 : 0;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Annualised volatility of the last <paramref name="count"/> daily returns: sample standard deviation times the
|
||||
/// square root of the sessions in a year.
|
||||
/// </summary>
|
||||
public static double? Volatility(BarSeries bars, int count, int periodsPerYear)
|
||||
{
|
||||
var returns = Returns(bars, count);
|
||||
if (returns is null || returns.Length < 2)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return StandardDeviation(returns) * Math.Sqrt(periodsPerYear);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The return over <paramref name="length"/> sessions that ends <paramref name="skip"/> sessions before the last
|
||||
/// bar: close[t − skip] / close[t − skip − length] − 1.
|
||||
/// </summary>
|
||||
public static double? Momentum(BarSeries bars, int length, int skip)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
var end = bars.Count - 1 - skip;
|
||||
var start = end - length;
|
||||
if (start < 0 || end < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var before = bars.Close(start);
|
||||
return before > 0 ? (bars.Close(end) / before) - 1 : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Annualised volatility of a portfolio with the given weights, from the covariance of the last
|
||||
/// <paramref name="count"/> daily returns of each instrument, aligned by day. Days missing for an instrument count
|
||||
/// as no change. Null when no instrument has enough history.
|
||||
/// </summary>
|
||||
public static double? PortfolioVolatility(IReadOnlyList<(BarSeries Bars, double Weight)> holdings, int count, int periodsPerYear)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(holdings);
|
||||
var series = new List<(Dictionary<DateOnly, double> Returns, double Weight)>();
|
||||
var days = new SortedSet<DateOnly>();
|
||||
foreach (var (bars, weight) in holdings)
|
||||
{
|
||||
if (weight == 0 || bars.Count < count + 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var map = new Dictionary<DateOnly, double>(count);
|
||||
for (var i = bars.Count - count; i < bars.Count; i++)
|
||||
{
|
||||
var before = bars.Close(i - 1);
|
||||
map[bars.Day(i)] = before > 0 ? (bars.Close(i) / before) - 1 : 0;
|
||||
}
|
||||
|
||||
series.Add((map, weight));
|
||||
}
|
||||
|
||||
if (series.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// The common calendar is the last `count` days any of them traded.
|
||||
foreach (var (map, _) in series)
|
||||
{
|
||||
days.UnionWith(map.Keys);
|
||||
}
|
||||
|
||||
var calendar = days.TakeLast(count).ToList();
|
||||
if (calendar.Count < 2)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var portfolio = calendar.Select(d => series.Sum(s => s.Weight * s.Returns.GetValueOrDefault(d))).ToArray();
|
||||
return StandardDeviation(portfolio) * Math.Sqrt(periodsPerYear);
|
||||
}
|
||||
|
||||
/// <summary>Sample standard deviation (n − 1).</summary>
|
||||
public static double StandardDeviation(IReadOnlyList<double> values)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
if (values.Count < 2)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var mean = values.Average();
|
||||
var sum = 0d;
|
||||
foreach (var v in values)
|
||||
{
|
||||
sum += (v - mean) * (v - mean);
|
||||
}
|
||||
|
||||
return Math.Sqrt(sum / (values.Count - 1));
|
||||
}
|
||||
|
||||
/// <summary>Highest close from <paramref name="from"/> to the last bar, both included.</summary>
|
||||
public static double? HighestCloseSince(BarSeries bars, DateOnly from)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
double? high = null;
|
||||
for (var i = bars.Count - 1; i >= 0 && bars.Day(i) >= from; i--)
|
||||
{
|
||||
high = Math.Max(high ?? double.MinValue, bars.Close(i));
|
||||
}
|
||||
|
||||
return high;
|
||||
}
|
||||
|
||||
/// <summary>Sessions from <paramref name="from"/> to the last bar, both included.</summary>
|
||||
public static int SessionsSince(BarSeries bars, DateOnly from)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
var n = 0;
|
||||
for (var i = bars.Count - 1; i >= 0 && bars.Day(i) >= from; i--)
|
||||
{
|
||||
n++;
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>Median of the last <paramref name="count"/> traded values (close × volume, or the quote volume when known).</summary>
|
||||
public static double? MedianValue(BarSeries bars, int count, int end)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
if (end < count - 1 || end >= bars.Count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var values = new double[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var k = end - count + 1 + i;
|
||||
values[i] = bars.Value(k);
|
||||
}
|
||||
|
||||
Array.Sort(values);
|
||||
return count % 2 == 1 ? values[count / 2] : (values[(count / 2) - 1] + values[count / 2]) / 2;
|
||||
}
|
||||
}
|
||||
@@ -143,10 +143,11 @@ public sealed class MovingAverageCrossFamily : IStrategyFamily
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The strategies the laboratory can test. The bot's own strategies join with Phase 5.</summary>
|
||||
/// <summary>The strategies the laboratory can test: the three of the bot first, then the examples.</summary>
|
||||
public static class StrategyCatalog
|
||||
{
|
||||
public static IReadOnlyList<IStrategyFamily> All { get; } = [MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance];
|
||||
public static IReadOnlyList<IStrategyFamily> All { get; } =
|
||||
[CryptoTrendFamily.Instance, EquityMomentumFamily.Instance, EquityMeanrevFamily.Instance, MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance];
|
||||
|
||||
public static IStrategyFamily? Find(string id) => All.FirstOrDefault(f => f.Id == id);
|
||||
}
|
||||
@@ -28,6 +28,18 @@ public sealed record Intent(string Symbol, decimal? TargetWeight, string Reason)
|
||||
{
|
||||
public decimal? Stop { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// For a new position: the stop goes this far below the price obtained (a distance in today's prices, such as 3
|
||||
/// ATR). Ignored when <see cref="Stop"/> is given or the position already has a stop.
|
||||
/// </summary>
|
||||
public decimal? StopOffset { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// An exit to carry out at this close rather than at the next open: <c>equity_meanrev</c> sells at 15:55 live,
|
||||
/// which the daily backtest reads as the close (SPEC 8.3).
|
||||
/// </summary>
|
||||
public bool AtClose { get; init; }
|
||||
|
||||
public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Symbol} {(TargetWeight is { } w ? w.ToString(CultureInfo.InvariantCulture) : "keep")} stop {(Stop is { } s ? s.ToString(CultureInfo.InvariantCulture) : "-")} ({Reason})");
|
||||
}
|
||||
|
||||
@@ -94,6 +106,42 @@ public sealed class BarSeries
|
||||
|
||||
public double Volume(int index) => Bar(index).Volume;
|
||||
|
||||
/// <summary>Value traded in the session, in the quote currency: the source's own figure, or close × volume.</summary>
|
||||
public double Value(int index)
|
||||
{
|
||||
var bar = Bar(index);
|
||||
return bar.QuoteVolume ?? (bar.Close * bar.Volume);
|
||||
}
|
||||
|
||||
/// <summary>The real close of the session, as traded that day, not adjusted to today.</summary>
|
||||
public double RealClose(int index) => Bar(index).Close;
|
||||
|
||||
/// <summary>Index of the last bar on or before <paramref name="day"/>; −1 when there is none.</summary>
|
||||
public int IndexThrough(DateOnly day)
|
||||
{
|
||||
int lo = 0, hi = Count;
|
||||
while (lo < hi)
|
||||
{
|
||||
var mid = (lo + hi) / 2;
|
||||
if (_bars[mid].Day <= day)
|
||||
{
|
||||
lo = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
|
||||
return lo - 1;
|
||||
}
|
||||
|
||||
/// <summary>The first day of the history; null when there is none.</summary>
|
||||
public DateOnly? FirstDay => Count > 0 ? _bars[0].Day : null;
|
||||
|
||||
/// <summary>The day of the last bar; null when there is none.</summary>
|
||||
public DateOnly? LastDay => Count > 0 ? _bars[Count - 1].Day : null;
|
||||
|
||||
/// <summary>The last <paramref name="length"/> closes, oldest first (fewer when the history is shorter).</summary>
|
||||
public double[] Closes(int length)
|
||||
{
|
||||
@@ -115,8 +163,22 @@ public sealed class BarSeries
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a strategy may read to choose its instruments for a decision.</summary>
|
||||
public sealed record UniverseContext(DateOnly Day, IReadOnlyList<string> Available);
|
||||
/// <summary>
|
||||
/// What a strategy may read to choose its instruments for a decision: the instruments with data, their bars up to the
|
||||
/// day and their rules. Live, <see cref="Members"/> gives the universes chosen and saved "as of a date" (SPEC 6.7).
|
||||
/// </summary>
|
||||
public sealed record UniverseContext(DateOnly Day, IReadOnlyList<string> Available)
|
||||
{
|
||||
public Func<string, BarSeries> Bars { get; init; } = _ => BarSeries.Empty;
|
||||
|
||||
public Func<string, InstrumentSpec?> Spec { get; init; } = _ => null;
|
||||
|
||||
/// <summary>Median spread of the last 30 days in basis points, live only; null in a backtest (no history).</summary>
|
||||
public Func<string, double?>? SpreadBp { get; init; }
|
||||
|
||||
/// <summary>The saved universe of a strategy on a date, live; null means "compute it from the bars".</summary>
|
||||
public Func<string, DateOnly, IReadOnlyList<string>?>? Members { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Named numeric parameters of a strategy variant. Values are decimal so a grid is written exactly.</summary>
|
||||
public sealed class StrategyParameters
|
||||
@@ -169,8 +231,45 @@ public sealed class StrategyContext(
|
||||
public BarSeries Bars(string symbol) => bars(symbol);
|
||||
|
||||
public InstrumentSpec? Spec(string symbol) => spec(symbol);
|
||||
|
||||
/// <summary>
|
||||
/// The next session of the market calendar after <see cref="Day"/>. Calendars are published in advance, so this
|
||||
/// is not looking ahead: <c>equity_momentum</c> uses it to find the last session before a new week.
|
||||
/// </summary>
|
||||
public DateOnly? NextSession { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The reference equity of SPEC 9.2: capital entrusted on every broker plus the strategies' results, which does
|
||||
/// not move when a strategy changes stage. In the backtest of one strategy: its equity divided by its share of
|
||||
/// the total. Defaults to the strategy's equity.
|
||||
/// </summary>
|
||||
public decimal ReferenceEquity
|
||||
{
|
||||
get => _reference ?? Portfolio.Equity;
|
||||
init => _reference = value;
|
||||
}
|
||||
|
||||
private readonly decimal? _reference;
|
||||
|
||||
/// <summary>Sessions in a year for this market: 365 for crypto, 252 for stocks.</summary>
|
||||
public int PeriodsPerYear { get; init; } = 365;
|
||||
|
||||
/// <summary>Next earnings date of a stock, live and when the calendar has it; null in a backtest (SPEC 8.3).</summary>
|
||||
public Func<string, DateOnly?>? NextEarnings { get; init; }
|
||||
|
||||
/// <summary>A restriction from the news on the instrument (SPEC 10.5, Phase 7); null in a backtest.</summary>
|
||||
public Func<string, bool>? Restricted { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The strategy's equity at each earlier close, up to and including this one: what the risk limits of SPEC 9.2
|
||||
/// measure losses and the fall from the high on.
|
||||
/// </summary>
|
||||
public IReadOnlyList<EquityMark> History { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>The equity at a close and the part of it in positions.</summary>
|
||||
public sealed record EquityMark(DateOnly Day, decimal Equity, decimal Invested);
|
||||
|
||||
/// <summary>A trading strategy (SPEC 5.3): a function of the data up to "now" and of its own book, nothing else.</summary>
|
||||
public interface IStrategy
|
||||
{
|
||||
|
||||
@@ -0,0 +1,562 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user