Phase 11: decisions from the numbers only, outside rules measured in the shadow
ci / test (postgres) (push) Successful in 5m56s
ci / test (sqlite) (push) Successful in 5m5s
ci / test (postgres) (pull_request) Successful in 5m36s
ci / test (sqlite) (pull_request) Successful in 4m52s
ci / image (push) Successful in 2m6s
ci / image (pull_request) Successful in 52s

News, the economic calendar and earnings dates no longer change any decision by
default (ADR 0023). A new switch, decisions.external_rules, chooses between
"misurate" (default) and "attive" (the Phase 7 behaviour); ADR 0027 records
every choice.

- Engine: with "misurate" nothing is held, postponed or kept, no diary or note
  is written and equity_meanrev gets no earnings dates. The gate is still asked,
  per rule and with all rows on, to write one shadow case per rule, strategy,
  instrument and day. The switch is read once per decision; the one-step check
  and the release of a planned order read it as it was when the decision ran.
- Shadow: five rules measured with the existing improvement machinery, 99%
  interval, "too early" under six months, the ADR 0023 criterion; the earnings
  exit is measured by relabelling with the report date. Shown in the Laboratorio
  and in the quarterly review beside the historical restriction balance.
- Model: the seven outside clues stay out of training; a champion that uses one
  is set aside at once, without an alarm, and Sunday trains one without them.
- Settings: the switch changes only from the settings form, with the
  protections of the five rows; the API refuses it; each change writes one diary
  line. The first start of this version records "attive" until then on an
  installation that had already decided.
- Screens, demo and manual follow "misurate".

Two independent review rounds; their confirmed findings are fixed and tested.
SQLite, PostgreSQL and the image with the guard drill are green.

refs #116, refs #117

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-03 22:59:16 +01:00
1 parent ed22d1c8b5
commit 501c9be70e
47 files changed
+1743 -169

No files matched your search

