using System.Globalization;
using System.Text.Json;
using Anubis.Backtest;
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Learning;
/// An improvement in observation (SPEC 8.7): what it changes and for which strategies.
public sealed record Improvement(string Key, string Name, string What, IReadOnlyList Strategies);
/// The five of SPEC 8.7. None of them changes a decision: they are only computed beside the rules in force.
public static class Improvements
{
public const string VolatilityCap = "portfolio_vol_cap";
public const string SectorCap = "sector_cap";
public const string EntryTime = "entry_time";
public const string ModelChoice = "model_choice";
public const string MarketFilter = "meanrev_market_filter";
/// The yearly volatility of the whole portfolio above which the new entries would shrink.
public const double MaxVolatility = 0.12;
public const int VolatilityWindow = 90;
public const int MaxPerSector = 4;
public const int MarketTrend = 200;
public static readonly IReadOnlyList All =
[
new(VolatilityCap, "Tetto di volatilità del portafoglio", "Ridurre i nuovi ingressi quando la volatilità stimata di tutto il portafoglio supera il 12% annuo",
[StrategyNames.CryptoTrend, StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev]),
new(SectorCap, "Tetto per settore nel momentum", "Al massimo 4 titoli dello stesso settore (prime due cifre del codice SIC della SEC)", [StrategyNames.EquityMomentum]),
new(EntryTime, "Orario d'ingresso sulle azioni", "Comprare 15 o 30 minuti dopo l'apertura invece di 5",
[StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev, StrategyNames.StockAthBreakout]),
new(ModelChoice, "Scelta dei candidati con il modello", "Nella mean reversion, quando i candidati sono più dei posti, preferire quelli che il modello giudica più probabili", [StrategyNames.EquityMeanrev]),
new(MarketFilter, "Filtro di mercato per la mean reversion", "Entrare solo se SPY chiude sopra la sua media a 200 giorni", [StrategyNames.EquityMeanrev]),
];
}
/// What an improvement would have done with a signal. A factor of 1 leaves it as it is.
public sealed record ShadowCase(string Improvement, string Strategy, string Symbol, DateOnly Day, double Factor, IReadOnlyDictionary Numbers)
{
/// The entry that would have taken its place (the choice with the model).
public ShadowEntry? Instead { get; init; }
/// Measured later on prices (the entry time), not on the outcome of the signal.
public bool OnPrices { get; init; }
}
public sealed record ShadowEntry(string Symbol, decimal Weight, decimal? StopOffset, string Reason, double? EarningsDays);
///
/// The portfolio of a strategy after its last decision, as returns: the daily returns its positions made in the last
/// days with the weights of now, as a share of the whole capital.
///
public sealed record ShadowBook
{
/// A book older than this no longer says what the strategy holds.
public const int MaxAgeDays = 10;
public string Day { get; init; } = "";
/// The stage of the strategy at that decision: in observation the positions are only what it would hold.
public string Stage { get; init; } = "";
/// The book of the decision before, for a decision of another strategy recovered late; it has no previous of its own.
public ShadowBook? Previous { get; init; }
public IReadOnlyDictionary Returns { get; init; } = new Dictionary();
public static string KeyOf(string strategy) => "shadow_book:" + strategy;
public static ShadowBook Of(StrategyContext context, IReadOnlyDictionary weights, decimal share)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(weights);
var returns = new SortedDictionary(StringComparer.Ordinal);
foreach (var (symbol, weight) in weights.Where(w => w.Value > 0m))
{
var bars = context.Bars(symbol);
for (var i = Math.Max(1, bars.Count - Improvements.VolatilityWindow); i < bars.Count; i++)
{
var day = BarStore.DayText(bars.Day(i));
returns[day] = returns.GetValueOrDefault(day) + (bars.Close(i - 1) > 0 ? ((bars.Close(i) / bars.Close(i - 1)) - 1) * (double)(weight * share) : 0);
}
}
return new ShadowBook { Day = BarStore.DayText(context.Day), Returns = returns };
}
/// The yearly volatility of several books together; null without enough days.
public static double? Volatility(IReadOnlyList books)
{
ArgumentNullException.ThrowIfNull(books);
var days = new SortedSet(books.SelectMany(b => b.Returns.Keys), StringComparer.Ordinal);
if (days.Count < 20)
{
return null;
}
// Crypto trades every day, so the calendar with it has 365 days; the stocks alone have 252.
var weekend = days.Any(d => BarStore.ParseDay(d).DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday);
var total = days.TakeLast(Improvements.VolatilityWindow).Select(d => books.Sum(b => b.Returns.GetValueOrDefault(d))).ToArray();
var mean = total.Average();
return Math.Sqrt(total.Sum(x => (x - mean) * (x - mean)) / (total.Length - 1)) * Math.Sqrt(weekend ? 365 : 252);
}
}
/// What the improvements need from outside the decision, read before it.
public sealed record ShadowInput(IReadOnlyList OtherBooks, IReadOnlyDictionary Sectors)
{
public static readonly ShadowInput Nothing = new([], new Dictionary());
/// False when what another strategy held on that day is no longer known: the portfolio cannot be judged.
public bool Whole { get; init; } = true;
}
///
/// The improvements beside one decision. Both steps return the very list they were given: what they find is written
/// apart, and a failure of theirs changes nothing.
///
internal sealed class ShadowTurn(string strategy, string stage, DateOnly day, CaseCollector collector, ShadowInput input, Func probability, Func create)
{
private readonly List _cases = [];
public IReadOnlyList Cases => _cases;
public ShadowBook? Book { get; private set; }
/// After the collector, on what the strategy proposed.
public IIntentStage OnProposals => new Step(day, Proposals);
/// After every corrective, on what would be bought.
public IIntentStage OnFinal => new Step(day, Final);
private sealed class Step(DateOnly day, Action> look) : IIntentStage
{
public string Name => "shadow";
public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents)
{
ArgumentNullException.ThrowIfNull(context);
if (context.Day == day)
{
look(context, intents);
}
return intents;
}
}
private void Add(string improvement, string symbol, double factor, params (string Name, double Value)[] numbers) =>
_cases.Add(new ShadowCase(improvement, strategy, symbol, day, factor, numbers.Where(n => double.IsFinite(n.Value)).ToDictionary(n => n.Name, n => Math.Round(n.Value, 8), StringComparer.Ordinal)));
private void Proposals(StrategyContext context, IReadOnlyList intents)
{
var fresh = collector.Cases.Where(c => c.Day == day).Select(c => c.Symbol).ToHashSet(StringComparer.Ordinal);
if (!StrategyNames.IsCrypto(strategy))
{
foreach (var symbol in fresh.Order(StringComparer.Ordinal))
{
_cases.Add(new ShadowCase(Improvements.EntryTime, strategy, symbol, day, 1, new Dictionary()) { OnPrices = true });
}
}
if (strategy == StrategyNames.EquityMomentum && input.Sectors.Count > 0)
{
Sectors(context, intents, fresh);
}
if (strategy == StrategyNames.EquityMeanrev)
{
var market = context.Bars(StrategyNames.MarketSymbol);
if (Indicators.Sma(market, Improvements.MarketTrend) is { } average)
{
var close = market.Close(market.Count - 1);
foreach (var symbol in fresh.Order(StringComparer.Ordinal))
{
Add(Improvements.MarketFilter, symbol, close > average ? 1 : 0, ("spy", close), ("average", average));
}
}
Choice(context, intents, fresh);
}
}
private void Sectors(StrategyContext context, IReadOnlyList intents, HashSet fresh)
{
var leaving = intents.Where(i => i.TargetWeight == 0m).Select(i => i.Symbol).ToHashSet(StringComparer.Ordinal);
var count = new Dictionary(StringComparer.Ordinal);
foreach (var symbol in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m && !leaving.Contains(h.Key)).Select(h => h.Key))
{
if (input.Sectors.TryGetValue(symbol, out var sector))
{
count[sector] = count.GetValueOrDefault(sector) + 1;
}
}
// In the order of the ranking, as the strategy fills its places. A stock without a known sector is never limited.
foreach (var entry in intents.Where(i => CaseCollector.IsEntry(context, i)).OrderByDescending(i => i.Strength).ThenBy(i => i.Symbol, StringComparer.Ordinal))
{
var known = input.Sectors.TryGetValue(entry.Symbol, out var sector);
var full = known && count.GetValueOrDefault(sector!) >= Improvements.MaxPerSector;
if (known && !full)
{
count[sector!] = count.GetValueOrDefault(sector!) + 1;
}
if (fresh.Contains(entry.Symbol))
{
Add(Improvements.SectorCap, entry.Symbol, full ? 0 : 1, ("sector", known && double.TryParse(sector, CultureInfo.InvariantCulture, out var code) ? code : double.NaN));
}
}
}
private void Choice(StrategyContext context, IReadOnlyList intents, HashSet fresh)
{
var entries = intents.Where(i => CaseCollector.IsEntry(context, i)).ToList();
if (entries.Count == 0 || create() is not EquityMeanrev rules)
{
return;
}
var candidates = rules.Candidates(context).Where(c => c.Value > 0m).Select(c => c.Entry(context.Portfolio.Equity)).ToList();
if (candidates.Count <= entries.Count)
{
return;
}
// Without a probability for each of them there is no choice to compare.
var judged = new List<(Intent Intent, double Probability)>();
foreach (var c in candidates)
{
if (probability(context, c) is not { } p)
{
return;
}
judged.Add((c, p));
}
var chosen = judged.OrderByDescending(j => j.Probability).ThenBy(j => j.Intent.Symbol, StringComparer.Ordinal).Take(entries.Count).ToList();
var taken = chosen.Select(c => c.Intent.Symbol).ToHashSet(StringComparer.Ordinal);
var instead = new Queue<(Intent Intent, double Probability)>(chosen.Where(c => entries.All(e => e.Symbol != c.Intent.Symbol)));
foreach (var entry in entries)
{
var replaced = !taken.Contains(entry.Symbol) && instead.Count > 0 ? instead.Dequeue() : ((Intent Intent, double Probability)?)null;
if (!fresh.Contains(entry.Symbol))
{
continue;
}
var own = judged.FirstOrDefault(j => j.Intent.Symbol == entry.Symbol).Probability;
Add(Improvements.ModelChoice, entry.Symbol, replaced is null ? 1 : 0, ("probability", own), ("instead", replaced?.Probability ?? double.NaN));
if (replaced is { } other)
{
var days = context.NextEarnings?.Invoke(other.Intent.Symbol) is { } report ? report.DayNumber - day.DayNumber : (double?)null;
_cases[^1] = _cases[^1] with { Instead = new ShadowEntry(other.Intent.Symbol, other.Intent.TargetWeight!.Value, other.Intent.StopOffset, other.Intent.Reason, days) };
}
}
}
private void Final(StrategyContext context, IReadOnlyList intents)
{
if (StrategyPipeline.DefaultShare(strategy) is not { } share)
{
return; // A candidate is no part of the portfolio.
}
var weights = context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).ToDictionary(h => h.Key, h => BookWeights.Current(context, h.Key), StringComparer.Ordinal);
foreach (var intent in intents)
{
if (intent.TargetWeight is { } target)
{
weights[intent.Symbol] = target;
}
}
Book = ShadowBook.Of(context, weights, share) with { Stage = stage };
if (!input.Whole || ShadowBook.Volatility([Book, .. input.OtherBooks]) is not { } volatility)
{
return;
}
var factor = volatility > Improvements.MaxVolatility ? Improvements.MaxVolatility / volatility : 1;
foreach (var made in collector.Cases.Where(c => c.Day == day && weights.GetValueOrDefault(c.Symbol) > 0m))
{
Add(Improvements.VolatilityCap, made.Symbol, Math.Round(factor, 8), ("volatility", volatility));
}
}
}
/// How many signals an improvement changed and what it would have been worth, on one alternative.
public sealed record ImprovementLine(string? Label, int Cases, int Months, double? Mean, double? Error)
{
/// Fewer months than these give no interval: the signals of a month move together, so a month counts as one.
public const int MinMonths = 6;
/// What is missing for an interval, in words; null when nothing is.
public string? Missing => Cases > 0 && Months < MinMonths ? $"troppo pochi mesi per un intervallo: {Months}, ne servono {MinMonths}" : null;
/// The interval that holds the mean effect 95 times in 100; null with too few months.
public (double Low, double High)? Interval => Mean is { } m && Error is { } e && Months >= MinMonths && StudentT.Quantile(0.975, Months - 1) is var t ? (m - (t * e), m + (t * e)) : null;
}
/// An improvement as the pages show it.
public sealed record ImprovementView(Improvement Improvement, int Examined, IReadOnlyList Lines, string State, bool Waiting, string? Note)
{
/// The signals of too few months say little, however many they are.
public string Trust => Discovery.TrustOf(Lines.Where(l => l.Missing is null).Select(l => l.Cases).DefaultIfEmpty(0).Max());
}
/// Saves the shadow of each decision, measures it when the outcomes are known and sums it up.
public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
{
/// Prices that never come (a suspended stock, a day without trades) are waited for this long.
public const int PriceDays = 10;
private static readonly TimeSpan[] _times = [TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(30)];
private readonly CompanySectors _sectors = new(db, clock);
///
/// What the decision of a strategy needs from outside it. The others count as they were on : one
/// that trades looks only at those that traded too, one that only observes at what the three of them would hold.
///
public async Task InputAsync(string strategy, string stage, DateOnly day, CancellationToken cancellationToken)
{
var books = new List();
var whole = true;
foreach (var (name, _, _) in StrategyNames.Base.Where(b => b.Name != strategy))
{
if (await store.StateAsync(ShadowBook.KeyOf(name), cancellationToken).ConfigureAwait(false) is not { } last)
{
continue; // It never decided: it holds nothing.
}
if ((IsBy(last, day) ? last : last.Previous) is not { } book || !IsBy(book, day))
{
whole = false;
}
else if (day.DayNumber - BarStore.ParseDay(book.Day).DayNumber <= ShadowBook.MaxAgeDays && (stage == StrategyStages.Observation || book.Stage is not ("" or StrategyStages.Observation)))
{
books.Add(book);
}
}
var sectors = strategy == StrategyNames.EquityMomentum ? await _sectors.GroupsAsync(cancellationToken).ConfigureAwait(false) : new Dictionary();
return new ShadowInput(books, sectors) { Whole = whole };
}
private static bool IsBy(ShadowBook book, DateOnly day) => BarStore.ParseDay(book.Day) <= day;
private sealed record Stored
{
public IReadOnlyDictionary Numbers { get; init; } = new Dictionary();
public ShadowEntry? Instead { get; init; }
}
internal static async Task WriteAsync(DbSession s, IClock clock, Guid decisionId, ShadowTurn turn, string strategy, CancellationToken cancellationToken)
{
var now = clock.UtcNow;
foreach (var c in turn.Cases)
{
// A signal the improvement leaves alone needs no outcome: its effect is nothing.
var known = c.Factor >= 1 && !c.OnPrices;
await 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, @m, @now, @now) ON CONFLICT (improvement, strategy, symbol, decided_day) DO NOTHING", cancellationToken,
("id", Ids.NewId(clock)), ("i", c.Improvement), ("s", c.Strategy), ("sy", c.Symbol), ("d", BarStore.DayText(c.Day)), ("dec", decisionId), ("f", c.Factor),
("data", new DbJson(JsonSerializer.Serialize(new Stored { Numbers = c.Numbers, Instead = c.Instead }))), ("e", known ? 0.0 : null), ("m", known ? now : null), ("now", now))
.ConfigureAwait(false);
}
if (turn.Book is { } book)
{
var key = ShadowBook.KeyOf(strategy);
var json = await s.FirstOrDefaultAsync("SELECT value FROM ml_state WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false);
var kept = json is null ? null : JsonSerializer.Deserialize(json);
await LearningStore.SaveStateAsync(s, clock, key, After(kept, book), cancellationToken).ConfigureAwait(false);
}
}
// The last two days of decisions, whatever the order they were made in.
private static ShadowBook After(ShadowBook? kept, ShadowBook book)
{
var newest = new[] { book, kept, kept?.Previous }.OfType().DistinctBy(b => b.Day, StringComparer.Ordinal).OrderByDescending(b => b.Day, StringComparer.Ordinal).Take(2).ToList();
return newest[0] with { Previous = newest.Count > 1 ? newest[1] with { Previous = null } : null };
}
private sealed record Open(Guid Id, string Improvement, string Strategy, string Symbol, DateOnly Day, double Factor, Stored Data);
///
/// The effect of the cases whose outcome is known by now. Repeating it changes nothing. is
/// null without the Alpaca keys, and the entry times wait.
///
public async Task MeasureAsync(Func, CancellationToken, Task> dataOf, IMarketCalendar? calendar,
Func>>? minutes, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(dataOf);
var open = await db.ReadAsync(s => s.QueryAsync("SELECT id, improvement, strategy, symbol, decided_day, factor, data FROM shadow_cases WHERE measured_at IS NULL ORDER BY decided_day, id",
r => new Open(r.Id("id"), r.Text("improvement"), r.Text("strategy"), r.Text("symbol"), BarStore.ParseDay(r.Text("decided_day")), r.Measure("factor"),
JsonSerializer.Deserialize(r.Json("data").Text) ?? new Stored())), cancellationToken).ConfigureAwait(false);
var made = 0;
foreach (var group in open.Where(o => o.Improvement != Improvements.EntryTime).GroupBy(o => o.Strategy, StringComparer.Ordinal))
{
var labels = (await store.LiveAsync(group.Key, cancellationToken).ConfigureAwait(false)).Where(e => e.Label is not null)
.ToDictionary(e => (e.Symbol, e.Day), e => e);
foreach (var o in group)
{
if (labels.TryGetValue((o.Symbol, o.Day), out var example) && await OutcomeAsync(o, example, dataOf, cancellationToken).ConfigureAwait(false))
{
made++;
}
}
}
if (minutes is not null && calendar is not null)
{
foreach (var o in open.Where(o => o.Improvement == Improvements.EntryTime))
{
made += await EntryTimeAsync(o, calendar, minutes, cancellationToken).ConfigureAwait(false) ? 1 : 0;
}
}
return made;
}
private async Task OutcomeAsync(Open o, Example example, Func, CancellationToken, Task> dataOf, CancellationToken cancellationToken)
{
if (example.Label!.Result is not { } result)
{
await SaveAsync(o, null, null, cancellationToken).ConfigureAwait(false); // It could never start: nothing to compare.
return true;
}
if (o.Data.Instead is not { } entry)
{
await SaveAsync(o, (o.Factor - 1) * result, null, cancellationToken).ConfigureAwait(false);
return true;
}
var clues = entry.EarningsDays is { } days ? new Dictionary { [Clues.EarningsDays] = Math.Clamp(days, 0, Clues.FarReport) } : [];
var other = new Example(Guid.Empty, o.Strategy, entry.Symbol, CaseSources.Live, o.Day, example.At, entry.Reason, entry.Weight, null, entry.StopOffset, clues);
if (await dataOf(o.Strategy, [other], cancellationToken).ConfigureAwait(false) is not { } source || source.Data[other.Symbol] is not { } instrument || instrument.IndexOf(o.Day) < 0
|| CaseLabels.Of(other, source.Create, source.Data, source.Through, earnings: Clues.ReportOf(other)) is not { } label)
{
return false;
}
await SaveAsync(o, label.Result - result, null, cancellationToken).ConfigureAwait(false);
return true;
}
private async Task EntryTimeAsync(Open o, IMarketCalendar calendar, Func>> minutes,
CancellationToken cancellationToken)
{
var session = Enumerable.Range(1, 10).Select(i => calendar.SessionOn(o.Day.AddDays(i))).FirstOrDefault(s => s is not null);
if (session is null || clock.UtcNow < session.CloseUtc)
{
return false;
}
var bars = (await minutes(o.Symbol, session.OpenUtc, session.OpenUtc + _times[^1] + TimeSpan.FromMinutes(5), cancellationToken).ConfigureAwait(false)).OrderBy(b => b.OpensAt).ToList();
// The price a purchase at that moment would have found: the open of the first minute traded within the next five.
double? At(TimeSpan after) => bars.FirstOrDefault(b => b.OpensAt >= session.OpenUtc + after && b.OpensAt < session.OpenUtc + after + TimeSpan.FromMinutes(5)) is { Open: > 0 } bar ? bar.Open : null;
if (At(TimeSpan.Zero) is not { } first || At(_times[0]) is not { } at5 || At(_times[1]) is not { } at15 || At(_times[2]) is not { } at30)
{
if (clock.UtcNow < session.CloseUtc.AddDays(PriceDays))
{
return false;
}
await SaveAsync(o, null, null, cancellationToken).ConfigureAwait(false);
return true;
}
// Buying lower than five minutes after the open is worth that much of what is invested.
var numbers = new Dictionary
{
["at5"] = Math.Round((at5 / first) - 1, 8),
["at15"] = Math.Round((at15 / first) - 1, 8),
["at30"] = Math.Round((at30 / first) - 1, 8),
["gain15"] = Math.Round((at5 / at15) - 1, 8),
["gain30"] = Math.Round((at5 / at30) - 1, 8),
};
await SaveAsync(o, numbers["gain15"], numbers, cancellationToken).ConfigureAwait(false);
return true;
}
private Task SaveAsync(Open o, double? effect, IReadOnlyDictionary? numbers, CancellationToken cancellationToken) =>
db.WriteAsync(s => s.ExecuteAsync("UPDATE shadow_cases SET effect = @e, data = @d, measured_at = @now, updated_at = @now WHERE id = @id AND measured_at IS NULL", cancellationToken,
("e", effect is { } e ? Math.Round(e, 8) : null), ("d", new DbJson(JsonSerializer.Serialize(numbers is null ? o.Data : o.Data with { Numbers = numbers }))), ("now", clock.UtcNow), ("id", o.Id)),
cancellationToken);
// ---- Page ---------------------------------------------------------------------------------------------------
private sealed record Row(string Improvement, DateOnly Day, double Factor, double? Effect, Stored Data);
/// Every improvement with what it would have been worth so far, or what it still waits for.
public async Task> LoadAsync(bool alpacaKeys, bool secContact, bool meanrevModel, CancellationToken cancellationToken)
{
var rows = await db.ReadAsync(s => s.QueryAsync("SELECT improvement, decided_day, factor, effect, data FROM shadow_cases",
r => new Row(r.Text("improvement"), BarStore.ParseDay(r.Text("decided_day")), r.Measure("factor"), r.IsNull("effect") ? null : r.Measure("effect"),
JsonSerializer.Deserialize(r.Json("data").Text) ?? new Stored())), cancellationToken).ConfigureAwait(false);
return
[
.. Improvements.All.Select(improvement =>
{
var mine = rows.Where(r => r.Improvement == improvement.Key).ToList();
var waiting = mine.Count > 0 ? null : improvement.Key switch
{
Improvements.VolatilityCap => null,
_ when !alpacaKeys => "In attesa delle chiavi Alpaca",
Improvements.SectorCap when !secContact => "In attesa del contatto per la SEC",
Improvements.ModelChoice when !meanrevModel => "In attesa di un modello per la mean reversion",
_ => null,
};
return improvement.Key == Improvements.EntryTime
? new ImprovementView(improvement, mine.Count, EntryLines(mine), waiting ?? "In osservazione", waiting is not null, EntryNote(mine))
: new ImprovementView(improvement, mine.Count, [Summary(null, [.. mine.Where(r => r is { Factor: < 1, Effect: not null }).Select(r => (r.Day, r.Effect!.Value))])],
waiting ?? "In osservazione", waiting is not null, null);
}),
];
}
private static IReadOnlyList EntryLines(List rows) =>
[
.. new[] { ("A 15 minuti", "gain15"), ("A 30 minuti", "gain30") }.Select(x =>
Summary(x.Item1, [.. rows.Where(r => r.Data.Numbers.ContainsKey(x.Item2)).Select(r => (r.Day, r.Data.Numbers[x.Item2]))])),
];
private static string? EntryNote(List rows)
{
var measured = rows.Where(r => r.Data.Numbers.ContainsKey("at5")).ToList();
if (measured.Count == 0)
{
return null;
}
string Mean(string key) => ImprovementText.Percent(measured.Average(r => r.Data.Numbers[key]));
return $"Prezzo rispetto all'apertura: {Mean("at5")} dopo 5 minuti, {Mean("at15")} dopo 15, {Mean("at30")} dopo 30. Le barre al minuto non contengono lo scarto tra domanda e offerta.";
}
///
/// The mean effect and its error, over which the signals decided in the same month count as one: they move together,
/// as in the discoveries (SPEC 11.6). With few months there is no error to speak of.
///
internal static ImprovementLine Summary(string? label, IReadOnlyList<(DateOnly Day, double Effect)> values)
{
if (values.Count == 0)
{
return new ImprovementLine(label, 0, 0, null, null);
}
var n = values.Count;
var mean = values.Average(v => v.Effect);
var months = values.GroupBy(v => (v.Day.Year, v.Day.Month)).Select(g => g.Sum(v => v.Effect - mean)).ToList();
if (months.Count < ImprovementLine.MinMonths)
{
return new ImprovementLine(label, n, months.Count, mean, null);
}
// Months that happen to cancel out never make the error smaller than that of independent signals.
var simple = Math.Sqrt(values.Sum(v => (v.Effect - mean) * (v.Effect - mean)) / (n - 1) / n);
var clustered = Math.Sqrt(months.Sum(x => x * x) * months.Count / (months.Count - 1)) / n;
return new ImprovementLine(label, n, months.Count, mean, Math.Max(simple, clustered));
}
/// The improvements with enough cases for a sentence, among the discoveries of SPEC 11.6.
public static IReadOnlyList Discoveries(IReadOnlyList views)
{
ArgumentNullException.ThrowIfNull(views);
return
[
.. views.SelectMany(v => v.Lines.Where(l => l.Cases >= DiscoveryFinder.MinGroup && l.Interval is not null).Select(l =>
{
var (low, high) = l.Interval!.Value;
var name = v.Improvement.Name + (l.Label is { } label ? " (" + char.ToLowerInvariant(label[0]) + label[1..] + ")" : "");
var verdict = low > 0 ? "avrebbe aiutato" : high < 0 ? "avrebbe fatto perdere" : "non avrebbe fatto una differenza chiara";
return new Discovery($"{name}: {verdict}",
$"In media {ImprovementText.Percent(l.Mean!.Value)} a segnale, quasi certamente tra {ImprovementText.Percent(low)} e {ImprovementText.Percent(high)}. Solo in osservazione", l.Cases);
})),
];
}
}
/// The numbers of the improvements in Italian.
public static class ImprovementText
{
private static readonly CultureInfo _it = CultureInfo.GetCultureInfo("it-IT");
public static string Percent(double value)
{
var rounded = Math.Round(value * 100, 2);
return (rounded > 0 ? "+" : rounded < 0 ? "−" : "") + Math.Abs(rounded).ToString("0.00", _it) + "%";
}
}