Merge branch 'fase9-fix-ombra' into fase-9
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
d26d945818
23 files changed
+577
-126
No files matched your search
@@ -97,6 +97,7 @@ public sealed class LaboratoryScreenTests
|
||||
Live = new Anubis.Trading.StageFigures(clock.UtcNow, 0.031m, 0.05m, 6.2m, 4, 0.1m), ExpectedFall = 0.32m, ExpectedSlippageBp = 7m, BacktestOverSameDays = 0.025,
|
||||
},
|
||||
new ReviewLine { Strategy = Anubis.Trading.StrategyNames.EquityMomentum, Stage = Anubis.Trading.StrategyStages.Observation, Verdict = Anubis.Trading.ReviewVerdicts.Waiting, Action = Anubis.Trading.ReviewActions.None, Text = "x", Signals = 10, Won = 6 },
|
||||
new ReviewLine { Strategy = Anubis.Trading.StrategyNames.EquityMeanrev, Stage = Anubis.Trading.StrategyStages.Observation, Verdict = Anubis.Trading.ReviewVerdicts.Waiting, Action = Anubis.Trading.ReviewActions.None, Text = "x", NoProtocol = true },
|
||||
],
|
||||
RatesBefore = new Dictionary<string, double> { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.412 },
|
||||
RatesAfter = new Dictionary<string, double> { [Anubis.Trading.StrategyNames.CryptoTrend] = 0.398 },
|
||||
@@ -120,7 +121,7 @@ public sealed class LaboratoryScreenTests
|
||||
{
|
||||
"1º trimestre 2027", "Non superata", "Non superata, resta in simulazione e non può passare ai soldi veri", $"href=\"/laboratorio/{trial}\"", "calo massimo 38,2%, oltre il 25%", "Variante in uso: coin_vol 15",
|
||||
"Non cambia da sola", "Risultato +3,1%; il backtest negli stessi giorni circa +2,5%.", "Scostamento dei prezzi 6,2 punti base, atteso 7 punti base.", "decisioni identiche al backtest del giorno dopo 90,0%",
|
||||
"In attesa dei dati", "10 segnali chiusi, in guadagno 60%", "da 41,2% a 39,8%", "Evento grave confermato", "120,50", "33,25", "1 ancora aperta, 2 solo rimandate", "trimestrali non è misurata", $"/laboratorio/revisione/{first}",
|
||||
"In attesa dei dati", "Non riprovata</span>", "Non riprovata: il protocollo per le azioni arriva con una versione successiva", "10 segnali chiusi, in guadagno 60%", "da 41,2% a 39,8%", "Evento grave confermato", "120,50", "33,25", "1 ancora aperta, 2 solo rimandate", "trimestrali non è misurata", $"/laboratorio/revisione/{first}",
|
||||
})
|
||||
{
|
||||
StringAssert.Contains(page, part, $"Missing \"{part}\".");
|
||||
|
||||
@@ -285,7 +285,7 @@ public sealed class NewsRulesTests
|
||||
var rows = await live.Rig.QueryAsync("SELECT symbol, stage, outcome, reasons FROM decisions WHERE stage = @o", r => (Symbol: r.TextOrNull("symbol"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons")),
|
||||
("o", DecisionStages.Order)).ConfigureAwait(false);
|
||||
CollectionAssert.AreEquivalent(new[] { "ETH-EUR", "SOL-EUR" }, rows.Where(r => r.Outcome == DecisionOutcomes.Refused && r.Reasons.Contains(NewsReasons.Severe, StringComparison.Ordinal)).Select(r => r.Symbol).ToList());
|
||||
var balance = await Anubis.Learning.RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none).ConfigureAwait(false);
|
||||
var balance = await Anubis.Learning.RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, live.Rig.Clock.UtcNow, _none).ConfigureAwait(false);
|
||||
Assert.AreEqual(2, balance.Lines.Single().Open);
|
||||
}
|
||||
|
||||
|
||||
@@ -35,22 +35,25 @@ public sealed class QuarterlyReviewTests
|
||||
}
|
||||
|
||||
// A report of the protocol on those coins, whose verdict each test chooses.
|
||||
private static readonly Lazy<Task<BacktestReport>> _report = new(async () =>
|
||||
private static readonly Lazy<Task<BacktestReport>> _report = new(async () => (await TrialAsync(null).ConfigureAwait(false)).Report);
|
||||
|
||||
private static async Task<(BacktestReport Report, TrialSummary Summary)> TrialAsync(string? judged)
|
||||
{
|
||||
var folder = TempFolder.Create("review-report");
|
||||
try
|
||||
{
|
||||
await WriteHistoryAsync(folder).ConfigureAwait(false);
|
||||
var (plan, _) = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through,
|
||||
CryptoTrendProtocol.Capital, null), At(2027, 1, 5));
|
||||
var plan = Laboratory.BuildPlan(new TrialRequest(Crypto, TrialSources.Research, EuroHistory.Venue, CryptoTrendProtocol.Narrow, CryptoTrendProtocol.From, Through,
|
||||
CryptoTrendProtocol.Capital, null), At(2027, 1, 5)).Plan with
|
||||
{ Judged = judged };
|
||||
var data = await Laboratory.LoadResearchAsync(folder, plan.Data, _none).ConfigureAwait(false);
|
||||
return TrialRunner.Run(Guid.Empty, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(Crypto)!, data, PriorTrials.None, At(2027, 1, 5)).Report;
|
||||
return TrialRunner.Run(Guid.Empty, plan, TrialPlan.Hash(plan.ToJson()), StrategyCatalog.Find(Crypto)!, data, PriorTrials.None, At(2027, 1, 5));
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private sealed class ReviewRig : IAsyncDisposable
|
||||
{
|
||||
@@ -64,6 +67,8 @@ public sealed class QuarterlyReviewTests
|
||||
|
||||
public string? Missing { get; set; }
|
||||
|
||||
public Exception? Failure { get; set; }
|
||||
|
||||
public List<DateOnly> Prepared { get; } = [];
|
||||
|
||||
public Database Db => Live.Rig.Db;
|
||||
@@ -96,7 +101,7 @@ public sealed class QuarterlyReviewTests
|
||||
Review = new QuarterlyReview(Db, Clock, Lab, Live.Stages, Live.Learning, Folder, (to, _) =>
|
||||
{
|
||||
Prepared.Add(to);
|
||||
return Task.FromResult(Missing);
|
||||
return Failure is { } failure ? Task.FromException<string?>(failure) : Task.FromResult(Missing);
|
||||
});
|
||||
Lab.ReviewTrialEnded = Review.ConcludeAsync;
|
||||
}
|
||||
@@ -226,6 +231,33 @@ public sealed class QuarterlyReviewTests
|
||||
Assert.AreEqual(2, await rig.CountAsync("SELECT COUNT(*) FROM journal WHERE code = 'quarterly_review'"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AnErrorWhilePreparingTheHistoryIsAMissingReasonLikeTheOthers()
|
||||
{
|
||||
await using var rig = await ReviewRig.CreateAsync(history: false);
|
||||
await rig.NightAsync(At(2026, 12, 10));
|
||||
rig.Failure = new InvalidOperationException("broken archive at C:\\x");
|
||||
await rig.NightAsync(At(2027, 1, 5));
|
||||
Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status);
|
||||
|
||||
// A wait that ran out is an error too; the stop of the program is not, and the review stays as it is.
|
||||
rig.Failure = new TaskCanceledException();
|
||||
await rig.NightAsync(At(2027, 1, 6));
|
||||
rig.Clock.Set(At(2027, 1, 17));
|
||||
using var stop = new CancellationTokenSource();
|
||||
await stop.CancelAsync();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => rig.Review.RunIfDueAsync(stop.Token));
|
||||
Assert.AreEqual(ReviewStatuses.Preparing, (await QuarterlyReview.ListAsync(rig.Db, _none)).Single().Status);
|
||||
|
||||
rig.Failure = new InvalidOperationException("broken archive at C:\\x");
|
||||
await rig.NightAsync(At(2027, 1, 18));
|
||||
var done = (await QuarterlyReview.ListAsync(rig.Db, _none)).Single();
|
||||
Assert.AreEqual(ReviewStatuses.Done, done.Status);
|
||||
Assert.AreEqual("lo storico non si è potuto preparare per un errore", done.Report!.Missing);
|
||||
Assert.AreEqual("Non riprovata, dati mancanti: lo storico non si è potuto preparare per un errore. Resta valido l'esito precedente.", done.Report.Strategies.Single().Text);
|
||||
}
|
||||
|
||||
// ---- The run ----------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>The real trials, with a restart in the middle: each trial counts once, the review concludes once.</summary>
|
||||
@@ -406,6 +438,78 @@ public sealed class QuarterlyReviewTests
|
||||
Assert.IsTrue((await DemotionAsync()).Met);
|
||||
}
|
||||
|
||||
// ---- The variant in use -----------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>The grid says how much was searched; the figures, the checks and the curve are those of the variant the strategy works with.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public async Task ATrialJudgesTheVariantInUseAndCountsTheSameTries()
|
||||
{
|
||||
var chosen = await _report.Value;
|
||||
Assert.IsNull(chosen.Judged);
|
||||
var used = chosen.Variants.First(v => !v.Chosen && v.NetResult != chosen.Metrics.NetResult);
|
||||
var (report, summary) = await TrialAsync(used.Parameters);
|
||||
Assert.AreEqual((used.Parameters, chosen.Chosen), (report.Judged, report.Chosen));
|
||||
Assert.AreEqual((used.NetResult, used.MaxDrawdown), (report.Metrics.NetResult, report.Metrics.MaxDrawdown));
|
||||
Assert.AreEqual(used.NetResult, report.Costs.Single(c => c.Multiplier == 1m).NetResult);
|
||||
Assert.AreNotEqual(chosen.Costs.Single(c => c.Multiplier == 2m).NetResult, report.Costs.Single(c => c.Multiplier == 2m).NetResult);
|
||||
Assert.AreEqual(used.MaxDrawdown, report.Checks.Single(c => c.Key == ReportCheckKeys.Drawdown).Value);
|
||||
Assert.AreEqual(used.Sharpe, report.DeflatedSharpe.Sharpe);
|
||||
Assert.AreEqual(report.DeflatedSharpe.Value, report.Checks.Single(c => c.Key == ReportCheckKeys.DeflatedSharpe).Value);
|
||||
Assert.AreEqual(CryptoTrendProtocol.Capital + used.NetResult, report.Curve[^1].Equity, 0.01m);
|
||||
CollectionAssert.AreNotEqual(chosen.ExpectedPathP5!.ToList(), report.ExpectedPathP5!.ToList());
|
||||
Assert.AreEqual((used.Parameters, used.NetResult), (summary.Chosen, summary.NetResult));
|
||||
|
||||
// What the grid decided stays.
|
||||
CollectionAssert.AreEqual(chosen.Variants.ToList(), report.Variants.ToList());
|
||||
Assert.AreEqual(chosen.Overfitting, report.Overfitting);
|
||||
Assert.AreEqual((chosen.TrialsCounted, chosen.DeflatedSharpe.Benchmark), (report.TrialsCounted, report.DeflatedSharpe.Benchmark));
|
||||
Assert.IsFalse(report.Limitations.Any(l => l.Contains("griglia", StringComparison.Ordinal)));
|
||||
|
||||
// Not among the variants of the grid: judged all the same, and it says so.
|
||||
var (outside, tries) = await TrialAsync("coin_vol=12;max_stop=20");
|
||||
var added = outside.Variants.Single(v => v.OutsideGrid);
|
||||
Assert.AreEqual(("coin_vol=12;max_stop=20", false), (added.Parameters, added.Chosen));
|
||||
Assert.AreEqual((added.NetResult, added.MaxDrawdown), (outside.Metrics.NetResult, outside.Metrics.MaxDrawdown));
|
||||
CollectionAssert.AreEqual(chosen.Variants.ToList(), outside.Variants.Where(v => !v.OutsideGrid).ToList());
|
||||
Assert.HasCount(chosen.Variants.Count, tries.VariantSharpes);
|
||||
Assert.AreEqual((chosen.TrialsCounted, chosen.DeflatedSharpe.Benchmark, chosen.Overfitting), (outside.TrialsCounted, outside.DeflatedSharpe.Benchmark, outside.Overfitting));
|
||||
Assert.Contains("La variante in uso non è nella griglia", string.Join(" ", outside.Limitations));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
[DataRow(StrategyStages.Observation, "coin_vol=10;max_stop=20", null)]
|
||||
[DataRow(StrategyStages.Simulation, "coin_vol=10;max_stop=20", "coin_vol=10;max_stop=20")]
|
||||
[DataRow(StrategyStages.Simulation, "coin_vol=12.0;max_stop=20", "coin_vol=12;max_stop=20")]
|
||||
[DataRow(StrategyStages.Simulation, null, "coin_vol=15;max_stop=15")]
|
||||
public async Task ThePlanOfAReviewFixesTheVariantInUse(string stage, string? parameters, string? judged)
|
||||
{
|
||||
await using var rig = await ReviewRig.CreateAsync(stage, qualification: Old(true) with { Parameters = parameters });
|
||||
var review = await rig.OpenAsync();
|
||||
await rig.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none, ("q", new DbJson(JsonSerializer.Serialize(Old(true) with { Parameters = "coin_vol=20;max_stop=20" }, Qualification.Json)))), _none);
|
||||
rig.Start();
|
||||
var trials = await rig.Lab.Trials.OfReviewAsync(review.Id, _none);
|
||||
Assert.HasCount(2, trials);
|
||||
Assert.IsTrue(trials.All(t => t.PlanIntact && t.Plan.Judged == judged && t.Variants == 9), string.Join(" ", trials.Select(t => t.Plan.Judged)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheVerdictOnAStrategyWithCapitalIsOfTheVariantInUse()
|
||||
{
|
||||
const string used = "coin_vol=12;max_stop=20";
|
||||
await using var rig = await ReviewRig.CreateAsync(StrategyStages.Simulation, qualification: Old(true) with { Parameters = used });
|
||||
var review = await rig.ReviewAsync(passed: true, r => r with { Judged = used, Variants = [.. r.Variants, new ReportVariant(used, 0.05, 0, 321m, 0.11, 7, false) { OutsideGrid = true }] });
|
||||
var line = review.Report!.Strategies.Single();
|
||||
Assert.AreEqual((ReviewVerdicts.Passed, ReviewActions.Confirmed), (line.Verdict, line.Action));
|
||||
Assert.AreEqual("Revisione del 1º trimestre 2027: protocollo superato su entrambi gli universi con la variante in uso. La variante in uso non è nella griglia: è giudicata lo stesso.", line.Text);
|
||||
Assert.AreEqual((used, 321m, true), (line.InUse!.Parameters, line.InUse.NetResult, line.InUse.OutsideGrid));
|
||||
Assert.AreEqual((await _report.Value).Chosen, line.Chosen!.Parameters);
|
||||
var outcome = JsonSerializer.Deserialize<Qualification>((await rig.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT qualification FROM review_outcomes", r => r.Json("qualification").Text), _none))!, Qualification.Json)!;
|
||||
Assert.AreEqual(used, outcome.Parameters, "the parameters the figures are of");
|
||||
}
|
||||
|
||||
internal static Task NextAsync(Database db, IClock clock, string verdict, DateOnly through) => db.WriteAsync(async s =>
|
||||
{
|
||||
var id = Ids.NewId(clock);
|
||||
@@ -433,6 +537,21 @@ public sealed class QuarterlyReviewTests
|
||||
var stock = review.Report.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum);
|
||||
Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None), (stock.Verdict, stock.Action));
|
||||
Assert.IsNull(await rig.Live.Stages.ReviewVerdictAsync(StrategyNames.EquityMomentum, _none));
|
||||
Assert.AreEqual((false, "non riprovata, mancano i dati"), (stock.NoProtocol, QuarterlyReview.ActionText(stock)));
|
||||
|
||||
// With the bars collected what is missing is the protocol, not the data.
|
||||
var share = await new InstrumentCatalog(rig.Db, rig.Clock).EnsureAsync(StrategyData.Share("AAA"), _none);
|
||||
await new BarStore(rig.Db, rig.Clock).UpsertDailyAsync(share.Id, [new DailyBar(new DateOnly(2027, 1, 4), 50, 51, 49, 50, 1000)], "test", _none);
|
||||
await rig.NightAsync(At(2027, 4, 5));
|
||||
await rig.EndAsync((await QuarterlyReview.ListAsync(rig.Db, _none))[0], passed: false);
|
||||
await rig.Review.ConcludeAsync(_none);
|
||||
stock = (await QuarterlyReview.ListAsync(rig.Db, _none))[0].Report!.Strategies.Single(l => l.Strategy == StrategyNames.EquityMomentum);
|
||||
const string text = "non riprovata: il protocollo per le azioni arriva con una versione successiva";
|
||||
Assert.AreEqual((ReviewVerdicts.Waiting, ReviewActions.None, true), (stock.Verdict, stock.Action, stock.NoProtocol));
|
||||
Assert.AreEqual(text, QuarterlyReview.ActionText(stock));
|
||||
Assert.StartsWith("Non riprovata: il protocollo per le azioni", stock.Text);
|
||||
Assert.Contains(text, (await NewsRulesTests.DiaryAsync(rig.Db)).Last(m => m.StartsWith("Revisione trimestrale pronta (2º", StringComparison.Ordinal)));
|
||||
Assert.AreEqual(1, await rig.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind = 'quarterly_review' AND message LIKE '%versione successiva%'"));
|
||||
}
|
||||
|
||||
// ---- Base rates -------------------------------------------------------------------------------------------------
|
||||
@@ -619,6 +738,50 @@ public sealed class QuarterlyReviewTests
|
||||
Assert.AreEqual(1, RestrictionBalance.Of([Block(seen, NewsReasons.Negative)], [seen], [], _capital).Lines.Single().Stopped);
|
||||
}
|
||||
|
||||
/// <summary>A block is of the period in which its outcome became known, so the periods add up to the whole.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ThePeriodsOfTheBalanceAddUpToTheWhole()
|
||||
{
|
||||
var first = _t0.AddDays(3);
|
||||
var second = _t0.AddDays(30);
|
||||
var early = Case("AAA", true, 0.05, 2) with { LabelledAt = _t0.AddDays(2.5) };
|
||||
var lost = Case("BBB", false, -0.1, 5) with { LabelledAt = _t0.AddDays(6) };
|
||||
var off = Case("CCC", false, -0.2, 2) with { LabelledAt = first.AddDays(1) };
|
||||
var open = Case("DDD", null, null, null, labelled: false);
|
||||
var bought = Case("EEE", false, -0.2, 5) with { LabelledAt = _t0.AddDays(6) };
|
||||
var seen = Case("FFF", false, -0.2, 5, stage: StrategyStages.Observation) with { LabelledAt = _t0.AddDays(6) };
|
||||
var never = Case("GGG", null, null, 1) with { LabelledAt = _t0.AddDays(1) };
|
||||
IReadOnlyList<BlockedEntry> blocks =
|
||||
[
|
||||
.. new[] { early, lost, off, open, bought, never }.Select(e => Block(e, NewsReasons.Severe)), Block(seen, CorrectiveReasons.CalendarEvent, postponed: true),
|
||||
new BlockedEntry(Guid.NewGuid(), Crypto, "HHH", NewsReasons.Severe, false, _t0), new BlockedEntry(Guid.NewGuid(), Crypto, "HHH", NewsReasons.Severe, false, first.AddDays(2)),
|
||||
];
|
||||
RestrictionReport Of(DateTimeOffset from, DateTimeOffset until) => RestrictionBalance.Of(blocks, [early, lost, off, open, bought, seen, never], [new HeldTrade(Crypto, "EEE", _t0.AddDays(4), null)], _capital, from, until);
|
||||
RestrictionLine? Line(RestrictionReport r, string code) => r.Lines.SingleOrDefault(l => l.Code == code);
|
||||
var (one, two, ever) = (Of(DateTimeOffset.UnixEpoch, first), Of(first, second), Of(DateTimeOffset.UnixEpoch, second));
|
||||
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 1, 0m, 40m, 4, 1, 0, 1), Line(one, NewsReasons.Severe), "what was not known yet is open");
|
||||
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 2, 240m, 0m, 1, 0, 1, 1), Line(two, NewsReasons.Severe), "known after the first review, even what closed before it");
|
||||
Assert.AreEqual(new RestrictionLine(NewsReasons.Severe, 3, 240m, 40m, 1, 1, 1, 2), Line(ever, NewsReasons.Severe));
|
||||
Assert.AreEqual(1, Line(one, CorrectiveReasons.CalendarEvent)!.Open);
|
||||
Assert.AreEqual((1, 0), (Line(two, CorrectiveReasons.CalendarEvent)!.Delayed, Line(two, CorrectiveReasons.CalendarEvent)!.Open));
|
||||
Assert.AreEqual(Line(two, CorrectiveReasons.CalendarEvent), Line(ever, CorrectiveReasons.CalendarEvent));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheFirstReviewCountsTheRestrictionsFromTheStart()
|
||||
{
|
||||
await using var rig = await ReviewRig.CreateAsync();
|
||||
rig.Clock.Set(new DateTimeOffset(2026, 8, 15, 10, 0, 0, TimeSpan.Zero));
|
||||
await rig.Db.WriteAsync(s => DecisionLog.WriteAsync(s, rig.Clock, new DecisionRow(Guid.NewGuid(), Crypto, null, "ETH-EUR", DecisionStages.Order, DecisionOutcomes.Refused, [NewsReasons.Severe],
|
||||
new Dictionary<string, object?>(), rig.Clock.UtcNow), _none), _none);
|
||||
var report = (await rig.ReviewAsync(passed: false)).Report!;
|
||||
Assert.AreEqual(1, report.RestrictionsEver.Lines.Single().Increases);
|
||||
Assert.AreEqual(report.RestrictionsEver.Lines.Single(), report.Restrictions.Lines.SingleOrDefault());
|
||||
Assert.AreEqual(new DateOnly(2026, 8, 15), report.RestrictionsFrom);
|
||||
}
|
||||
|
||||
/// <summary>The decisions of the live engine, as they are written, give the balance.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
@@ -634,10 +797,13 @@ public sealed class QuarterlyReviewTests
|
||||
await live.DayAsync(day);
|
||||
var cases = (await live.Learning.Store.AllAsync(_none)).Where(e => e.Symbol is "ETH-EUR" or "SOL-EUR").ToList();
|
||||
Assert.HasCount(2, cases);
|
||||
var open = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none);
|
||||
var first = live.Rig.Clock.UtcNow;
|
||||
var open = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, first, _none);
|
||||
Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Severe).Open);
|
||||
Assert.AreEqual(1, open.Lines.Single(l => l.Code == NewsReasons.Negative).Open);
|
||||
|
||||
// The outcomes arrive after the first review.
|
||||
live.Rig.Clock.Set(first.AddDays(20));
|
||||
foreach (var e in cases)
|
||||
{
|
||||
var loses = e.Symbol == "ETH-EUR";
|
||||
@@ -645,11 +811,15 @@ public sealed class QuarterlyReviewTests
|
||||
}
|
||||
|
||||
var capital = (decimal)(await LearningCycle.CapitalsAsync(live.Rig.Db, live.Rig.Clock, _none))[Crypto];
|
||||
var r = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, _none);
|
||||
var now = live.Rig.Clock.UtcNow;
|
||||
var r = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, now, _none);
|
||||
decimal Of(string symbol, decimal result) => Math.Round(cases.Single(e => e.Symbol == symbol).Weight * result * capital, 2);
|
||||
Assert.IsGreaterThan(0m, r.Avoided);
|
||||
Assert.AreEqual(Of("ETH-EUR", 0.1m), r.Avoided, 0.01m);
|
||||
Assert.AreEqual(Of("SOL-EUR", 0.04m), r.GivenUp, 0.01m);
|
||||
Assert.IsTrue((await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, live.Rig.Clock.UtcNow.AddDays(1), _none)).IsEmpty);
|
||||
Assert.IsTrue((await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, now, now.AddDays(1), _none)).IsEmpty, "each outcome in one period only");
|
||||
var since = await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, first, now, _none);
|
||||
Assert.AreEqual((r.Avoided, r.GivenUp), (since.Avoided, since.GivenUp), "blocked before the first review, known after it");
|
||||
Assert.AreEqual(2, (await RestrictionBalance.LoadAsync(live.Rig.Db, live.Rig.Clock, DateTimeOffset.UnixEpoch, first, _none)).Lines.Sum(l => l.Open));
|
||||
}
|
||||
}
|
||||
@@ -271,19 +271,9 @@ public sealed partial class SecurityTests
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AKeyNeverFollowsARedirect()
|
||||
{
|
||||
var builder = WebApplication.CreateSlimBuilder();
|
||||
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||
await using var other = builder.Build();
|
||||
var reached = 0;
|
||||
other.MapFallback(() => Interlocked.Increment(ref reached));
|
||||
await other.StartAsync();
|
||||
var target = other.Urls.Single();
|
||||
|
||||
builder = WebApplication.CreateSlimBuilder();
|
||||
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||
await using var broker = builder.Build();
|
||||
broker.MapFallback((HttpContext c) => Results.Redirect(target + c.Request.Path, permanent: false, preserveMethod: true));
|
||||
await broker.StartAsync();
|
||||
await using var other = await FallbackAsync(_ => Results.Ok(Interlocked.Increment(ref reached)));
|
||||
await using var broker = await FallbackAsync(c => Results.Redirect(other.Urls.Single() + c.Request.Path, permanent: false, preserveMethod: true));
|
||||
var address = new Uri(broker.Urls.Single());
|
||||
|
||||
using var http = Outgoing.KeyedClient();
|
||||
@@ -298,6 +288,32 @@ public sealed partial class SecurityTests
|
||||
Assert.AreEqual(0, reached, "The other host must never be reached.");
|
||||
}
|
||||
|
||||
private static async Task<WebApplication> FallbackAsync(Func<HttpContext, IResult> answer)
|
||||
{
|
||||
var builder = WebApplication.CreateSlimBuilder();
|
||||
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||
var app = builder.Build();
|
||||
app.MapFallback(answer);
|
||||
await app.StartAsync();
|
||||
return app;
|
||||
}
|
||||
|
||||
/// <summary>The contact for the SEC is the user's own e-mail (ADR 0020): another host must never see it, on the client the service really uses.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheContactOfTheSecNeverFollowsARedirect()
|
||||
{
|
||||
var reached = 0;
|
||||
await using var other = await FallbackAsync(_ => Results.Ok(Interlocked.Increment(ref reached)));
|
||||
await using var sec = await FallbackAsync(c => Results.Redirect(other.Urls.Single() + c.Request.Path));
|
||||
await using var test = await DatabaseTests.MigratedAsync();
|
||||
var bus = new EventBus();
|
||||
using var market = new MarketDataService(test.Db, SystemClock.Instance, bus, new SettingsStore(test.Db, SystemClock.Instance, bus), new SecretStore(test.Db, SystemClock.Instance, new byte[32]), null);
|
||||
var agent = new Dictionary<string, string> { ["User-Agent"] = Edgar.UserAgent("prova@esempio.it")! };
|
||||
await Assert.ThrowsAsync<MarketDataException>(() => market.Sec.GetBytesAsync(new Uri(sec.Urls.Single() + "/files/company_tickers"), null, agent, CancellationToken.None));
|
||||
Assert.AreEqual(0, reached);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
[DataRow("POST", "/api/v5/asset/with" + "drawal")]
|
||||
|
||||
@@ -33,10 +33,11 @@ public sealed class ShadowTests
|
||||
|
||||
private static Intent Entry(string symbol, double strength = 0, decimal weight = 0.1m) => new(symbol, weight, "entry") { StopOffset = 1m, Strength = strength };
|
||||
|
||||
private static ShadowTurn Turn(string strategy, StrategyContext context, IReadOnlyList<Intent> intents, ShadowInput? input = null, Func<StrategyContext, Intent, double?>? probability = null)
|
||||
private static ShadowTurn Turn(string strategy, StrategyContext context, IReadOnlyList<Intent> intents, ShadowInput? input = null, Func<StrategyContext, Intent, double?>? probability = null,
|
||||
string stage = StrategyStages.Observation)
|
||||
{
|
||||
var collector = new CaseCollector(strategy, (_, _) => true, null, context.Day);
|
||||
var turn = new ShadowTurn(strategy, context.Day, collector, input ?? ShadowInput.Nothing, probability ?? ((_, _) => null), () => new EquityMeanrev());
|
||||
var turn = new ShadowTurn(strategy, stage, context.Day, collector, input ?? ShadowInput.Nothing, probability ?? ((_, _) => null), () => new EquityMeanrev());
|
||||
Assert.AreSame(intents, collector.Apply(context, intents));
|
||||
Assert.AreSame(intents, turn.OnProposals.Apply(context, intents), "the very same list: nothing changes");
|
||||
Assert.AreSame(intents, turn.OnFinal.Apply(context, intents));
|
||||
@@ -76,7 +77,7 @@ public sealed class ShadowTests
|
||||
// Another day of the run says nothing.
|
||||
var other = Context([Stock("AAA", i => 50), Stock(StrategyNames.MarketSymbol, i => 400 - i)], day: _days[^2]);
|
||||
var collector = new CaseCollector(StrategyNames.EquityMeanrev, (_, _) => true, null, Today);
|
||||
var turn = new ShadowTurn(StrategyNames.EquityMeanrev, Today, collector, ShadowInput.Nothing, (_, _) => null, () => new EquityMeanrev());
|
||||
var turn = new ShadowTurn(StrategyNames.EquityMeanrev, StrategyStages.Observation, Today, collector, ShadowInput.Nothing, (_, _) => null, () => new EquityMeanrev());
|
||||
turn.OnProposals.Apply(other, collector.Apply(other, [Entry("AAA")]));
|
||||
Assert.IsEmpty(turn.Cases);
|
||||
}
|
||||
@@ -106,6 +107,65 @@ public sealed class ShadowTests
|
||||
Assert.AreEqual(Improvements.EntryTime, candidate.Cases.Single().Improvement);
|
||||
}
|
||||
|
||||
private static readonly IReadOnlyList<BacktestInstrument> _moving = [Stock("AAA", i => i % 2 == 0 ? 100 : 102)];
|
||||
|
||||
private static Task DecideAsync(TradingRig rig, string strategy, string stage, DateOnly day) => rig.Db.WriteAsync(s =>
|
||||
ShadowDesk.WriteAsync(s, rig.Clock, Guid.NewGuid(), Turn(strategy, Context(_moving, day: day), [Entry("AAA", weight: 1m)], stage: stage), strategy, _none), _none);
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AStrategyThatTradesCountsOnlyWhatTheOthersReallyHold()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync();
|
||||
var desk = new LearningDesk(rig.Db, rig.Clock).Shadow;
|
||||
async Task<string> BooksAsync(string stage) => string.Join(",", (await desk.InputAsync(StrategyNames.CryptoTrend, stage, Today, _none)).OtherBooks.Select(b => b.Stage).Order(StringComparer.Ordinal));
|
||||
await DecideAsync(rig, StrategyNames.EquityMomentum, StrategyStages.Observation, Today);
|
||||
await DecideAsync(rig, StrategyNames.EquityMeanrev, StrategyStages.Simulation, Today);
|
||||
Assert.AreEqual("simulation", await BooksAsync(StrategyStages.Simulation));
|
||||
Assert.AreEqual("simulation", await BooksAsync(StrategyStages.Real));
|
||||
Assert.AreEqual("observation,simulation", await BooksAsync(StrategyStages.Observation), "one that only observes is measured on the three");
|
||||
|
||||
// The entry of one that trades is not shrunk by what another only looks at.
|
||||
async Task<double> FactorAsync(string stage) => Turn(StrategyNames.EquityMeanrev, Context(_moving), [Entry("AAA", weight: 0.2m)],
|
||||
await desk.InputAsync(StrategyNames.EquityMeanrev, stage, Today, _none), stage: stage).Cases.Single(c => c.Improvement == Improvements.VolatilityCap).Factor;
|
||||
Assert.AreEqual(1.0, await FactorAsync(StrategyStages.Simulation));
|
||||
Assert.IsLessThan(1.0, await FactorAsync(StrategyStages.Observation));
|
||||
|
||||
// From the first decision it makes after its promotion, it counts.
|
||||
await DecideAsync(rig, StrategyNames.EquityMomentum, StrategyStages.Simulation, Today);
|
||||
Assert.AreEqual("simulation,simulation", await BooksAsync(StrategyStages.Reduced));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ADecisionRecoveredLateNeverSeesABookOfALaterDay()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync();
|
||||
var desk = new LearningDesk(rig.Db, rig.Clock).Shadow;
|
||||
Task DecideOnAsync(DateOnly day) => DecideAsync(rig, StrategyNames.EquityMomentum, StrategyStages.Observation, day);
|
||||
async Task<string> SeenAsync(DateOnly day) => await desk.InputAsync(StrategyNames.EquityMeanrev, StrategyStages.Observation, day, _none) is var i && i.Whole
|
||||
? string.Join(",", i.OtherBooks.Select(b => b.Day)) : "unknown";
|
||||
Assert.AreEqual("", await SeenAsync(Today), "no decision yet, nothing held");
|
||||
await DecideOnAsync(_days[^4]);
|
||||
await DecideOnAsync(Today);
|
||||
Assert.AreEqual(BarStore.DayText(Today), await SeenAsync(Today));
|
||||
Assert.AreEqual(BarStore.DayText(_days[^4]), await SeenAsync(_days[^2]), "the one in force that day");
|
||||
Assert.AreEqual("unknown", await SeenAsync(_days[^5]));
|
||||
Assert.AreEqual("", await SeenAsync(Today.AddDays(ShadowBook.MaxAgeDays + 1)), "too old to say what it holds");
|
||||
|
||||
// The same day again keeps the one before; a late decision of the same strategy never takes the place of a newer one.
|
||||
await DecideOnAsync(Today);
|
||||
Assert.AreEqual(BarStore.DayText(_days[^4]), await SeenAsync(_days[^2]));
|
||||
await DecideOnAsync(_days[^3]);
|
||||
Assert.AreEqual(BarStore.DayText(Today), await SeenAsync(Today));
|
||||
Assert.AreEqual(BarStore.DayText(_days[^3]), await SeenAsync(_days[^2]));
|
||||
|
||||
// Without the whole portfolio there is no case, but the book is there for the others.
|
||||
var turn = Turn(StrategyNames.EquityMomentum, Context(_moving), [Entry("AAA", weight: 1m)], ShadowInput.Nothing with { Whole = false });
|
||||
Assert.IsNotNull(turn.Book);
|
||||
Assert.IsFalse(turn.Cases.Any(c => c.Improvement == Improvements.VolatilityCap));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheModelWouldChooseOtherCandidates()
|
||||
@@ -138,18 +198,51 @@ public sealed class ShadowTests
|
||||
Assert.IsNull(ShadowDesk.Summary(null, []).Mean);
|
||||
Assert.IsNull(ShadowDesk.Summary(null, [(Monday, 0.01)]).Interval);
|
||||
|
||||
// Ten equal signals in each of two months: the spread between months is what counts.
|
||||
var many = ShadowDesk.Summary(null, [.. Enumerable.Range(0, 20).Select(i => (Monday.AddDays(i < 10 ? 0 : 40), i < 10 ? 0.02 : -0.01))]);
|
||||
// Ten equal signals in each of six months: the spread between months is what counts, not the sixty signals.
|
||||
ImprovementLine Months(int months) => ShadowDesk.Summary(null, [.. Enumerable.Range(0, months * 10).Select(i => (Monday.AddMonths(i / 10), (i / 10) % 2 == 0 ? 0.02 : -0.01))]);
|
||||
var many = Months(6);
|
||||
Assert.AreEqual((60, 6), (many.Cases, many.Months));
|
||||
Assert.AreEqual(0.005, many.Mean!.Value, 1e-9);
|
||||
Assert.IsGreaterThan(0.01, many.Error!.Value);
|
||||
var view = new ImprovementView(Improvements.All[0], 30, [new ImprovementLine(null, 25, 0.004, 0.001)], "", false, null);
|
||||
Assert.AreEqual(Math.Sqrt(6 * 0.15 * 0.15 * 6 / 5) / 60, many.Error!.Value, 1e-9);
|
||||
Assert.IsGreaterThan(3 * 0.015 / Math.Sqrt(59), many.Error.Value, "three times the error of independent signals");
|
||||
Assert.AreEqual(0.005 + (2.5706 * many.Error.Value), many.Interval!.Value.High, 1e-5, "five degrees of freedom, not the normal");
|
||||
Assert.IsNull(many.Missing);
|
||||
var view = new ImprovementView(Improvements.All[0], 30, [new ImprovementLine(null, 25, 12, 0.004, 0.001)], "", false, null);
|
||||
Assert.AreEqual("un indizio discreto", view.Trust);
|
||||
Assert.AreEqual("troppo pochi per fidarsi", (view with { Lines = [new ImprovementLine(null, 19, 0, 0.1)] }).Trust);
|
||||
Assert.AreEqual("conclusione solida", (view with { Lines = [new ImprovementLine(null, 100, 0, 0.1)] }).Trust);
|
||||
Assert.AreEqual("troppo pochi per fidarsi", (view with { Lines = [new ImprovementLine(null, 19, 12, 0, 0.1)] }).Trust);
|
||||
Assert.AreEqual("conclusione solida", (view with { Lines = [new ImprovementLine(null, 100, 12, 0, 0.1)] }).Trust);
|
||||
var said = ShadowDesk.Discoveries([view]).Single();
|
||||
StringAssert.EndsWith(said.Title, "avrebbe aiutato");
|
||||
StringAssert.Contains(said.Detail, "+0,40%");
|
||||
Assert.IsEmpty(ShadowDesk.Discoveries([view with { Lines = [new ImprovementLine(null, 9, 0.1, 0.01)] }]));
|
||||
Assert.IsEmpty(ShadowDesk.Discoveries([view with { Lines = [new ImprovementLine(null, 9, 12, 0.1, 0.01)] }]));
|
||||
|
||||
// With fewer months there is a mean and nothing else, however many the signals.
|
||||
foreach (var months in new[] { 1, 2, 5 })
|
||||
{
|
||||
var few = Months(months);
|
||||
Assert.AreEqual(months * 10, few.Cases);
|
||||
Assert.IsNotNull(few.Mean);
|
||||
Assert.IsNull(few.Error);
|
||||
Assert.IsNull(few.Interval);
|
||||
Assert.AreEqual($"troppo pochi mesi per un intervallo: {months}, ne servono 6", few.Missing);
|
||||
Assert.IsEmpty(ShadowDesk.Discoveries([view with { Lines = [few] }]));
|
||||
Assert.AreEqual("troppo pochi per fidarsi", (view with { Lines = [few with { Cases = 500 }] }).Trust);
|
||||
}
|
||||
|
||||
Assert.IsNull(ShadowDesk.Summary(null, []).Missing);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheQuantilesOfStudentMatchTheTables()
|
||||
{
|
||||
foreach (var (freedom, expected) in new[] { (5, 2.5706), (6, 2.4469), (7, 2.3646), (10, 2.2281), (11, 2.2010), (23, 2.0687), (30, 2.0423), (60, 2.0003), (120, 1.9799) })
|
||||
{
|
||||
Assert.AreEqual(expected, StudentT.Quantile(0.975, freedom), 0.0005);
|
||||
Assert.AreEqual(-expected, StudentT.Quantile(0.025, freedom), 0.0005);
|
||||
}
|
||||
|
||||
Assert.AreEqual(Normal.Quantile(0.975), StudentT.Quantile(0.975, 1_000_000), 1e-5);
|
||||
}
|
||||
|
||||
/// <summary>The same decisions with and without the shadow, also when it cannot be written; then its measure.</summary>
|
||||
|
||||
Reference in new issue
Block a user