Add the event-driven backtest engine and the strategy interface (refs #34)
The strategy contract of SPEC 5.3 (IStrategy, StrategyContext, Intent) is shared by backtest and live: the context exposes bars only up to the decision, adjusted and anchored to that day, and reading past it throws. The engine runs each session as ordered events (corporate actions, open, session, close), decides on the close and executes at the next open with the simulator's price lists, slippage tiers, tick and lot rounding, minimums and no leverage. Corrective and risk hooks are wired in and pass everything through until Phase 5. One decision cycle can restart from a recorded book (SPEC 12.3). A scripted toy strategy reproduces a result computed by hand to the cent on OKX and Alpaca costs. The Phase 3 class Trading.Strategies becomes StrategyNames so the Anubis.Strategies namespace can exist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6d3ef8e7b5
commit
d97304d7b9
19 files changed
+1592
-78
No files matched your search
@@ -136,7 +136,7 @@ internal sealed record AccountsView(
|
||||
var (pending, others, alpacaStops) = PendingRows(orders.Where(o => shown.Contains(o.Account)).ToList(), byId, instruments.ToDictionary(i => i.Key, i => i.Value.Symbol),
|
||||
positions, market.Open, market.Next, clock.UtcNow, zone);
|
||||
|
||||
var slices = Strategies.Base.Select(b => new StrategySlice(Strategies.Label(b.Name, withMarket: true), "var(--s-" + b.Name.Replace('_', '-') + ")",
|
||||
var slices = StrategyNames.Base.Select(b => new StrategySlice(StrategyNames.Label(b.Name, withMarket: true), "var(--s-" + b.Name.Replace('_', '-') + ")",
|
||||
rows.Where(r => r.Row.Strategy == b.Name).Sum(r => r.Row.ValueEur))).ToList();
|
||||
decimal? fxEffect = null;
|
||||
if (cards.Count > 0)
|
||||
|
||||
@@ -221,7 +221,7 @@ else
|
||||
<tr>
|
||||
<th scope="row"><strong>@p.Symbol</strong> <span class="muted">@p.Name</span></th>
|
||||
<td class="wide">@(p.Broker == Venues.Alpaca ? "Alpaca" : "OKX")</td>
|
||||
<td class="nowrap wide"><span class="swatch round" style="background: var(--s-@p.Strategy.Replace('_', '-'))"></span>@Strategies.Label(p.Strategy)</td>
|
||||
<td class="nowrap wide"><span class="swatch round" style="background: var(--s-@p.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(p.Strategy)</td>
|
||||
<td class="num wide">@Format.Quantity(p.Quantity)</td>
|
||||
<td class="num wide">@Format.Money(p.Average, p.Currency)</td>
|
||||
<td class="num wide">@Format.Money(p.Last, p.Currency)</td>
|
||||
|
||||
@@ -118,7 +118,7 @@
|
||||
<ul class="plain">
|
||||
@foreach (var s in b.Strategies)
|
||||
{
|
||||
<li>@Strategies.Label(s.Strategy, withMarket: true): quota @Format.Percent(s.Share * 100m, 0), capitale @Format.Money(s.Capital, s.Currency), liquidità @Format.Money(s.Cash, s.Currency)</li>
|
||||
<li>@StrategyNames.Label(s.Strategy, withMarket: true): quota @Format.Percent(s.Share * 100m, 0), capitale @Format.Money(s.Capital, s.Currency), liquidità @Format.Money(s.Cash, s.Currency)</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Backtest;
|
||||
|
||||
/// <summary>A fill of the backtest: quantity received or given, cash moved and fee, all in the dataset currency.</summary>
|
||||
public sealed record CostedFill(decimal Quantity, decimal Price, decimal Gross, decimal CashFee, decimal CoinFee, decimal CashDelta)
|
||||
{
|
||||
/// <summary>Every fee valued in the dataset currency: cash fees plus the coin kept by the venue at the fill price.</summary>
|
||||
public decimal FeeValue => CashFee + DbValues.Money(CoinFee * Price);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The costs of SPEC 12.1 for a market order: the same price lists and slippage tiers as the internal simulator
|
||||
/// (SPEC 7.3, ADR 0009 point 5), rounded the cautious way. <see cref="Multiplier"/> scales fees and slippage
|
||||
/// together, for the runs at double and triple costs of SPEC 12.2, step 3.
|
||||
/// </summary>
|
||||
public sealed record CostModel(decimal Multiplier = 1m)
|
||||
{
|
||||
public static CostModel Standard { get; } = new();
|
||||
|
||||
/// <summary>The price list of the venue where the instrument would trade. Research archives trade like OKX.</summary>
|
||||
public static PaperOptions PriceList(InstrumentSpec spec)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
return spec.Venue == Venues.Alpaca ? PaperOptions.Alpaca() : PaperOptions.Okx(spec.QuoteCurrency);
|
||||
}
|
||||
|
||||
public decimal SlippageRate(InstrumentSpec spec) => PaperBroker.SlippageBp(spec) / 10_000m * Multiplier;
|
||||
|
||||
/// <summary>The price paid or received: the reference moved by the slippage, rounded to the tick against us.</summary>
|
||||
public decimal ExecutionPrice(InstrumentSpec spec, OrderSide side, decimal reference)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
var slip = SlippageRate(spec);
|
||||
var price = side == OrderSide.Buy ? reference * (1m + slip) : reference * (1m - slip);
|
||||
var tick = OrderRules.TickOf(spec, price);
|
||||
price = tick is > 0m ? (side == OrderSide.Buy ? OrderRules.RoundUp(price, tick.Value) : OrderRules.RoundDown(price, tick.Value)) : price;
|
||||
return DbValues.Money(price);
|
||||
}
|
||||
|
||||
/// <summary>The cost of a market order of <paramref name="quantity"/> at <paramref name="price"/>, as the venue would charge it.</summary>
|
||||
public CostedFill Fill(InstrumentSpec spec, OrderSide side, decimal quantity, decimal price)
|
||||
{
|
||||
var list = PriceList(spec);
|
||||
var taker = list.TakerFee * Multiplier;
|
||||
var gross = DbValues.Money(quantity * price);
|
||||
var share = list.ShareFee > 0m ? OrderRules.RoundUp(quantity * list.ShareFee * Multiplier, 0.01m) : 0m;
|
||||
if (side == OrderSide.Buy)
|
||||
{
|
||||
if (list.FeeInKind)
|
||||
{
|
||||
var coin = DbValues.Money(quantity * taker);
|
||||
return new CostedFill(quantity - coin, price, gross, 0m, coin, -gross);
|
||||
}
|
||||
|
||||
var fee = DbValues.Money(gross * taker) + share;
|
||||
return new CostedFill(quantity, price, gross, fee, 0m, -(gross + fee));
|
||||
}
|
||||
|
||||
var sellFee = DbValues.Money(gross * taker) + share
|
||||
+ (list.SellValueFee > 0m ? OrderRules.RoundUp(gross * list.SellValueFee * Multiplier, 0.01m) : 0m);
|
||||
return new CostedFill(quantity, price, gross, sellFee, 0m, gross - sellFee);
|
||||
}
|
||||
|
||||
/// <summary>The largest quantity whose purchase, fees included, fits in <paramref name="cash"/>: no leverage (SPEC 9.1).</summary>
|
||||
public decimal Affordable(InstrumentSpec spec, decimal cash, decimal price)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
if (cash <= 0m || price <= 0m)
|
||||
{
|
||||
return 0m;
|
||||
}
|
||||
|
||||
var list = PriceList(spec);
|
||||
var perUnit = price * (1m + (list.FeeInKind ? 0m : list.TakerFee * Multiplier)) + (list.ShareFee * Multiplier);
|
||||
var lot = OrderRules.LotOf(spec);
|
||||
var quantity = OrderRules.RoundDown(cash / perUnit, lot);
|
||||
// Fees rounded up to the cent can push the total a little past the cash: step back by the excess.
|
||||
for (var guard = 0; guard < 8 && quantity > 0m; guard++)
|
||||
{
|
||||
var excess = -Fill(spec, OrderSide.Buy, quantity, price).CashDelta - cash;
|
||||
if (excess <= 0m)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
quantity = OrderRules.RoundDown(quantity - (excess / perUnit) - lot, lot);
|
||||
}
|
||||
|
||||
return Math.Max(quantity, 0m);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Anubis.Data;
|
||||
using Anubis.Strategies;
|
||||
|
||||
namespace Anubis.Backtest;
|
||||
|
||||
/// <summary>
|
||||
/// One instrument of a backtest: its rules, its real daily bars (oldest first, one per day) and its corporate
|
||||
/// actions. Signals read the bars adjusted and anchored to the decision day; executions use the real prices.
|
||||
/// </summary>
|
||||
public sealed class BacktestInstrument
|
||||
{
|
||||
private readonly Dictionary<DateOnly, int> _index;
|
||||
|
||||
public BacktestInstrument(InstrumentSpec spec, IReadOnlyList<DailyBar> bars, IReadOnlyList<CorporateAction>? actions = null, string source = "")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
ArgumentNullException.ThrowIfNull(bars);
|
||||
Spec = spec;
|
||||
Bars = [.. bars.OrderBy(b => b.Day)];
|
||||
Actions = [.. (actions ?? []).Where(a => a.Symbol == spec.Symbol).OrderBy(a => a.ExDate)];
|
||||
Source = source;
|
||||
_index = new Dictionary<DateOnly, int>(Bars.Count);
|
||||
for (var i = 0; i < Bars.Count; i++)
|
||||
{
|
||||
if (!_index.TryAdd(Bars[i].Day, i))
|
||||
{
|
||||
throw new ArgumentException("Two bars on the same day for " + spec.Symbol, nameof(bars));
|
||||
}
|
||||
}
|
||||
|
||||
// Cumulative price factor of every bar: the product of the factors of the actions that come after it. A bar
|
||||
// anchored to day A is the real bar times Factors[i] / Factors[A] (SPEC 6.10).
|
||||
Factors = new double[Bars.Count];
|
||||
var running = 1d;
|
||||
var next = Actions.Count - 1;
|
||||
while (next >= 0 && Bars.Count > 0 && Actions[next].ExDate > Bars[^1].Day)
|
||||
{
|
||||
next--;
|
||||
}
|
||||
|
||||
for (var i = Bars.Count - 1; i >= 0; i--)
|
||||
{
|
||||
Factors[i] = running;
|
||||
while (next >= 0 && Actions[next].ExDate > (i > 0 ? Bars[i - 1].Day : DateOnly.MinValue) && Actions[next].ExDate <= Bars[i].Day)
|
||||
{
|
||||
running *= Adjustments.PriceFactor(Actions[next], i > 0 ? Bars[i - 1].Close : null);
|
||||
next--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public InstrumentSpec Spec { get; }
|
||||
|
||||
public string Symbol => Spec.Symbol;
|
||||
|
||||
public IReadOnlyList<DailyBar> Bars { get; }
|
||||
|
||||
public IReadOnlyList<CorporateAction> Actions { get; }
|
||||
|
||||
/// <summary>Where the bars come from, in words for the report.</summary>
|
||||
public string Source { get; }
|
||||
|
||||
internal double[] Factors { get; }
|
||||
|
||||
public int IndexOf(DateOnly day) => _index.TryGetValue(day, out var i) ? i : -1;
|
||||
|
||||
/// <summary>Number of bars up to and including <paramref name="day"/>.</summary>
|
||||
public int CountThrough(DateOnly day)
|
||||
{
|
||||
var lo = 0;
|
||||
var hi = Bars.Count;
|
||||
while (lo < hi)
|
||||
{
|
||||
var mid = (lo + hi) / 2;
|
||||
if (Bars[mid].Day <= day)
|
||||
{
|
||||
lo = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
|
||||
return lo;
|
||||
}
|
||||
|
||||
public BarSeries SeriesThrough(DateOnly day) => new(Bars, Factors, CountThrough(day));
|
||||
|
||||
internal BacktestInstrument Through(DateOnly day) =>
|
||||
new(Spec, [.. Bars.Where(b => b.Day <= day)], [.. Actions.Where(a => a.ExDate <= day)], Source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The data of a backtest: instruments in one currency, and the sessions (every day with at least one bar). Built
|
||||
/// once and never changed, so the same dataset and parameters always give the same result (SPEC 12.1).
|
||||
/// </summary>
|
||||
public sealed class BacktestDataset
|
||||
{
|
||||
private readonly Dictionary<string, BacktestInstrument> _bySymbol;
|
||||
|
||||
public BacktestDataset(IEnumerable<BacktestInstrument> instruments, string currency)
|
||||
{
|
||||
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);
|
||||
if (wrong is not null)
|
||||
{
|
||||
throw new ArgumentException($"{wrong.Symbol} is in {wrong.Spec.QuoteCurrency}, the backtest is in {currency}", nameof(instruments));
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<BacktestInstrument> Instruments { 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>Sessions in a year, to annualise: crypto trades every day, stocks about 252 days.</summary>
|
||||
public int PeriodsPerYear => IsCrypto ? 365 : 252;
|
||||
|
||||
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);
|
||||
|
||||
/// <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);
|
||||
|
||||
/// <summary>
|
||||
/// A SHA-256 of every bar, action and rule used: two reports with the same fingerprint and the same plan were
|
||||
/// computed on exactly the same data.
|
||||
/// </summary>
|
||||
public string Fingerprint()
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
text.Append(Currency).Append('\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");
|
||||
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");
|
||||
}
|
||||
|
||||
foreach (var a in i.Actions)
|
||||
{
|
||||
text.Append(CultureInfo.InvariantCulture, $"{a.Kind},{a.ExDate:yyyy-MM-dd},{a.Ratio},{a.CashAmount}\n");
|
||||
}
|
||||
}
|
||||
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
|
||||
}
|
||||
|
||||
/// <summary>When a session opens and closes: crypto at midnight UTC (trap 23), stocks 09:30–16:00 in New York.</summary>
|
||||
public (DateTimeOffset Opens, DateTimeOffset Closes) SessionTimes(DateOnly day)
|
||||
{
|
||||
if (IsCrypto)
|
||||
{
|
||||
var open = new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
|
||||
return (open, open.AddDays(1));
|
||||
}
|
||||
|
||||
return (NewYork(day, new TimeOnly(9, 30)), NewYork(day, new TimeOnly(16, 0)));
|
||||
}
|
||||
|
||||
private static readonly TimeZoneInfo NewYorkZone = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
|
||||
|
||||
private static DateTimeOffset NewYork(DateOnly day, TimeOnly time)
|
||||
{
|
||||
var local = day.ToDateTime(time);
|
||||
return new DateTimeOffset(local, NewYorkZone.GetUtcOffset(local)).ToUniversalTime();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Strategies;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Backtest;
|
||||
|
||||
/// <summary>How a backtest runs (SPEC 12.1).</summary>
|
||||
public sealed record BacktestOptions
|
||||
{
|
||||
public decimal InitialCapital { get; init; } = 10_000m;
|
||||
|
||||
public CostModel Costs { get; init; } = CostModel.Standard;
|
||||
|
||||
/// <summary>First and last session simulated; null means the whole dataset.</summary>
|
||||
public DateOnly? From { get; init; }
|
||||
|
||||
public DateOnly? To { get; init; }
|
||||
|
||||
/// <summary>The correctives of SPEC 8.5. Until Phase 5 they let everything through.</summary>
|
||||
public IReadOnlyList<IIntentStage> Correctives { get; init; } = [PassThroughStage.Correctives];
|
||||
|
||||
/// <summary>The risk engine of SPEC 9. Until Phase 5 it lets everything through.</summary>
|
||||
public IIntentStage Risk { get; init; } = PassThroughStage.Risk;
|
||||
}
|
||||
|
||||
/// <summary>A book to start from: a state recorded live, for the one-step comparison of SPEC 12.3.</summary>
|
||||
public sealed record PortfolioState(decimal Cash, IReadOnlyDictionary<string, Holding> Holdings)
|
||||
{
|
||||
public static PortfolioState OnlyCash(decimal cash) => new(cash, new Dictionary<string, Holding>());
|
||||
}
|
||||
|
||||
public sealed record EquityPoint(DateOnly Day, decimal Equity, decimal Cash, decimal Invested);
|
||||
|
||||
/// <summary>An execution. <see cref="Fee"/> is every fee valued in the dataset currency.</summary>
|
||||
public sealed record BacktestFill(DateOnly Day, string Symbol, OrderSide Side, decimal Quantity, decimal Price, decimal Gross, decimal Fee, string Reason);
|
||||
|
||||
/// <summary>An operation from zero to zero (SPEC 7.5). <see cref="Result"/> is net of every cost; an open one is valued at the last close.</summary>
|
||||
public sealed record BacktestTrade(string Symbol, DateOnly Opened, DateOnly? Closed, decimal Invested, decimal Result, decimal Fees)
|
||||
{
|
||||
public bool IsClosed => Closed is not null;
|
||||
}
|
||||
|
||||
/// <summary>What the strategy proposed on a day, and what was left after correctives and risk.</summary>
|
||||
public sealed record DecisionRecord(DateOnly Day, IReadOnlyList<Intent> Proposed, IReadOnlyList<Intent> Final);
|
||||
|
||||
/// <summary>Something the engine did not do as asked, and why: an order below the minimum, no cash, no price.</summary>
|
||||
public sealed record BacktestNote(DateOnly Day, string Symbol, string Reason);
|
||||
|
||||
/// <summary>The outcome of one run of one strategy on one dataset.</summary>
|
||||
public sealed record BacktestRun(
|
||||
string Currency,
|
||||
decimal InitialCapital,
|
||||
IReadOnlyList<EquityPoint> Equity,
|
||||
IReadOnlyList<BacktestFill> Fills,
|
||||
IReadOnlyList<BacktestTrade> Trades,
|
||||
IReadOnlyList<DecisionRecord> Decisions,
|
||||
IReadOnlyList<BacktestNote> Notes)
|
||||
{
|
||||
public decimal FinalEquity => Equity.Count > 0 ? Equity[^1].Equity : InitialCapital;
|
||||
|
||||
public decimal NetResult => FinalEquity - InitialCapital;
|
||||
|
||||
public decimal Fees => Fills.Sum(f => f.Fee);
|
||||
|
||||
public decimal Dividends { get; init; }
|
||||
|
||||
/// <summary>Value of the leftovers below the minimum written off after an exit (SPEC 7.2).</summary>
|
||||
public decimal WrittenOff { get; init; }
|
||||
|
||||
/// <summary>Daily returns of the equity, one per session after the first.</summary>
|
||||
public double[] DailyReturns()
|
||||
{
|
||||
var result = new double[Math.Max(Equity.Count - 1, 0)];
|
||||
for (var i = 1; i < Equity.Count; i++)
|
||||
{
|
||||
var before = Equity[i - 1].Equity;
|
||||
result[i - 1] = before > 0m ? (double)(Equity[i].Equity / before) - 1d : 0d;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reasons the engine writes in fills and notes.</summary>
|
||||
public static class BacktestReasons
|
||||
{
|
||||
public const string Stop = "stop";
|
||||
public const string StopGap = "stop_gap";
|
||||
public const string WrittenOff = "residue_written_off";
|
||||
public const string NoCash = "no_cash";
|
||||
public const string NoPrice = "no_price";
|
||||
public const string UnknownSymbol = "unknown_symbol";
|
||||
public const string NoShortSelling = "no_short_selling";
|
||||
public const string Dividend = "dividend";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The event-driven backtest engine (SPEC 12.1). Each session is a sequence of events in time order: corporate
|
||||
/// actions before the open, the open (stops that open below their level, then the orders decided at the previous
|
||||
/// close, sales first), the session (stops touched by the low), the close (valuation and decision). A decision sees
|
||||
/// the data up to its close and its orders go at the next open: the delay between deciding and executing. The same
|
||||
/// <see cref="IStrategy"/> classes run live: the strategy cannot tell the difference.
|
||||
/// </summary>
|
||||
public static class BacktestEngine
|
||||
{
|
||||
public static BacktestRun Run(IStrategy strategy, BacktestDataset data, BacktestOptions? options = null, PortfolioState? start = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(strategy);
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
options ??= new BacktestOptions();
|
||||
CheckSchedule(strategy);
|
||||
var simulation = new Simulation(strategy, data, options, start ?? PortfolioState.OnlyCash(options.InitialCapital));
|
||||
// Ordered by time, then by day: a crypto close and the next open fall on the same midnight, and the close of
|
||||
// the earlier day comes first.
|
||||
var events = new PriorityQueue<(SessionEvent Kind, DateOnly Day), (DateTimeOffset At, int Day, int Order)>();
|
||||
foreach (var day in data.Sessions.Where(d => (options.From is null || d >= options.From) && (options.To is null || d <= options.To)))
|
||||
{
|
||||
var (opens, closes) = data.SessionTimes(day);
|
||||
events.Enqueue((SessionEvent.CorporateActions, day), (opens, day.DayNumber, 0));
|
||||
events.Enqueue((SessionEvent.Open, day), (opens, day.DayNumber, 1));
|
||||
events.Enqueue((SessionEvent.Session, day), (opens, day.DayNumber, 2));
|
||||
events.Enqueue((SessionEvent.Close, day), (closes, day.DayNumber, 3));
|
||||
}
|
||||
|
||||
while (events.TryDequeue(out var e, out var when))
|
||||
{
|
||||
switch (e.Kind)
|
||||
{
|
||||
case SessionEvent.CorporateActions:
|
||||
simulation.CorporateActions(e.Day);
|
||||
break;
|
||||
case SessionEvent.Open:
|
||||
simulation.Open(e.Day);
|
||||
break;
|
||||
case SessionEvent.Session:
|
||||
simulation.Session(e.Day);
|
||||
break;
|
||||
default:
|
||||
simulation.Close(e.Day, when.At);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return simulation.Finish();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One decision cycle from a recorded book (SPEC 12.1, 12.3): the strategy decides on the close of
|
||||
/// <paramref name="day"/> with the data known then and the book given, and nothing else runs.
|
||||
/// </summary>
|
||||
public static DecisionRecord DecideOnce(IStrategy strategy, BacktestDataset data, PortfolioState state, DateOnly day, BacktestOptions? options = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(strategy);
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
CheckSchedule(strategy);
|
||||
var simulation = new Simulation(strategy, data.Through(day), options ?? new BacktestOptions(), state);
|
||||
simulation.MarkThrough(day);
|
||||
return simulation.Decide(day, data.SessionTimes(day).Closes);
|
||||
}
|
||||
|
||||
private static void CheckSchedule(IStrategy strategy)
|
||||
{
|
||||
if (strategy.Schedule().Any(t => t.Anchor != DecisionAnchor.Close))
|
||||
{
|
||||
throw new NotSupportedException($"{strategy.Id}: the daily backtest decides only on the close of a session");
|
||||
}
|
||||
}
|
||||
|
||||
private enum SessionEvent
|
||||
{
|
||||
CorporateActions,
|
||||
Open,
|
||||
Session,
|
||||
Close,
|
||||
}
|
||||
|
||||
private sealed class Position
|
||||
{
|
||||
public decimal Quantity { get; set; }
|
||||
|
||||
public decimal AveragePrice { get; set; }
|
||||
|
||||
public decimal? Stop { get; set; }
|
||||
|
||||
public DateOnly EnteredOn { get; init; }
|
||||
|
||||
public required OpenTrade Trade { get; init; }
|
||||
}
|
||||
|
||||
private sealed class OpenTrade
|
||||
{
|
||||
public DateOnly Opened { get; init; }
|
||||
|
||||
public decimal Bought { get; set; }
|
||||
|
||||
public decimal CashFlow { get; set; }
|
||||
|
||||
public decimal Fees { get; set; }
|
||||
}
|
||||
|
||||
private sealed record Pending(string Symbol, OrderSide Side, decimal Quantity, bool Exit, decimal? Stop, string Reason);
|
||||
|
||||
private sealed class Simulation
|
||||
{
|
||||
private readonly IStrategy _strategy;
|
||||
private readonly BacktestDataset _data;
|
||||
private readonly BacktestOptions _options;
|
||||
private readonly CostModel _costs;
|
||||
private readonly SortedDictionary<string, Position> _positions = new(StringComparer.Ordinal);
|
||||
private readonly SortedDictionary<string, Pending> _pending = new(StringComparer.Ordinal);
|
||||
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<BacktestFill> _fills = [];
|
||||
private readonly List<BacktestTrade> _trades = [];
|
||||
private readonly List<DecisionRecord> _decisions = [];
|
||||
private readonly List<BacktestNote> _notes = [];
|
||||
private readonly decimal _initial;
|
||||
private decimal _cash;
|
||||
private decimal _dividends;
|
||||
private decimal _writtenOff;
|
||||
|
||||
public Simulation(IStrategy strategy, BacktestDataset data, BacktestOptions options, PortfolioState start)
|
||||
{
|
||||
_strategy = strategy;
|
||||
_data = data;
|
||||
_options = options;
|
||||
_costs = options.Costs;
|
||||
_cash = start.Cash;
|
||||
var first = data.Sessions.FirstOrDefault(d => options.From is null || d >= options.From);
|
||||
foreach (var (symbol, h) in start.Holdings.Where(h => h.Value.Quantity > 0m))
|
||||
{
|
||||
var trade = new OpenTrade { Opened = h.EnteredOn, Bought = DbValues.Money(h.Quantity * h.AveragePrice), CashFlow = -DbValues.Money(h.Quantity * h.AveragePrice) };
|
||||
_positions[symbol] = new Position { Quantity = h.Quantity, AveragePrice = h.AveragePrice, Stop = h.Stop, EnteredOn = h.EnteredOn, Trade = trade };
|
||||
_lastClose[symbol] = h.AveragePrice;
|
||||
}
|
||||
|
||||
_initial = start.Cash + _positions.Values.Sum(p => p.Trade.Bought);
|
||||
foreach (var i in data.Instruments)
|
||||
{
|
||||
_actionsDoneThrough[i.Symbol] = first == default ? DateOnly.MinValue : first.AddDays(-1);
|
||||
}
|
||||
}
|
||||
|
||||
public void MarkThrough(DateOnly day)
|
||||
{
|
||||
foreach (var i in _data.Instruments)
|
||||
{
|
||||
var n = i.CountThrough(day);
|
||||
if (n > 0)
|
||||
{
|
||||
_lastClose[i.Symbol] = Price(i.Bars[n - 1].Close);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void CorporateActions(DateOnly day)
|
||||
{
|
||||
foreach (var i in _data.Instruments)
|
||||
{
|
||||
var done = _actionsDoneThrough[i.Symbol];
|
||||
foreach (var action in i.Actions.Where(a => a.ExDate > done && a.ExDate <= day))
|
||||
{
|
||||
Apply(i, action);
|
||||
}
|
||||
|
||||
_actionsDoneThrough[i.Symbol] = day;
|
||||
}
|
||||
}
|
||||
|
||||
private void Apply(BacktestInstrument instrument, CorporateAction action)
|
||||
{
|
||||
var symbol = instrument.Symbol;
|
||||
if (action.ChangesShares)
|
||||
{
|
||||
if (_positions.TryGetValue(symbol, out var p))
|
||||
{
|
||||
p.Quantity = Adjustments.ConvertQuantity(p.Quantity, action);
|
||||
p.AveragePrice = DbValues.Money(Adjustments.ConvertLevel(p.AveragePrice, action, null));
|
||||
p.Stop = p.Stop is { } s ? DbValues.Money(Adjustments.ConvertLevel(s, action, null)) : null;
|
||||
}
|
||||
|
||||
if (_pending.TryGetValue(symbol, out var order))
|
||||
{
|
||||
_pending[symbol] = order with
|
||||
{
|
||||
Quantity = Adjustments.ConvertQuantity(order.Quantity, action),
|
||||
Stop = order.Stop is { } s ? DbValues.Money(Adjustments.ConvertLevel(s, action, null)) : null,
|
||||
};
|
||||
}
|
||||
|
||||
if (_lastClose.TryGetValue(symbol, out var close))
|
||||
{
|
||||
_lastClose[symbol] = DbValues.Money(Adjustments.ConvertLevel(close, action, null));
|
||||
}
|
||||
}
|
||||
else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m && _positions.TryGetValue(symbol, out var held)
|
||||
&& (action.Currency is null || action.Currency == _data.Currency))
|
||||
{
|
||||
// To whoever held the shares at the close before the ex-date: that is the book now, before the open.
|
||||
var amount = DbValues.Money(held.Quantity * action.CashAmount.Value);
|
||||
_cash += amount;
|
||||
_dividends += amount;
|
||||
held.Trade.CashFlow += amount;
|
||||
}
|
||||
}
|
||||
|
||||
public void Open(DateOnly day)
|
||||
{
|
||||
// Stops resting on the broker fill first when the price opens below them (SPEC 7.2, trap 24).
|
||||
foreach (var (symbol, p) in _positions.ToList())
|
||||
{
|
||||
if (Bar(symbol, day) is { } bar && p.Stop is { } stop && Price(bar.Open) <= stop)
|
||||
{
|
||||
Sell(day, symbol, p.Quantity, Price(bar.Open), BacktestReasons.StopGap, exit: true);
|
||||
_pending.Remove(symbol);
|
||||
}
|
||||
}
|
||||
|
||||
var due = _pending.Values.Where(o => Bar(o.Symbol, day) is not null).OrderBy(o => o.Side == OrderSide.Buy).ToList();
|
||||
foreach (var order in due)
|
||||
{
|
||||
_pending.Remove(order.Symbol);
|
||||
var open = Price(Bar(order.Symbol, day)!.Open);
|
||||
if (order.Side == OrderSide.Sell)
|
||||
{
|
||||
if (_positions.TryGetValue(order.Symbol, out var p))
|
||||
{
|
||||
Sell(day, order.Symbol, order.Exit ? p.Quantity : Math.Min(order.Quantity, p.Quantity), open, order.Reason, order.Exit);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Buy(day, order, open);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Session(DateOnly day)
|
||||
{
|
||||
foreach (var (symbol, p) in _positions.ToList())
|
||||
{
|
||||
if (Bar(symbol, day) is { } bar && p.Stop is { } stop && Price(bar.Low) <= stop)
|
||||
{
|
||||
Sell(day, symbol, p.Quantity, Math.Min(stop, Price(bar.Open)), BacktestReasons.Stop, exit: true);
|
||||
_pending.Remove(symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Close(DateOnly day, DateTimeOffset at)
|
||||
{
|
||||
MarkOn(day);
|
||||
var invested = Invested();
|
||||
_equity.Add(new EquityPoint(day, _cash + invested, _cash, invested));
|
||||
var record = Decide(day, at);
|
||||
_decisions.Add(record);
|
||||
Plan(day, record.Final);
|
||||
}
|
||||
|
||||
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 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 proposed = _strategy.Decide(context);
|
||||
var final = proposed;
|
||||
foreach (var stage in _options.Correctives)
|
||||
{
|
||||
final = stage.Apply(context, final);
|
||||
}
|
||||
|
||||
final = _options.Risk.Apply(context, final);
|
||||
return new DecisionRecord(day, proposed, final);
|
||||
}
|
||||
|
||||
/// <summary>Turns the intents of a close into orders for the next open, sized on the equity of that close.</summary>
|
||||
private void Plan(DateOnly day, IReadOnlyList<Intent> intents)
|
||||
{
|
||||
var equity = _cash + Invested();
|
||||
foreach (var intent in intents.GroupBy(i => i.Symbol, StringComparer.Ordinal).Select(g => g.Last()))
|
||||
{
|
||||
var instrument = _data[intent.Symbol];
|
||||
if (instrument is null)
|
||||
{
|
||||
_notes.Add(new BacktestNote(day, intent.Symbol, BacktestReasons.UnknownSymbol));
|
||||
continue;
|
||||
}
|
||||
|
||||
_positions.TryGetValue(intent.Symbol, out var p);
|
||||
var stop = intent.Stop is { } level ? OrderRules.StopPrice(level, OrderRules.TickOf(instrument.Spec, level)) : (decimal?)null;
|
||||
if (p is not null && stop is not null)
|
||||
{
|
||||
p.Stop = stop;
|
||||
}
|
||||
|
||||
if (intent.TargetWeight is not { } weight)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (weight < 0m)
|
||||
{
|
||||
_notes.Add(new BacktestNote(day, intent.Symbol, BacktestReasons.NoShortSelling));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!_lastClose.TryGetValue(intent.Symbol, out var close) || close <= 0m)
|
||||
{
|
||||
_notes.Add(new BacktestNote(day, intent.Symbol, BacktestReasons.NoPrice));
|
||||
continue;
|
||||
}
|
||||
|
||||
var current = p?.Quantity ?? 0m;
|
||||
if (weight == 0m)
|
||||
{
|
||||
if (current > 0m)
|
||||
{
|
||||
_pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Sell, current, Exit: true, null, intent.Reason);
|
||||
}
|
||||
else
|
||||
{
|
||||
_pending.Remove(intent.Symbol);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var target = weight * equity / close;
|
||||
var difference = target - current;
|
||||
if (difference > 0m)
|
||||
{
|
||||
_pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Buy, difference, Exit: false, stop, intent.Reason);
|
||||
}
|
||||
else if (difference < 0m)
|
||||
{
|
||||
_pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Sell, -difference, Exit: false, null, intent.Reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Buy(DateOnly day, Pending order, decimal reference)
|
||||
{
|
||||
var spec = _data[order.Symbol]!.Spec;
|
||||
var price = _costs.ExecutionPrice(spec, OrderSide.Buy, reference);
|
||||
var quantity = Math.Min(order.Quantity, _costs.Affordable(spec, _cash, price));
|
||||
if (quantity < order.Quantity)
|
||||
{
|
||||
// Less cash than the decision assumed (the open moved): the purchase shrinks, never borrows (SPEC 9.1).
|
||||
_notes.Add(new BacktestNote(day, order.Symbol, BacktestReasons.NoCash));
|
||||
}
|
||||
|
||||
var rounded = OrderRules.Round(spec, OrderSide.Buy, OrderKind.Market, quantity, price);
|
||||
if (!rounded.IsValid)
|
||||
{
|
||||
if (quantity >= order.Quantity)
|
||||
{
|
||||
_notes.Add(new BacktestNote(day, order.Symbol, rounded.Rejection!));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var fill = _costs.Fill(spec, OrderSide.Buy, rounded.Quantity, price);
|
||||
_cash += fill.CashDelta;
|
||||
if (!_positions.TryGetValue(order.Symbol, out var p))
|
||||
{
|
||||
p = new Position { EnteredOn = day, Trade = new OpenTrade { Opened = day } };
|
||||
_positions[order.Symbol] = p;
|
||||
}
|
||||
|
||||
p.AveragePrice = DbValues.Money(((p.Quantity * p.AveragePrice) + fill.Gross) / (p.Quantity + fill.Quantity));
|
||||
p.Quantity += fill.Quantity;
|
||||
p.Stop = order.Stop ?? p.Stop;
|
||||
p.Trade.Bought += fill.Gross;
|
||||
p.Trade.CashFlow += fill.CashDelta;
|
||||
p.Trade.Fees += fill.FeeValue;
|
||||
_fills.Add(new BacktestFill(day, order.Symbol, OrderSide.Buy, rounded.Quantity, price, fill.Gross, fill.FeeValue, order.Reason));
|
||||
}
|
||||
|
||||
private void Sell(DateOnly day, string symbol, decimal quantity, decimal reference, string reason, bool exit)
|
||||
{
|
||||
var p = _positions[symbol];
|
||||
var spec = _data[symbol]!.Spec;
|
||||
var price = _costs.ExecutionPrice(spec, OrderSide.Sell, reference);
|
||||
var rounded = OrderRules.Round(spec, OrderSide.Sell, OrderKind.Market, Math.Min(quantity, p.Quantity), price);
|
||||
if (rounded.IsValid)
|
||||
{
|
||||
var fill = _costs.Fill(spec, OrderSide.Sell, rounded.Quantity, price);
|
||||
_cash += fill.CashDelta;
|
||||
p.Quantity -= rounded.Quantity;
|
||||
p.Trade.CashFlow += fill.CashDelta;
|
||||
p.Trade.Fees += fill.FeeValue;
|
||||
_fills.Add(new BacktestFill(day, symbol, OrderSide.Sell, rounded.Quantity, price, fill.Gross, fill.FeeValue, reason));
|
||||
}
|
||||
else if (!exit)
|
||||
{
|
||||
_notes.Add(new BacktestNote(day, symbol, rounded.Rejection!));
|
||||
return;
|
||||
}
|
||||
|
||||
// After an exit, what is below the minimum cannot be sold on its own: it is written off (SPEC 7.2).
|
||||
if (p.Quantity > 0m && (exit || OrderRules.IsUnsellable(spec, p.Quantity, price)))
|
||||
{
|
||||
_writtenOff += DbValues.Money(p.Quantity * price);
|
||||
_notes.Add(new BacktestNote(day, symbol, BacktestReasons.WrittenOff));
|
||||
p.Quantity = 0m;
|
||||
}
|
||||
|
||||
if (p.Quantity <= 0m)
|
||||
{
|
||||
_positions.Remove(symbol);
|
||||
_trades.Add(new BacktestTrade(symbol, p.Trade.Opened, day, p.Trade.Bought, p.Trade.CashFlow, p.Trade.Fees));
|
||||
}
|
||||
}
|
||||
|
||||
public BacktestRun Finish()
|
||||
{
|
||||
foreach (var (symbol, p) in _positions)
|
||||
{
|
||||
var value = DbValues.Money(p.Quantity * _lastClose.GetValueOrDefault(symbol));
|
||||
_trades.Add(new BacktestTrade(symbol, p.Trade.Opened, null, p.Trade.Bought, p.Trade.CashFlow + value, p.Trade.Fees));
|
||||
}
|
||||
|
||||
return new BacktestRun(_data.Currency, _initial, _equity, _fills, [.. _trades.OrderBy(t => t.Opened).ThenBy(t => t.Symbol, StringComparer.Ordinal)], _decisions, _notes)
|
||||
{
|
||||
Dividends = _dividends,
|
||||
WrittenOff = _writtenOff,
|
||||
};
|
||||
}
|
||||
|
||||
private void MarkOn(DateOnly day)
|
||||
{
|
||||
foreach (var i in _data.Instruments)
|
||||
{
|
||||
if (Bar(i.Symbol, day) is { } bar)
|
||||
{
|
||||
_lastClose[i.Symbol] = Price(bar.Close);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private decimal Invested() => _positions.Sum(p => DbValues.Money(p.Value.Quantity * _lastClose.GetValueOrDefault(p.Key)));
|
||||
|
||||
private DailyBar? Bar(string symbol, DateOnly day)
|
||||
{
|
||||
var instrument = _data[symbol];
|
||||
var index = instrument?.IndexOf(day) ?? -1;
|
||||
return index >= 0 ? instrument!.Bars[index] : null;
|
||||
}
|
||||
|
||||
/// <summary>Bars are analysis data in floating point; prices used for money become decimal here, once.</summary>
|
||||
private static decimal Price(double value) => DbValues.Money((decimal)value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
namespace Anubis.Strategies;
|
||||
|
||||
/// <summary>
|
||||
/// Buy at the first close in equal parts, then hold to the end: the "comprare e tenere" comparison of SPEC 12.2,
|
||||
/// step 6. It decides only from its own book, so it can restart from any recorded state.
|
||||
/// </summary>
|
||||
public sealed class BuyAndHold : IStrategy
|
||||
{
|
||||
/// <summary>A little cash stays aside for the fees, so the last purchase is not cut short.</summary>
|
||||
public const decimal Invested = 0.995m;
|
||||
|
||||
public string Id => BuyAndHoldFamily.FamilyId;
|
||||
|
||||
public string Version => "1";
|
||||
|
||||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||
|
||||
public IReadOnlyList<string> Universe(UniverseContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return context.Available;
|
||||
}
|
||||
|
||||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (context.Portfolio.Holdings.Count > 0 || context.Universe.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var weight = Invested / context.Universe.Count;
|
||||
return [.. context.Universe.Select(s => new Intent(s, weight, "buy_and_hold"))];
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class BuyAndHoldFamily : IStrategyFamily
|
||||
{
|
||||
public const string FamilyId = "buy_and_hold";
|
||||
|
||||
public static BuyAndHoldFamily Instance { get; } = new();
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => "1";
|
||||
|
||||
public string Name => "Comprare e tenere";
|
||||
|
||||
public string Description => "Compra in parti uguali alla prima chiusura e tiene fino alla fine. È il confronto di ogni rapporto: dice quanto avrebbe reso non fare nulla.";
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters => [];
|
||||
|
||||
public IStrategy Create(StrategyParameters parameters) => new BuyAndHold();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An example strategy to try the laboratory, not one of the bot's (those arrive with Phase 5): it holds an
|
||||
/// instrument while the short average of its closes is above the long one. It has no strategy code, so it can never
|
||||
/// send an order (SPEC 7.2).
|
||||
/// </summary>
|
||||
public sealed class MovingAverageCross(int fast, int slow) : IStrategy
|
||||
{
|
||||
public string Id => MovingAverageCrossFamily.FamilyId;
|
||||
|
||||
public string Version => "1";
|
||||
|
||||
public int Fast { get; } = fast;
|
||||
|
||||
public int Slow { get; } = slow;
|
||||
|
||||
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||
|
||||
public IReadOnlyList<string> Universe(UniverseContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
return context.Available;
|
||||
}
|
||||
|
||||
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var intents = new List<Intent>();
|
||||
var weight = 1m / Math.Max(context.Universe.Count, 1);
|
||||
foreach (var symbol in context.Universe)
|
||||
{
|
||||
var bars = context.Bars(symbol);
|
||||
if (bars.Count < Slow)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var closes = bars.Closes(Slow);
|
||||
var slowAverage = closes.Average();
|
||||
var fastAverage = closes[^Fast..].Average();
|
||||
var held = context.Portfolio.Holds(symbol);
|
||||
if (!held && fastAverage > slowAverage)
|
||||
{
|
||||
intents.Add(new Intent(symbol, weight, "average_cross_up"));
|
||||
}
|
||||
else if (held && fastAverage < slowAverage)
|
||||
{
|
||||
intents.Add(new Intent(symbol, 0m, "average_cross_down"));
|
||||
}
|
||||
}
|
||||
|
||||
return intents;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class MovingAverageCrossFamily : IStrategyFamily
|
||||
{
|
||||
public const string FamilyId = "sma_cross";
|
||||
|
||||
public static MovingAverageCrossFamily Instance { get; } = new();
|
||||
|
||||
public string Id => FamilyId;
|
||||
|
||||
public string Version => "1";
|
||||
|
||||
public string Name => "Incrocio di medie (esempio)";
|
||||
|
||||
public string Description => "Strategia d'esempio per provare il laboratorio, non una di quelle del bot: tiene uno strumento finché la media breve dei prezzi di chiusura sta sopra la media lunga, in parti uguali tra gli strumenti scelti. Non manda mai ordini.";
|
||||
|
||||
public IReadOnlyList<ParameterSpec> Parameters =>
|
||||
[
|
||||
new("fast", "Giorni della media breve", 20m, [10m, 20m, 30m], 2m, 200m),
|
||||
new("slow", "Giorni della media lunga", 100m, [50m, 100m, 150m], 5m, 400m),
|
||||
];
|
||||
|
||||
public bool Accepts(StrategyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
return parameters.Whole("fast") < parameters.Whole("slow");
|
||||
}
|
||||
|
||||
public IStrategy Create(StrategyParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
return new MovingAverageCross(parameters.Whole("fast"), parameters.Whole("slow"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The strategies the laboratory can test. The bot's own strategies join with Phase 5.</summary>
|
||||
public static class StrategyCatalog
|
||||
{
|
||||
public static IReadOnlyList<IStrategyFamily> All { get; } = [MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance];
|
||||
|
||||
public static IStrategyFamily? Find(string id) => All.FirstOrDefault(f => f.Id == id);
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.Strategies;
|
||||
|
||||
/// <summary>Where in the market's day a decision is taken (SPEC 5.3: decision times follow the market calendar).</summary>
|
||||
public enum DecisionAnchor
|
||||
{
|
||||
/// <summary>After the close of the session, on its finished bar. Orders go at the next open.</summary>
|
||||
Close,
|
||||
|
||||
/// <summary>A given time after the open (live engine, Phase 6). The backtest of daily bars does not support it.</summary>
|
||||
Open,
|
||||
}
|
||||
|
||||
/// <summary>When a strategy decides, expressed against the market calendar, never as a fixed clock time.</summary>
|
||||
public sealed record DecisionTime(DecisionAnchor Anchor, TimeSpan Offset)
|
||||
{
|
||||
public static DecisionTime AfterClose { get; } = new(DecisionAnchor.Close, TimeSpan.Zero);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a strategy wants for one instrument (SPEC 5.2). <see cref="TargetWeight"/> is the share of the strategy's
|
||||
/// equity to hold in the instrument after the next execution: 0 means exit. Null keeps the size and only updates the
|
||||
/// stop. <see cref="Stop"/> is a protective stop level in today's prices; null keeps the current one.
|
||||
/// </summary>
|
||||
public sealed record Intent(string Symbol, decimal? TargetWeight, string Reason)
|
||||
{
|
||||
public decimal? Stop { 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})");
|
||||
}
|
||||
|
||||
/// <summary>Kinds of intent, as the one-step comparison of SPEC 12.3 reads them.</summary>
|
||||
public enum IntentAction
|
||||
{
|
||||
Enter,
|
||||
Exit,
|
||||
Resize,
|
||||
Keep,
|
||||
}
|
||||
|
||||
/// <summary>A position as the strategy sees it: quantity, average entry price and stop in today's prices.</summary>
|
||||
public sealed record Holding(decimal Quantity, decimal AveragePrice, decimal? Stop, DateOnly EnteredOn);
|
||||
|
||||
/// <summary>The strategy's own book at the moment of the decision.</summary>
|
||||
public sealed class PortfolioView(decimal cash, decimal equity, IReadOnlyDictionary<string, Holding> holdings)
|
||||
{
|
||||
public decimal Cash { get; } = cash;
|
||||
|
||||
/// <summary>Cash plus positions at the last close.</summary>
|
||||
public decimal Equity { get; } = equity;
|
||||
|
||||
public IReadOnlyDictionary<string, Holding> Holdings { get; } = holdings;
|
||||
|
||||
public Holding? Of(string symbol) => Holdings.GetValueOrDefault(symbol);
|
||||
|
||||
public bool Holds(string symbol) => Holdings.TryGetValue(symbol, out var h) && h.Quantity > 0m;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Daily bars of one instrument up to the moment of the decision and not beyond (SPEC 5.3). Prices are adjusted
|
||||
/// for splits and dividends and anchored to the decision day, so the last bar shows the prices of today: signals
|
||||
/// read adjusted prices, orders use real ones (trap 9). Index 0 is the oldest bar, <see cref="Count"/> − 1 today's.
|
||||
/// Reading past today throws: there is no way to look ahead through this object.
|
||||
/// </summary>
|
||||
public sealed class BarSeries
|
||||
{
|
||||
private readonly IReadOnlyList<DailyBar> _bars;
|
||||
private readonly double[] _factors;
|
||||
private readonly double _anchor;
|
||||
|
||||
internal BarSeries(IReadOnlyList<DailyBar> bars, double[] factors, int count)
|
||||
{
|
||||
_bars = bars;
|
||||
_factors = factors;
|
||||
Count = count;
|
||||
_anchor = count > 0 ? factors[count - 1] : 1d;
|
||||
}
|
||||
|
||||
public static BarSeries Empty { get; } = new([], [], 0);
|
||||
|
||||
public int Count { get; }
|
||||
|
||||
public DateOnly Day(int index) => Bar(index).Day;
|
||||
|
||||
public Ohlc Prices(int index) => Bar(index).Prices.Scale(_factors[index] / _anchor);
|
||||
|
||||
public double Close(int index) => Bar(index).Close * (_factors[index] / _anchor);
|
||||
|
||||
public double High(int index) => Bar(index).High * (_factors[index] / _anchor);
|
||||
|
||||
public double Low(int index) => Bar(index).Low * (_factors[index] / _anchor);
|
||||
|
||||
public double Volume(int index) => Bar(index).Volume;
|
||||
|
||||
/// <summary>The last <paramref name="length"/> closes, oldest first (fewer when the history is shorter).</summary>
|
||||
public double[] Closes(int length)
|
||||
{
|
||||
var n = Math.Min(length, Count);
|
||||
var result = new double[n];
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
result[i] = Close(Count - n + i);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private DailyBar Bar(int index)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(index);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count);
|
||||
return _bars[index];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a strategy may read to choose its instruments for a decision.</summary>
|
||||
public sealed record UniverseContext(DateOnly Day, IReadOnlyList<string> Available);
|
||||
|
||||
/// <summary>Named numeric parameters of a strategy variant. Values are decimal so a grid is written exactly.</summary>
|
||||
public sealed class StrategyParameters
|
||||
{
|
||||
private readonly SortedDictionary<string, decimal> _values;
|
||||
|
||||
public StrategyParameters(IEnumerable<KeyValuePair<string, decimal>> values)
|
||||
{
|
||||
_values = new SortedDictionary<string, decimal>(StringComparer.Ordinal);
|
||||
foreach (var (key, value) in values)
|
||||
{
|
||||
_values[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public static StrategyParameters None { get; } = new([]);
|
||||
|
||||
public IReadOnlyDictionary<string, decimal> Values => _values;
|
||||
|
||||
public decimal this[string name] => _values.TryGetValue(name, out var v) ? v : throw new KeyNotFoundException("Missing parameter " + name);
|
||||
|
||||
public int Whole(string name) => (int)this[name];
|
||||
|
||||
/// <summary>A stable text such as <c>fast=20;slow=100</c>: equal parameters give equal text.</summary>
|
||||
public override string ToString() => string.Join(';', _values.Select(p => p.Key + "=" + p.Value.ToString(CultureInfo.InvariantCulture)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Everything a strategy may know when it decides (SPEC 5.3): data up to the decision and not beyond, its own book,
|
||||
/// the instruments' rules. The same object in the backtest, in simulation and with real money: a strategy cannot
|
||||
/// tell where it runs.
|
||||
/// </summary>
|
||||
public sealed class StrategyContext(
|
||||
DateOnly day,
|
||||
DateTimeOffset now,
|
||||
IReadOnlyList<string> universe,
|
||||
PortfolioView portfolio,
|
||||
Func<string, BarSeries> bars,
|
||||
Func<string, InstrumentSpec?> spec)
|
||||
{
|
||||
public DateOnly Day { get; } = day;
|
||||
|
||||
public DateTimeOffset Now { get; } = now;
|
||||
|
||||
/// <summary>Instruments the strategy chose for this decision.</summary>
|
||||
public IReadOnlyList<string> Universe { get; } = universe;
|
||||
|
||||
public PortfolioView Portfolio { get; } = portfolio;
|
||||
|
||||
public BarSeries Bars(string symbol) => bars(symbol);
|
||||
|
||||
public InstrumentSpec? Spec(string symbol) => spec(symbol);
|
||||
}
|
||||
|
||||
/// <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
|
||||
{
|
||||
string Id { get; }
|
||||
|
||||
string Version { get; }
|
||||
|
||||
IReadOnlyList<DecisionTime> Schedule();
|
||||
|
||||
IReadOnlyList<string> Universe(UniverseContext context);
|
||||
|
||||
IReadOnlyList<Intent> Decide(StrategyContext context);
|
||||
}
|
||||
|
||||
/// <summary>A parameter of a strategy family, with the grid tried by default (SPEC 12.2: written before the results).</summary>
|
||||
public sealed record ParameterSpec(string Name, string Label, decimal Default, IReadOnlyList<decimal> Grid, decimal Min, decimal Max);
|
||||
|
||||
/// <summary>A strategy and the parameters it can take: the laboratory builds one variant for each point of the grid.</summary>
|
||||
public interface IStrategyFamily
|
||||
{
|
||||
string Id { get; }
|
||||
|
||||
string Version { get; }
|
||||
|
||||
/// <summary>The name shown to the user, in Italian.</summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>What the strategy does, in plain Italian (SPEC 13.3).</summary>
|
||||
string Description { get; }
|
||||
|
||||
IReadOnlyList<ParameterSpec> Parameters { get; }
|
||||
|
||||
/// <summary>False for a point of the grid that makes no sense (a short average longer than the long one).</summary>
|
||||
bool Accepts(StrategyParameters parameters) => true;
|
||||
|
||||
IStrategy Create(StrategyParameters parameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A step between the strategy and the orders: the correctives of SPEC 8.5 and the risk engine of SPEC 9 plug in
|
||||
/// here. Until Phase 5 both let everything through (SPEC 17, Phase 4).
|
||||
/// </summary>
|
||||
public interface IIntentStage
|
||||
{
|
||||
string Name { get; }
|
||||
|
||||
IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents);
|
||||
}
|
||||
|
||||
public sealed class PassThroughStage(string name) : IIntentStage
|
||||
{
|
||||
public static PassThroughStage Correctives { get; } = new("correctives");
|
||||
|
||||
public static PassThroughStage Risk { get; } = new("risk");
|
||||
|
||||
public string Name { get; } = name;
|
||||
|
||||
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents) => intents;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ using Anubis.Db;
|
||||
namespace Anubis.Trading;
|
||||
|
||||
/// <summary>The three base strategies, their broker and their default share of its capital (SPEC 8.6).</summary>
|
||||
public static class Strategies
|
||||
public static class StrategyNames
|
||||
{
|
||||
public const string CryptoTrend = "crypto_trend";
|
||||
public const string EquityMomentum = "equity_momentum";
|
||||
@@ -82,7 +82,7 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
|
||||
r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Amount: r.Money("amount")), ("k", LedgerKinds.Capital)), cancellationToken).ConfigureAwait(false);
|
||||
var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return rows.Select(r => new StrategyCapital(r.Strategy, r.Account, r.Currency,
|
||||
r.Share ?? Strategies.Base.FirstOrDefault(b => b.Name == r.Strategy).Share,
|
||||
r.Share ?? StrategyNames.Base.FirstOrDefault(b => b.Name == r.Strategy).Share,
|
||||
given.Where(g => g.Account == r.Account && g.Strategy == r.Strategy).Sum(g => g.Amount),
|
||||
equities.Where(e => e.AccountId == r.Account && e.Strategy == r.Strategy).Sum(e => e.Cash))).ToList();
|
||||
}
|
||||
@@ -95,7 +95,7 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx
|
||||
throw new CapitalException("Il capitale affidato non può essere negativo.");
|
||||
}
|
||||
|
||||
var currency = Strategies.CurrencyOf(broker);
|
||||
var currency = StrategyNames.CurrencyOf(broker);
|
||||
var previous = await EntrustedAsync(broker, cancellationToken).ConfigureAwait(false);
|
||||
if (previous is not null && previous.AmountEur == amountEur)
|
||||
{
|
||||
|
||||
@@ -96,7 +96,7 @@ public static class AccountSetup
|
||||
if (await s.CountAsync("SELECT COUNT(*) FROM accounts WHERE broker = @b AND environment = @e", ("b", broker), ("e", environment)).ConfigureAwait(false) == 0)
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, @n, @b, @e, @c, @now)", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("n", NameOf(broker, environment)), ("b", broker), ("e", environment), ("c", Strategies.CurrencyOf(broker)), ("now", now))
|
||||
("id", Ids.NewId(clock)), ("n", NameOf(broker, environment)), ("b", broker), ("e", environment), ("c", StrategyNames.CurrencyOf(broker)), ("now", now))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -106,7 +106,7 @@ public static class AccountSetup
|
||||
|
||||
// By default crypto runs in the internal simulator and stocks in the demo account (SPEC 7.1). A strategy
|
||||
// whose ledger is still empty follows the default when a demo account appears; one with a history stays.
|
||||
foreach (var (strategy, broker, share) in Strategies.Base)
|
||||
foreach (var (strategy, broker, share) in StrategyNames.Base)
|
||||
{
|
||||
var environment = broker == Venues.Alpaca && alpacaDemo ? TradingEnvironments.Demo : TradingEnvironments.Simulation;
|
||||
var target = accounts.First(a => a.Broker == broker && a.Environment == environment).AccountId;
|
||||
@@ -115,7 +115,7 @@ public static class AccountSetup
|
||||
if (current is null && await s.CountAsync("SELECT COUNT(*) FROM strategy_state WHERE strategy = @s", ("s", strategy)).ConfigureAwait(false) == 0)
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, @sh)",
|
||||
cancellationToken, ("id", Ids.NewId(clock)), ("s", strategy), ("a", target), ("st", Strategies.Observation), ("j", new DbJson("{}")), ("now", now), ("sh", share))
|
||||
cancellationToken, ("id", Ids.NewId(clock)), ("s", strategy), ("a", target), ("st", StrategyNames.Observation), ("j", new DbJson("{}")), ("now", now), ("sh", share))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else if (current != target
|
||||
|
||||
Reference in new issue
Block a user