+17
View File
@@ -17,9 +17,26 @@ public sealed class DatabaseTests
{
var test = await TestDb.CreateAsync().ConfigureAwait(false);
await Migrations.MigrateAsync(test.Db, _clock, null, CancellationToken.None).ConfigureAwait(false);
// The rules of the news act in the tests of Phase 7 (ADR 0027 point 3): set here, without a change in the log. A
// test of «misurate» asks for it.
await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)", CancellationToken.None,
("id", Ids.NewId(_clock)), ("k", News.ExternalRules.Setting.Key), ("v", new DbJson(System.Text.Json.JsonSerializer.Serialize(News.ExternalRules.Active))), ("t", _clock.UtcNow)))
.ConfigureAwait(false);
return test;
}
/// <summary>
/// Puts the rules of the news back to the default of ADR 0023, «misurate», in a database of <see cref="MigratedAsync"/>;
/// <paramref name="since"/> is when the switch was written, as on a new installation.
/// </summary>
internal static Task MeasuredAsync(Database db, DateTimeOffset? since = null) =>
db.WriteAsync(s => since is { } at
? s.ExecuteAsync("UPDATE config SET value = @v, created_at = @t, updated_at = @t WHERE key = @k", CancellationToken.None,
("k", News.ExternalRules.Setting.Key), ("v", new DbJson(System.Text.Json.JsonSerializer.Serialize(News.ExternalRules.Measured))), ("t", at))
: s.ExecuteAsync("UPDATE config SET value = @v WHERE key = @k", CancellationToken.None,
("k", News.ExternalRules.Setting.Key), ("v", new DbJson(System.Text.Json.JsonSerializer.Serialize(News.ExternalRules.Measured)))));
[TestMethod]
[TestCategory(Category.Integration)]
public async Task MigrationsCreateTheSchemaAndRunOnce()
+1 -1
View File
@@ -121,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", "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}",
"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", "Le trimestrali sono misurate nella tabella delle regole in ombra", $"/laboratorio/revisione/{first}",
})
{
StringAssert.Contains(page, part, $"Missing \"{part}\".");
+1 -1
View File
@@ -44,7 +44,7 @@ public sealed class LearningScreenTests
"Non potrà mai ingrandirle, né aprirne di sue.", "<strong>212</strong> <span class=\"muted\">su 300 necessari</span>", "Al ritmo attuale, tra tre e quattro settimane.",
"56%", "Tirando a caso sarebbe il 50%", "Domenica 4 ottobre, versione 3", "Prossima verifica dello sfidante", "Domenica 11 ottobre, 03:00",
"54% su 61 casi", "71% su 14 casi", "Stima perfetta", "Quando stima il 60%, è andata bene il 60% delle volte: è ben tarato.", "troppo pochi casi per contarci",
"Forza della tendenza", "Scommesse a leva sulle crypto", "Tutto il resto", "insieme a paura e avidità pesano 17 su 100.",
"Forza della tendenza", "Scommesse a leva sulle crypto", "Tutto il resto", "Notizie, trimestrali, paura e avidità non entrano nel modello: le decisioni guardano solo i numeri del mercato.",
"In carica, versione 2", "Sfidante, versione 3", "16 agosto", "2.152", "2.332", "0,241", "0,239", "(senza filtro: +5,84", "+7,90", "+8,10", "non serve", "14 su 100",
"La versione 3 è ancora in prova.", "Sembra un po' meglio, ma ha solo 14 casi di confronto su 100", "Fino ad allora gira in ombra accanto alla 2.",
"Nessuna anomalia", "Il mercato di oggi somiglia a quello su cui ha studiato", "Precisione sugli ultimi 60 casi: 55%, in linea con il 56% atteso",
+18
View File
@@ -118,6 +118,24 @@ internal sealed class StockRig : IAsyncDisposable
Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, _stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar) { Learning = learning };
}
/// <summary>
/// The engine again with news, calendar and earnings only measured (ADR 0023): the earnings calendar, the learning and the
/// gate it asks for the shadow.
/// </summary>
/// <paramref name="measuredAt"/> says whether they were measured at an instant (the change log); without it, always.
public void UseMeasured(Func<DateOnly, CancellationToken, Task<EarningsView?>> earnings, Learning.LearningDesk learning, News.IEntryGate? gate = null,
Func<DateTimeOffset, bool>? measuredAt = null)
{
Engine.Dispose();
Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, _stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar)
{
Earnings = earnings,
Learning = learning,
Gate = gate,
RulesMeasured = (at, _) => Task.FromResult(measuredAt?.Invoke(at) ?? true),
};
}
/// <summary>The engine again, with the rules of SPEC 10.5 on single purchases.</summary>
public void UseGate(News.IEntryGate gate)
{
+12
View File
@@ -111,9 +111,21 @@ internal sealed class LiveRig : IAsyncDisposable
AccountReady = _ => AccountStarted,
Gate = Gate,
Learning = Learning = new Anubis.Learning.LearningDesk(Rig.Db, Rig.Clock) { First = First },
RulesMeasured = Measured ? (_, _) => Task.FromResult(true) : null,
};
}
/// <summary>News, calendar and earnings only measured (ADR 0023): the default of a real installation, asked by the tests of Phase 11.</summary>
public bool Measured { get; private set; }
/// <summary>The engine again, with the rules of 10.5 only measured.</summary>
public void UseMeasured()
{
Measured = true;
Engine.Dispose();
Build();
}
public Anubis.Learning.LearningDesk Learning { get; private set; } = null!;
/// <summary>The first model and the base rates the engine starts from.</summary>
+472
View File
@@ -0,0 +1,472 @@
using System.Net.Http.Json;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Learning;
using Anubis.News;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// Phase 11 (ADR 0023, 0027): news, calendar and earnings only measured. By default nothing they say changes a decision,
/// and each rule writes in the shadow what it would have done.
/// </summary>
[TestClass]
public sealed class MeasuredRulesTests
{
private static readonly CancellationToken _none = CancellationToken.None;
// ---- The switch ---------------------------------------------------------------------------------------------
/// <summary>
/// A new installation starts with the rules only measured; a part built without settings (only tests do that) lets them
/// act. A change writes its line once, in the same transaction, and the value of an earlier moment is read back.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheSwitchStartsMeasuredAndRemembersWhatItWas()
{
await using var test = await TestDb.CreateAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero));
await Migrations.MigrateAsync(test.Db, clock, null, _none);
var settings = new SettingsStore(test.Db, clock, new EventBus());
Assert.AreEqual(ExternalRules.Measured, (await settings.GetAsync(ExternalRules.Setting.Key)).Value);
Assert.IsTrue(await ExternalRules.MeasuredAsync(settings, _none));
Assert.IsFalse(await ExternalRules.MeasuredAsync(null, _none), "without settings the rules act, as the five rows are on");
var before = clock.UtcNow;
clock.Advance(TimeSpan.FromHours(1));
async Task<bool> SetAsync(string value) => await settings.SetAsync(ExternalRules.Setting.Key, value, "admin",
(s, old) => ExternalRules.WriteChangeAsync(s, clock, old, value, "admin", _none), _none);
Assert.IsTrue(await SetAsync(ExternalRules.Active));
Assert.IsFalse(await SetAsync(ExternalRules.Active), "nothing changed: no line");
var lines = await NewsRulesTests.DiaryAsync(test.Db);
Assert.HasCount(1, lines);
StringAssert.StartsWith(lines[0], "Notizie, calendario e trimestrali da «solo misurate» a «attive»");
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications"), _none), "no Telegram");
Assert.IsFalse(await ExternalRules.MeasuredAsync(settings, _none));
Assert.IsTrue(await ExternalRules.MeasuredAtAsync(settings, before, _none), "an hour ago they were only measured");
Assert.IsFalse(await ExternalRules.MeasuredAtAsync(settings, clock.UtcNow, _none));
}
/// <summary>The tests of Phase 7 run with the rules acting: the support of the tests sets «attive», without a change in the log.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheSupportOfTheTestsSetsTheRulesActing()
{
await using var test = await DatabaseTests.MigratedAsync();
var settings = new SettingsStore(test.Db, new ManualClock(DateTimeOffset.UnixEpoch), new EventBus());
Assert.IsFalse(await ExternalRules.MeasuredAsync(settings, _none));
Assert.IsEmpty(await settings.HistoryAsync(ExternalRules.Setting.Key));
await DatabaseTests.MeasuredAsync(test.Db);
Assert.IsTrue(await ExternalRules.MeasuredAsync(settings, _none));
}
// ---- The decisions ------------------------------------------------------------------------------------------
/// <summary>
/// The scene of NewsRulesTests: a confirmed serious event on ETH and a negative story on SOL before the crypto close. With
/// the rules measured both purchases go, nothing is held, nothing is said, and each rule leaves one case in the shadow.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AConfirmedSevereStoryChangesNothingAndIsMeasuredInTheShadow()
{
var day = new DateOnly(2026, 9, 1);
await using var live = await LiveRig.CreateAsync(day, day.AddDays(39));
live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock));
live.UseMeasured();
await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["ETH-EUR"].Spec, "Ethereum exchange hacked", new DateTimeOffset(2026, 8, 31, 20, 0, 0, TimeSpan.Zero), 4, -0.9,
"CoinDesk", trusted: true);
await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["SOL-EUR"].Spec, "Solana upgrade delayed by a week", new DateTimeOffset(2026, 8, 31, 23, 30, 0, TimeSpan.Zero),
3, -0.8, "CoinDesk", trusted: true);
await live.DayAsync(day);
var fills = await live.LiveFillsAsync();
Assert.IsTrue(fills.Any(f => f is { Symbol: "ETH-EUR", Side: OrderSide.Buy }), string.Join(", ", fills));
Assert.IsTrue(fills.Any(f => f is { Symbol: "SOL-EUR", Side: OrderSide.Buy }), string.Join(", ", fills));
var held = (await live.Rig.QueryAsync("SELECT symbol, reasons FROM decisions WHERE outcome IN (@r, @p)", r => (Symbol: r.TextOrNull("symbol"), Reasons: r.Text("reasons")),
("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed))).Where(d => d.Reasons.Contains("news_", StringComparison.Ordinal) || d.Reasons.Contains("calendar", StringComparison.Ordinal));
Assert.IsFalse(held.Any(), "no row of a block");
var diary = await NewsRulesTests.DiaryAsync(live.Rig.Db);
Assert.IsFalse(diary.Any(l => l.Contains("Non compro", StringComparison.Ordinal) || l.Contains("Motivo: «", StringComparison.Ordinal)), string.Join(" | ", diary));
Assert.AreEqual(0L, await live.Rig.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications WHERE kind LIKE 'news%'"), _none), "no notice of the news");
var cases = await live.Rig.QueryAsync("SELECT improvement, symbol, decided_day, factor FROM shadow_cases WHERE improvement LIKE 'rule_%'",
r => (Rule: r.Text("improvement"), Symbol: r.Text("symbol"), Day: r.Text("decided_day"), Factor: r.Measure("factor")));
Assert.IsFalse(cases.GroupBy(c => (c.Rule, c.Symbol, c.Day)).Any(g => g.Count() > 1), "one case per rule, strategy, instrument and day");
// The crypto close of 31 August is decided just after midnight UTC: the case carries the day of the bar.
double Factor(string rule, string symbol) =>
cases.SingleOrDefault(c => c.Rule == rule && c.Symbol == symbol && c.Day == "2026-08-31") is { Rule: not null } found ? found.Factor
: throw new AssertFailedException($"No case {rule} on {symbol}: " + string.Join(", ", cases));
Assert.AreEqual(0, Factor(ShadowRules.NewsSevere, "ETH-EUR"), "the serious event would have left ETH out");
Assert.AreEqual(1, Factor(ShadowRules.NewsSevere, "SOL-EUR"));
Assert.AreEqual(0, Factor(ShadowRules.NewsNegative, "SOL-EUR"), "the negative story would have left SOL out");
Assert.AreEqual(1, Factor(ShadowRules.Macro, "ETH-EUR"), "no figure that morning");
}
/// <summary>The same scene with the rules acting writes no case in the shadow: the balance of the restrictions measures them.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task WithTheRulesActingNothingGoesToTheShadow()
{
var day = new DateOnly(2026, 9, 1);
await using var live = await LiveRig.CreateAsync(day, day.AddDays(39));
live.UseGate(new EntryGate(live.Rig.Db, live.Rig.Clock));
await NewsRulesTests.StoryAsync(live.Rig.Db, live.Rig.Clock, live.Instruments["ETH-EUR"].Spec, "Ethereum exchange hacked", new DateTimeOffset(2026, 8, 31, 20, 0, 0, TimeSpan.Zero), 4, -0.9,
"CoinDesk", trusted: true);
await live.DayAsync(day);
Assert.IsEmpty(await live.Rig.QueryAsync("SELECT id FROM shadow_cases WHERE improvement LIKE 'rule_%'", r => r.Id("id")));
}
/// <summary>
/// The scene of the earnings: the close of 1 September plans BBB, which reports on 3 September before the open. With the
/// rules measured the purchase goes, the strategy never leaves for the report, and both rules of the earnings are noted
/// at the entry. Once the operation has its label, the exit is measured against the label made with the report.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task MeanReversionEntersBeforeEarningsAndNeverLeavesForThem()
{
var day = new DateOnly(2026, 9, 1);
await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41));
await new CalendarEventStore(stocks.Rig.Db, stocks.Rig.Clock).UpsertAsync(
[new CalendarEvent(CalendarEventKinds.Earnings, "Trimestrale BBB", new DateTimeOffset(2026, 9, 3, 11, 0, 0, TimeSpan.Zero), false, "test", "earnings:BBB")
{ Symbol = "BBB", TimeHint = "bmo" }], _none);
var desk = new NewsDesk(stocks.Rig.Db, stocks.Rig.Clock);
var learning = new LearningDesk(stocks.Rig.Db, stocks.Rig.Clock) { First = null };
stocks.UseMeasured(async (d, ct) => new EarningsView(await desk.EarningsAsync(d, ct), true), learning);
await stocks.SessionAsync(day);
var planned = await stocks.Rig.QueryAsync("SELECT i.symbol FROM planned_orders p JOIN instruments i ON i.id = p.instrument_id WHERE p.side = 'buy'", r => r.Text("symbol"));
CollectionAssert.Contains(planned.ToList(), "BBB", "the report tomorrow keeps nothing out");
var example = (await learning.Store.LiveAsync(StrategyNames.EquityMeanrev, _none)).Single(e => e.Symbol == "BBB");
Assert.IsFalse(example.Features.ContainsKey(Clues.EarningsDays), "no earnings clue: the label never leaves before a report");
for (var d = day.AddDays(1); d <= day.AddDays(20); d = d.AddDays(1))
{
await stocks.SessionAsync(d);
}
Assert.IsFalse((await stocks.Rig.QueryAsync("SELECT reasons FROM decisions", r => r.Text("reasons"))).Any(r => r.Contains(EquityMeanrev.Reasons.ExitEarnings, StringComparison.Ordinal)),
"never the exit for the report");
var cases = await stocks.Rig.QueryAsync("SELECT improvement, factor, data FROM shadow_cases WHERE symbol = 'BBB' AND decided_day = '2026-09-01' AND improvement LIKE 'rule_earnings%'",
r => (Rule: r.Text("improvement"), Factor: r.Measure("factor"), Data: r.Json("data").Text));
Assert.AreEqual(0, cases.Single(c => c.Rule == ShadowRules.EarningsEntry).Factor, "the filter would have kept BBB out");
var exit = cases.Single(c => c.Rule == ShadowRules.EarningsExit);
StringAssert.Contains(exit.Data, "\"Report\":\"2026-09-03\"");
await new LearningCycle(stocks.Rig.Db, stocks.Rig.Clock, learning, stocks.Engine.LabelDataAsync).LabelAsync(_none);
await learning.Shadow.MeasureAsync(stocks.Engine.LabelDataAsync, null, null, _none);
var measured = await stocks.Rig.QueryAsync("SELECT factor, effect, measured_at FROM shadow_cases WHERE symbol = 'BBB' AND decided_day = '2026-09-01' AND improvement = @i",
r => (Factor: r.Measure("factor"), Effect: r.IsNull("effect") ? (double?)null : r.Measure("effect"), Done: !r.IsNull("measured_at")), ("i", ShadowRules.EarningsExit));
Assert.IsTrue(measured.Single().Done);
Assert.AreEqual(0, measured.Single().Factor, "with the report the label leaves on the close before it");
Assert.IsNotNull(measured.Single().Effect);
}
/// <summary>
/// A purchase decided with the rules measured goes at the open as it was decided, even when they act again in the
/// evening: the gate at send time belongs to the decisions taken with «attive» (ADR 0027 point 2).
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task APurchaseDecidedWithTheRulesMeasuredGoesEvenIfTheyActBeforeItLeaves()
{
var day = new DateOnly(2026, 9, 1);
await using var stocks = await StockRig.CreateAsync(day, day.AddDays(41));
var switched = new DateTimeOffset(2026, 9, 1, 23, 0, 0, TimeSpan.Zero);
stocks.UseMeasured((_, _) => Task.FromResult<EarningsView?>(null), new LearningDesk(stocks.Rig.Db, stocks.Rig.Clock) { First = null },
new HoldingGate(new EntryHold(NewsReasons.Severe, new DateTimeOffset(2026, 9, 9, 0, 0, 0, TimeSpan.Zero), "fatto")), at => at < switched);
await stocks.SessionAsync(day);
await stocks.SessionAsync(day.AddDays(1));
var fills = await stocks.LiveFillsAsync();
Assert.IsTrue(fills.Any(f => f is { Symbol: "BBB", Side: OrderSide.Buy }), string.Join(", ", fills));
Assert.IsEmpty(await stocks.Rig.QueryAsync("SELECT id FROM decisions WHERE stage = @o AND outcome IN (@r, @p)", r => r.Id("id"),
("o", DecisionStages.Order), ("r", DecisionOutcomes.Refused), ("p", DecisionOutcomes.Postponed)), "nothing held at the open");
}
// A rule that would hold every purchase, asked only with the rules acting.
private sealed class HoldingGate(EntryHold hold) : IEntryGate
{
public Task<EntryHold?> HoldAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult<EntryHold?>(at < hold.Until ? hold : null);
public Task<EntryHold?> KeepStopAsync(InstrumentSpec spec, DateTimeOffset at, CancellationToken cancellationToken) => Task.FromResult<EntryHold?>(null);
}
/// <summary>
/// The first start of this version writes the switch: on a new installation only the row; on one that already decided,
/// «attive» until now in the change log and one line in the diary, never twice.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFirstStartWritesTheSwitchAndRemembersTheRulesActedBefore()
{
foreach (var decided in new[] { false, true })
{
await using var test = await TestDb.CreateAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero));
await Migrations.MigrateAsync(test.Db, clock, null, _none);
var before = clock.UtcNow.AddDays(-1);
if (decided)
{
await test.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO engine_runs (id, strategy, run_key, decision_day, decision_id, mode, state, proposed, created_at) " +
"VALUES (@id, 'crypto_trend', 'k', '2026-12-02', @d, 'observation', NULL, NULL, @t)", _none, ("id", Ids.NewId(clock)), ("d", Guid.NewGuid()), ("t", before)), _none);
}
Assert.AreEqual(decided, await ExternalRules.SettleAsync(test.Db, clock, _none));
clock.Advance(TimeSpan.FromHours(1));
Assert.IsFalse(await ExternalRules.SettleAsync(test.Db, clock, _none), "once");
var settings = new SettingsStore(test.Db, clock, new EventBus());
Assert.IsTrue(await ExternalRules.MeasuredAsync(settings, _none));
Assert.AreEqual(!decided, await ExternalRules.MeasuredAtAsync(settings, before, _none), "before the upgrade the rules acted");
Assert.IsTrue(await ExternalRules.MeasuredAtAsync(settings, clock.UtcNow, _none));
var history = await settings.HistoryAsync(ExternalRules.Setting.Key);
Assert.HasCount(decided ? 1 : 0, history);
var lines = await NewsRulesTests.DiaryAsync(test.Db);
Assert.HasCount(decided ? 1 : 0, lines);
if (decided)
{
Assert.AreEqual(ExternalRules.Upgrade, history[0].ChangedBy);
StringAssert.StartsWith(lines[0], "Con questa versione notizie, calendario e trimestrali sono solo misurate");
}
}
}
/// <summary>With the rules measured the watcher of the news writes nothing: no note, no line, no notice.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheWatcherIsSilentWhileTheRulesAreMeasured()
{
await using var test = await DatabaseTests.MigratedAsync();
var (clock, settings, specs) = await NewsAnalystTests.SetUpAsync(test.Db);
await DatabaseTests.MeasuredAsync(test.Db);
await NewsRulesTests.StoryAsync(test.Db, clock, specs["SOL"], "Solana upgrade delayed by a week", clock.UtcNow.AddHours(-1), 3, -0.7, "CoinDesk", trusted: true);
Assert.AreEqual(0, await new NewsWatcher(test.Db, clock, settings).RunOnceAsync(_none));
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_notes"), _none), "no note");
Assert.IsEmpty(await NewsRulesTests.DiaryAsync(test.Db));
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications"), _none));
// The same story with the rules acting: the line of Phase 7.
await settings.SetAsync(ExternalRules.Setting.Key, ExternalRules.Active, "admin");
Assert.AreEqual(1, await new NewsWatcher(test.Db, clock, settings).RunOnceAsync(_none));
Assert.HasCount(1, await NewsRulesTests.DiaryAsync(test.Db));
}
// ---- The model ----------------------------------------------------------------------------------------------
/// <summary>The seven outside clues stay out of a training with the rules measured, however many live examples carry them; VIX goes in.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheOutsideCluesStayOutOfTraining()
{
CollectionAssert.AreEquivalent(
new[] { Clues.Tone1, Clues.Tone3, Clues.Count1, Clues.Count3, Clues.WorstEvent, Clues.FearGreed, Clues.EarningsDays }, Clues.External.ToList());
Assert.IsFalse(Clues.IsExternal(Clues.Vix) || Clues.IsExternal(Clues.Funding) || Clues.IsExternal(Clues.OpenInterest), "market numbers stay");
Assert.IsFalse(Clues.HasExternal(FirstModel.Embedded!.Model!.Clues), "the first model uses none of them");
var history = LearningModelTests.Cases(300, _ => 0.5);
IReadOnlyList<Example> examples =
[
.. history, .. LearningModelTests.Cases(400, _ => 0.5, 8, source: CaseSources.Live).Select((c, i) => c with
{
Features = new Dictionary<string, double>(c.Features) { [Clues.FearGreed] = i, [Clues.Tone3] = i % 5, [Clues.EarningsDays] = i % 31, [Clues.Vix] = 10 + (i % 20) },
}),
];
var with = Trainer.CluesOf(examples);
var without = Trainer.CluesOf(examples, external: false);
Assert.Contains(Clues.FearGreed, with);
Assert.Contains(Clues.Vix, without);
Assert.IsFalse(without.Any(Clues.IsExternal), string.Join(", ", without));
}
/// <summary>
/// A model in charge that uses fear and greed counts with the rules acting; with them measured it is set aside at the very
/// next decision, for that reason, and goes on estimating.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AModelWithAnOutsideClueIsSetAsideAtOnce()
{
await using var test = await DatabaseTests.MigratedAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero));
var model = LearningCycleTests.Always(0.3) with { Clues = [Clues.Strength, Clues.FearGreed] };
await LearningCycleTests.AddModelAsync(test.Db, clock, model, ModelStatuses.Champion);
await test.Db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, CycleState.Key, new CycleState { ActivatedAt = clock.UtcNow }, _none), _none);
var desk = new LearningDesk(test.Db, clock, new SettingsStore(test.Db, clock, new EventBus()));
var acting = await desk.GateAsync(_none);
Assert.IsTrue(acting.Counts);
Assert.IsFalse(acting.OutsideClues);
await DatabaseTests.MeasuredAsync(test.Db);
var measured = await desk.GateAsync(_none);
Assert.IsFalse(measured.Counts);
Assert.IsTrue(measured.Aside);
Assert.IsTrue(measured.OutsideClues);
Assert.IsNotNull(measured.Champion, "it keeps estimating");
}
/// <summary>
/// The first night with the rules measured writes the day of the change in the history of the models, once; a model in
/// charge with an outside clue is set aside with its own words and nothing goes to the phone.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFirstNightWritesTheDayOfTheChangeOnce()
{
await using var test = await DatabaseTests.MigratedAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 2, 0, 0, TimeSpan.Zero));
// The switch written with the first start of this version, the evening before: the event says that day, not the night of the check.
await DatabaseTests.MeasuredAsync(test.Db, new DateTimeOffset(2026, 12, 2, 18, 0, 0, TimeSpan.Zero));
await LearningCycleTests.AddModelAsync(test.Db, clock, LearningCycleTests.Always(0.3) with { Clues = [Clues.Strength, Clues.Tone3] }, ModelStatuses.Champion);
var desk = new LearningDesk(test.Db, clock, new SettingsStore(test.Db, clock, new EventBus())) { First = null };
var cycle = new LearningCycle(test.Db, clock, desk, (_, _, _) => Task.FromResult<LabelData?>(null));
await cycle.CheckAsync(_none);
clock.Advance(TimeSpan.FromDays(1));
await cycle.CheckAsync(_none);
var events = await desk.Models.EventsAsync(_none);
Assert.HasCount(1, events.Where(e => e.Kind == ModelEvents.RulesMeasured).ToList());
StringAssert.StartsWith(events.Single(e => e.Kind == ModelEvents.RulesMeasured).Text, "Dal mercoledì 2 dicembre notizie, calendario e trimestrali non cambiano le decisioni");
Assert.HasCount(1, events.Where(e => e.Kind == ModelEvents.RulesAside).ToList());
Assert.IsFalse(events.Any(e => e.Kind == ModelEvents.SetAside), "not an alarm");
Assert.AreEqual(0L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM notifications"), _none));
Assert.IsNull((await desk.CycleAsync(_none)).ActivatedAt, "a model that cannot count does not start counting");
StringAssert.Contains(events.Single(e => e.Kind == ModelEvents.RulesAside).Text, "La domenica ne addestro una senza, che entra in prova come sfidante.");
// The rules act again: the model is back for that reason, and the words say why.
await new SettingsStore(test.Db, clock, new EventBus()).SetAsync(ExternalRules.Setting.Key, ExternalRules.Active, "admin");
clock.Advance(TimeSpan.FromDays(1));
await cycle.CheckAsync(_none);
StringAssert.StartsWith((await desk.Models.EventsAsync(_none)).Single(e => e.Kind == ModelEvents.RulesBack).Text,
"Notizie, calendario e trimestrali sono di nuovo attive: la versione");
}
// ---- The shadow ---------------------------------------------------------------------------------------------
/// <summary>
/// Under six months from the first case a rule says «troppo presto»; then the criterion of ADR 0023 at 99%: 30 entries
/// changed and the whole interval above zero. Postponed entries are counted, not valued.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheRulesSayTooEarlyUnderSixMonthsAndAreJudgedAt99()
{
await using var test = await DatabaseTests.MigratedAsync();
var clock = new ManualClock(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero));
var desk = new LearningDesk(test.Db, clock);
async Task CaseAsync(string rule, string symbol, DateOnly day, double factor, double? effect, string? kind = null) =>
await test.Db.WriteAsync(s => s.ExecuteAsync(
"INSERT INTO shadow_cases (id, improvement, strategy, symbol, decided_day, decision_id, factor, data, effect, measured_at, created_at, updated_at) " +
"VALUES (@id, @i, @s, @sy, @d, @dec, @f, @data, @e, @now, @now, @now)", _none, ("id", Ids.NewId(clock)), ("i", rule), ("s", StrategyNames.CryptoTrend), ("sy", symbol),
("d", BarStore.DayText(day)), ("dec", Guid.NewGuid()), ("f", factor), ("data", new DbJson(kind is null ? "{}" : "{\"Kind\":\"" + kind + "\"}")), ("e", effect), ("now", clock.UtcNow)), _none);
// Eight months of a rule that avoids a loss of about 2% each time, five times a month; one entry only postponed.
var first = new DateOnly(2026, 4, 1);
for (var m = 0; m < 8; m++)
{
for (var i = 0; i < 5; i++)
{
await CaseAsync(ShadowRules.NewsNegative, "C" + i, first.AddMonths(m).AddDays(i), 0, 0.02 + (0.001 * ((m + i) % 3)));
}
}
await CaseAsync(ShadowRules.NewsNegative, "P", first.AddDays(20), 1, 0, ShadowKinds.Postponed);
await CaseAsync(ShadowRules.NewsNegative, "I", first.AddDays(21), 0, null, ShadowKinds.Increase);
await CaseAsync(ShadowRules.NewsSevere, "Q", new DateOnly(2026, 11, 2), 0, -0.01);
var rules = await desk.Shadow.LoadRulesAsync(alpacaKeys: false, finnhubKey: false, _none);
var negative = rules.Single(r => r.Rule.Key == ShadowRules.NewsNegative);
Assert.AreEqual(42, negative.Examined);
Assert.AreEqual(40, negative.Changed);
Assert.AreEqual(1, negative.Postponed);
Assert.AreEqual(1, negative.Increases, "an increase held back is counted, not valued");
Assert.AreEqual(0.99, negative.Line.Level);
Assert.IsGreaterThan(0, negative.Line.Interval!.Value.Low);
Assert.AreEqual("Criterio raggiunto", negative.State);
Assert.IsTrue(negative.Met);
var severe = rules.Single(r => r.Rule.Key == ShadowRules.NewsSevere);
Assert.AreEqual("Troppo presto", severe.State);
Assert.AreEqual(new DateOnly(2027, 5, 2), severe.JudgedFrom);
Assert.AreEqual("In attesa delle chiavi Alpaca", rules.Single(r => r.Rule.Key == ShadowRules.EarningsEntry).State);
Assert.AreEqual("Nessun caso finora", rules.Single(r => r.Rule.Key == ShadowRules.Macro).State);
// At 95% the same months would give a narrower interval: the rules ask for more.
var at95 = negative.Line with { Level = 0.95 };
Assert.IsLessThan(negative.Line.Interval!.Value.High - negative.Line.Interval.Value.Low, at95.Interval!.Value.High - at95.Interval.Value.Low);
}
/// <summary>The entry filter of the strategy as a pure rule: three sessions after the entry, the weekend skipped.</summary>
[TestMethod]
[TestCategory(Category.Unit)]
public void TheEarningsRuleSkipsTheWeekend()
{
var thursday = new DateOnly(2026, 9, 3);
var friday = thursday.AddDays(1);
Assert.IsTrue(EquityMeanrev.EarningsAhead(thursday, friday, new DateOnly(2026, 9, 9), 3), "Friday, Monday, Tuesday, Wednesday");
Assert.IsFalse(EquityMeanrev.EarningsAhead(thursday, friday, new DateOnly(2026, 9, 10), 3));
Assert.IsFalse(EquityMeanrev.EarningsAhead(thursday, friday, thursday.AddDays(-1), 3), "a report already out");
Assert.IsTrue(EquityMeanrev.EarningsAhead(thursday, friday, thursday, 3), "out after today's close");
}
// ---- The page -----------------------------------------------------------------------------------------------
/// <summary>
/// The switch changes only from the settings form: the programs' interface refuses it; with real money, only measuring
/// asks for the phrase and the password; acting again is free; each change writes one line in the diary.
/// </summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheSwitchChangesOnlyFromTheSettingsWithTheProtectionsOfTheRows()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true);
var password = await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
async Task<string> Switch(string value, params (string, string)[] more)
{
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + ExternalRules.Setting.Key, [("ritorno", "/impostazioni#notizie"), ("valore", value), .. more]);
return ServerHarness.Location(answer);
}
var page = await server.TextAsync("/impostazioni");
StringAssert.Contains(page, "Notizie, calendario e trimestrali");
StringAssert.Contains(page, "Le righe qui sotto valgono quando le regole sono attive.");
StringAssert.Contains(await server.TextAsync("/notizie"), "Archivio: le notizie non cambiano nessuna decisione. Qui vedi cosa avrebbe fatto ogni regola.");
Assert.AreEqual("/impostazioni#notizie", await Switch(ExternalRules.Active), "acting is always free");
Assert.AreEqual(ExternalRules.Active, (await services.Settings.GetAsync(ExternalRules.Setting.Key)).Value);
Assert.DoesNotContain("Archivio: le notizie", await server.TextAsync("/notizie"));
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = 'crypto_trend'"));
StringAssert.Contains(await server.TextAsync("/impostazioni"), "per misurare soltanto le regole servono la frase e la password");
StringAssert.Contains(await Switch(ExternalRules.Measured), "errore=frase-rischio");
StringAssert.Contains(await Switch(ExternalRules.Measured, ("frase", StageBook.RaisePhrase), ("password", "wrong-password-1")), "errore=password-rischio");
Assert.AreEqual(ExternalRules.Active, (await services.Settings.GetAsync(ExternalRules.Setting.Key)).Value);
Assert.AreEqual("/impostazioni#notizie", await Switch(ExternalRules.Measured, ("frase", StageBook.RaisePhrase), ("password", password)));
Assert.AreEqual(ExternalRules.Measured, (await services.Settings.GetAsync(ExternalRules.Setting.Key)).Value);
var lines = await services.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = @c ORDER BY occurred_at, id", r => r.Text("message"), ("c", ExternalRules.Changed)));
Assert.HasCount(2, lines);
StringAssert.Contains(lines[1], "da «attive» a «solo misurate»");
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
using var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + ExternalRules.Setting.Key, UriKind.Relative))
{ Content = JsonContent.Create(new { value = ExternalRules.Active }) };
request.Headers.Add(csrf!["header"], csrf["token"]);
using var put = await server.Http.SendAsync(request);
Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, put.StatusCode);
StringAssert.Contains(await put.Content.ReadAsStringAsync(), "usa_le_impostazioni");
}
}
+1 -1
View File
@@ -527,7 +527,7 @@ public sealed partial class NewsAnalystTests
}
// SOL held on OKX, ETH and ADA in the catalog and not watched.
private static async Task<(ManualClock Clock, SettingsStore Settings, Dictionary<string, InstrumentSpec> Specs)> SetUpAsync(Database db)
internal static async Task<(ManualClock Clock, SettingsStore Settings, Dictionary<string, InstrumentSpec> Specs)> SetUpAsync(Database db)
{
var clock = new ManualClock(Now);
var specs = new[] { "SOL-EUR", "ETH-EUR", "ADA-EUR" }.ToDictionary(s => s[..3], s => MarketDataStoreTests.Okx(s));
+8 -8
View File
@@ -104,16 +104,16 @@ public sealed class NewsScreenTests
var page = await server.TextAsync("/notizie");
foreach (var text in new[]
{
"312 notizie lette nelle ultime 24 ore, 2 con un effetto in corso.", "Con effetto, 2", "Sulle tue posizioni, 9", "Tutte, 312",
"Oggi 06:10, da CoinDesk", "Cosa ho fatto:</strong> per 24 ore non aumento la posizione su SOL. Lo stop resta dov'è.",
"Neutra, evento in arrivo", "niente nuovi acquisti di mean reversion su JPM fino a martedì. La posizione di momentum resta.",
"312 notizie lette nelle ultime 24 ore, 2 su cui una regola avrebbe agito.", "Con una regola, 2", "Archivio: le notizie non cambiano nessuna decisione.", "Sulle tue posizioni, 9", "Tutte, 312",
"Oggi 06:10, da CoinDesk", "Cosa avrebbe fatto la regola:</strong> avrebbe fermato per 24 ore gli aumenti della posizione su SOL/EUR. Solo registrato.",
"Neutra, evento in arrivo", "con le regole attive niente nuovi acquisti di mean reversion su JPM prima dei conti. Solo registrato.",
"Mercato USA", "Una sola fonte", "Negativa, non confermata", "Leggermente positiva", "Importanza 3 su 5", "Importanza 2 su 5",
"niente, perché nessun'altra fonte la riportava. Ricontrollata alle 18:20: rientrata.", "Mostra le altre 3",
"niente. Riguarda il mercato nel suo insieme: le restrizioni valgono per un singolo strumento.", "Mostra le altre 3",
"Crypto: paura o avidità", "su 100, paura", "17,8", "calmo", "+0,006%", "nella norma",
"Oggi, 16:00", "Fiducia dei consumatori USA", "Impatto medio: nessun blocco",
"Martedì 13 ottobre, prima dell'apertura", "Riguarda JPM: niente mean reversion fino a martedì",
"Mercoledì 14 ottobre, 14:30", "Impatto alto: nessun nuovo ingresso dalle 14:00 alle 15:00",
"Mercoledì 28 ottobre, 19:00", "Impatto alto: nessun nuovo ingresso dalle 18:30 alle 20:00",
"Martedì 13 ottobre, prima dell'apertura", "Riguarda JPM: con le regole attive niente mean reversion fino a martedì. Solo registrato.",
"Mercoledì 14 ottobre, 14:30", "Impatto alto: con le regole attive nessun nuovo ingresso dalle 14:00 alle 15:00. Solo registrato.",
"Mercoledì 28 ottobre, 19:00", "Impatto alto: con le regole attive nessun nuovo ingresso dalle 18:30 alle 20:00. Solo registrato.",
"Alpaca News", "in tempo reale", "14 testate e banche centrali", "Comunicati alla SEC", "aggiornato alle 08:00",
"oggi è costato 0,04 € su un tetto di 0,50 €",
})
@@ -156,7 +156,7 @@ public sealed class NewsScreenTests
// A new installation without market data: the screen says what is missing.
var empty = await server.TextAsync("/notizie");
StringAssert.Contains(empty, "0 notizie lette nelle ultime 24 ore, nessuna con un effetto in corso.");
StringAssert.Contains(empty, "0 notizie lette nelle ultime 24 ore, nessuna su cui una regola avrebbe agito.");
StringAssert.Contains(empty, "Non leggo ancora notizie");
var store = new NewsStore(services.Db, server.Host.Clock);
+6 -6
View File
@@ -33,7 +33,7 @@ public sealed class OverviewScreenTests
"BTC/EUR", "1.299,84", "66.180", "(−7,3%)", "Vedi le altre 6",
"In simulazione, giorno 58 di 60", "In simulazione, 21 operazioni su 30", "1 posizione aperta, 21 operazioni chiuse (10 in guadagno)",
"Nessuna strategia usa soldi veri.",
"Rinviato di una settimana l'aggiornamento della rete Solana", "Negativa: per 24 ore non aumento SOL",
"Rinviato di una settimana l'aggiornamento della rete Solana", "Negativa: la regola l'avrebbe fermata, solo registrato",
"Il modello osserva e impara, ma non decide ancora.", "domenica 11 ottobre, 03:00",
"connesso, 84 ms", "PostgreSQL, 1,8 GB", "ultimo messaggio alle 08:00",
})
@@ -61,8 +61,8 @@ public sealed class OverviewScreenTests
var all = await server.TextAsync("/diario");
StringAssert.Contains(all, "Oggi, venerdì 9 ottobre");
StringAssert.Contains(all, "Ieri, giovedì 8 ottobre");
StringAssert.Contains(all, "Ho cambiato una regola per 24 ore:");
StringAssert.Contains(all, "Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana.");
StringAssert.Contains(all, "Comprate 2 AAPL a 259,80 $.");
Assert.IsFalse(all.Contains("Ho cambiato una regola", StringComparison.Ordinal), "With the rules only measured the news write no line (ADR 0027).");
StringAssert.Contains(all, "href=\"/operazioni?cerca=MSFT\"");
StringAssert.Contains(all, "Perché l'ho comprata e venduta");
Assert.IsFalse(all.Contains("(con il collegamento", StringComparison.Ordinal), "The demo's note on the link is not shown.");
@@ -79,10 +79,10 @@ public sealed class OverviewScreenTests
StringAssert.Contains(await server.TextAsync("/diario?tipo=rischio"), "Nessuna voce di questo tipo finora.");
// The search ignores case and accents, and keeps the kind chosen.
var search = await server.TextAsync("/diario?cerca=MARTEDI");
StringAssert.Contains(search, "Ho messo una restrizione fino a martedì:");
var search = await server.TextAsync("/diario?cerca=NON%20E%20ANCORA");
StringAssert.Contains(search, "non è ancora tornata sopra la media");
Assert.IsFalse(search.Contains("Alzato lo stop", StringComparison.Ordinal));
StringAssert.Contains(search, "Una voce con «MARTEDI»");
StringAssert.Contains(search, "Una voce con «NON E ANCORA»");
var none = await server.TextAsync("/diario?tipo=ordini&cerca=solana");
StringAssert.Contains(none, "Nessuna voce con «solana»");
}
@@ -859,6 +859,10 @@ public sealed class QuarterlyReviewTests
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);
// Beside the balance of the period when the rules acted, the five rules measured in the shadow (ADR 0027 point 17).
CollectionAssert.AreEqual(ShadowRules.All.Select(r => r.Key).ToList(), report.ShadowRules.Select(r => r.Key).ToList());
Assert.AreEqual("Nessun caso finora", report.ShadowRules[0].State);
}
/// <summary>The decisions of the live engine, as they are written, give the balance.</summary>