Compute the improvements of 8.7 in shadow on the examples
Each improvement is measured on the signals the bot already collects, in its own savepoint after the decision, so no order depends on it: the correlation filter, the volatility cap, the sector cap, the market filter, the entry time and the choice of the model. The laboratory shows how many cases each one has and how far to trust it. Sectors come from the SEC only with a contact given by the user. refs #74 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fb0ab223a5
commit
79bb194de0
14 files changed
+1149
-42
No files matched your search
@@ -456,6 +456,9 @@
|
||||
<p class="hint">Senza chiave di Finnhub non conosco le date delle trimestrali e la mean reversion non usa il suo filtro; senza chiave di FRED il calendario usa solo Forex Factory. Le chiavi sono gratuite.</p>
|
||||
@DataKey("FINNHUB_API_KEY", "Chiave di Finnhub")
|
||||
@DataKey("FRED_API_KEY", "Chiave di FRED")
|
||||
<h3>Settori delle società</h3>
|
||||
<p class="hint">Facoltativo. La SEC, l'ente che controlla la borsa americana, chiede a chi legge i suoi archivi un contatto, di solito un indirizzo e-mail: se lo scrivi qui va solo alla SEC, dentro ogni richiesta, e serve a conoscere il settore delle azioni per una delle migliorie in osservazione. Senza, non chiedo niente.</p>
|
||||
@DataKey(Anubis.Data.Edgar.ContactSecret, "Contatto per la SEC")
|
||||
<h3>Riunioni di Fed e BCE</h3>
|
||||
<form method="post" action="/azioni/impostazioni/@SettingsStore.CentralBankMeetings.Key" class="form">
|
||||
<AntiforgeryToken />
|
||||
|
||||
@@ -167,10 +167,31 @@
|
||||
|
||||
<section class="panel" aria-labelledby="migliorie">
|
||||
<h2 id="migliorie">Migliorie in osservazione</h2>
|
||||
<div class="empty">
|
||||
<p class="empty-title">Nessuna miglioria in osservazione.</p>
|
||||
<p>Le modifiche che potrebbero migliorare il risultato o ridurre i costi si calcolano in ombra accanto alle regole in vigore e compaiono qui con l'effetto che avrebbero avuto. Arrivano con la Fase 9.</p>
|
||||
<p class="hint">Modifiche che potrebbero migliorare il risultato o ridurre i costi. Nessuna è attiva: si calcolano accanto alle regole in vigore, su ogni segnale, e qui c'è l'effetto che avrebbero avuto. Per attivarne una servono il protocollo di validazione superato e una tua decisione.</p>
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Miglioria</th><th scope="col" class="num">Segnali esaminati</th><th scope="col" class="num">Cambiati</th><th scope="col">Effetto medio a segnale</th><th scope="col">Affidabilità</th><th scope="col">Stato</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var m in _improvements)
|
||||
{
|
||||
<tr>
|
||||
<td><strong>@m.Improvement.Name</strong><br /><span class="note">@m.Improvement.What</span>@if (m.Note is not null) {<br /><span class="note">@m.Note</span>}</td>
|
||||
<td class="num">@m.Examined</td>
|
||||
<td class="num">@(m.Lines.Max(l => l.Cases))</td>
|
||||
<td>
|
||||
@foreach (var l in m.Lines)
|
||||
{
|
||||
<div>@(l.Label is null ? "" : l.Label + ": ")@(l.Mean is { } mean ? Anubis.Learning.ImprovementText.Percent(mean) : "—")@if (l.Interval is { } i) {<span class="note"> tra @Anubis.Learning.ImprovementText.Percent(i.Low) e @Anubis.Learning.ImprovementText.Percent(i.High)</span>}</div>
|
||||
}
|
||||
</td>
|
||||
<td>@(m.Lines.Max(l => l.Cases) == 0 ? "—" : m.Trust)</td>
|
||||
<td class="@(m.Waiting ? "attention-text" : null)">@m.State</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="note">L'effetto è una quota di quanto il segnale avrebbe investito: +0,10% vuol dire un euro in più ogni mille. L'intervallo contiene il valore vero 95 volte su 100.</p>
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-labelledby="stime">
|
||||
@@ -236,6 +257,7 @@
|
||||
private DateOnly _to;
|
||||
private IReadOnlyList<string> _research = [];
|
||||
private IReadOnlyList<CostEstimate> _costs = [];
|
||||
private IReadOnlyList<Anubis.Learning.ImprovementView> _improvements = [];
|
||||
private bool _anyLive;
|
||||
private SlippageTable _table = SlippageTable.Standard;
|
||||
|
||||
@@ -258,6 +280,11 @@
|
||||
_costs = await costs.ListAsync(ct);
|
||||
_table = await costs.TableAsync(ct);
|
||||
_anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct);
|
||||
var learning = new Anubis.Learning.LearningDesk(services.Db, Clock, services.Settings);
|
||||
var champion = await learning.Models.FindAsync(Anubis.Learning.ModelStatuses.Champion, ct);
|
||||
async Task<bool> HasAsync(string secret) => (await services.Secrets.StatusAsync(secret, ct)).IsSet;
|
||||
_improvements = await learning.Shadow.LoadAsync(await HasAsync("ALPACA_API_KEY_DEMO") && await HasAsync("ALPACA_API_SECRET_DEMO"), await HasAsync(Edgar.ContactSecret),
|
||||
learning.BaseRates.ContainsKey(StrategyNames.EquityMeanrev) && champion?.Model?.Strategies.Contains(StrategyNames.EquityMeanrev) == true, ct);
|
||||
_running = _trials.Any(t => !t.IsFinished);
|
||||
_family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0];
|
||||
var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime);
|
||||
|
||||
@@ -53,7 +53,7 @@ internal static partial class Forms
|
||||
}
|
||||
|
||||
/// <summary>The optional keys of SPEC 13.5 that are not a broker's: the language model, Finnhub, FRED.</summary>
|
||||
internal static readonly IReadOnlyList<string> DataKeys = [Anubis.News.NewsModelSettings.KeySecret, "FINNHUB_API_KEY", "FRED_API_KEY"];
|
||||
internal static readonly IReadOnlyList<string> DataKeys = [Anubis.News.NewsModelSettings.KeySecret, "FINNHUB_API_KEY", "FRED_API_KEY", Anubis.Data.Edgar.ContactSecret];
|
||||
|
||||
private static async Task<IResult> SetNewsSourceAsync(Guid id, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -244,7 +244,7 @@ internal sealed record LearningView
|
||||
Anomaly = state.Aside is not null,
|
||||
Checked = state.Health is not null,
|
||||
GainOnReference = champion?.Report.AllStrategiesCounted == true,
|
||||
Found = discoveries.Found,
|
||||
Found = [.. discoveries.Found, .. discoveries.Improvements],
|
||||
News = discoveries.News,
|
||||
Story = [.. events.Reverse().Select(e => new LearningStory(DayText(DayOf(e.At), now), e.Text))],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Anubis.Brokers;
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
|
||||
namespace Anubis.Data;
|
||||
|
||||
/// <summary>The company filings of the SEC (EDGAR): the number of each ticker and the SIC code of its company.</summary>
|
||||
public static class Edgar
|
||||
{
|
||||
public const string Source = "sec_edgar";
|
||||
|
||||
/// <summary>
|
||||
/// The contact the SEC asks for in the User-Agent (API-NOTES F8). It is the user's own datum: without it no request
|
||||
/// is made, and it goes to the SEC only (ADR 0020).
|
||||
/// </summary>
|
||||
public const string ContactSecret = "SEC_CONTACT";
|
||||
|
||||
public static readonly Uri Tickers = new("https://www.sec.gov/files/company_tickers.json");
|
||||
|
||||
public static Uri Submissions(string cik) => new($"https://data.sec.gov/submissions/CIK{cik}.json");
|
||||
|
||||
/// <summary>The ten-digit number of each ticker, with the ticker as Alpaca writes it (BRK.B, not BRK-B).</summary>
|
||||
public static IReadOnlyDictionary<string, string> ParseTickers(string json)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var result = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var item in document.RootElement.EnumerateObject())
|
||||
{
|
||||
var ticker = item.Value.GetProperty("ticker").GetString()!.ToUpperInvariant().Replace('-', '.');
|
||||
result.TryAdd(ticker, item.Value.GetProperty("cik_str").GetInt64().ToString("D10", CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>The SIC code and its name; null when the company has none (a fund, a foreign filer).</summary>
|
||||
public static (string? Sic, string? Description) ParseSubmissions(string json)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
string? Text(string name) => document.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.GetString() is { Length: > 0 } text ? text : null;
|
||||
return (Text("sic") is { Length: 4 } sic && sic.All(char.IsAsciiDigit) ? sic : null, Text("sicDescription"));
|
||||
}
|
||||
|
||||
/// <summary>The value of the User-Agent; null when the contact is not something that can stand in a header.</summary>
|
||||
public static string? UserAgent(string? contact) =>
|
||||
contact?.Trim() is { Length: > 2 and <= 200 } text && text.All(c => c is > ' ' and < (char)127) ? $"{AnubisInfo.Name}/{AnubisInfo.Version} {text}" : null;
|
||||
}
|
||||
|
||||
/// <summary>The sectors of the companies of the stock universe, refreshed a few at a time (SPEC 8.7).</summary>
|
||||
public sealed class CompanySectors(Database db, IClock clock)
|
||||
{
|
||||
/// <summary>A company changes sector rarely: each one is read again after this long.</summary>
|
||||
public static readonly TimeSpan MaxAge = TimeSpan.FromDays(90);
|
||||
|
||||
/// <summary>The major group: the first two digits of the SIC code.</summary>
|
||||
public static string GroupOf(string sic)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sic);
|
||||
return sic.Length >= 2 ? sic[..2] : sic;
|
||||
}
|
||||
|
||||
/// <summary>The major group of each symbol that has one.</summary>
|
||||
public async Task<IReadOnlyDictionary<string, string>> GroupsAsync(CancellationToken cancellationToken) =>
|
||||
(await db.ReadAsync(s => s.QueryAsync("SELECT symbol, sic FROM company_sectors WHERE sic IS NOT NULL", r => (r.Text("symbol"), r.Text("sic"))), cancellationToken).ConfigureAwait(false))
|
||||
.ToDictionary(r => r.Item1, r => GroupOf(r.Item2), StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Reads the sectors missing or old among <paramref name="symbols"/>. Returns how many it read.</summary>
|
||||
public async Task<int> RefreshAsync(ApiHttp http, string userAgent, IReadOnlyCollection<string> symbols, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(http);
|
||||
ArgumentNullException.ThrowIfNull(symbols);
|
||||
var now = clock.UtcNow;
|
||||
var known = (await db.ReadAsync(s => s.QueryAsync("SELECT symbol, updated_at FROM company_sectors", r => (r.Text("symbol"), r.Moment("updated_at"))), cancellationToken).ConfigureAwait(false))
|
||||
.ToDictionary(r => r.Item1, r => r.Item2, StringComparer.Ordinal);
|
||||
var due = symbols.Where(s => !known.TryGetValue(s, out var at) || now - at > MaxAge).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList();
|
||||
if (due.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The SEC allows ten requests a second: half of it.
|
||||
var limiter = new RateLimiter(clock, 5, TimeSpan.FromSeconds(1));
|
||||
var headers = new Dictionary<string, string> { ["User-Agent"] = userAgent };
|
||||
var ciks = Edgar.ParseTickers(await http.GetStringAsync(Edgar.Tickers, limiter, headers, cancellationToken).ConfigureAwait(false));
|
||||
foreach (var symbol in due)
|
||||
{
|
||||
var cik = ciks.GetValueOrDefault(symbol);
|
||||
var body = cik is null ? null : await http.GetBytesAsync(Edgar.Submissions(cik), limiter, headers, cancellationToken).ConfigureAwait(false);
|
||||
var (sic, description) = body is null ? (null, null) : Edgar.ParseSubmissions(System.Text.Encoding.UTF8.GetString(body));
|
||||
await db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO company_sectors (id, symbol, cik, sic, description, created_at, updated_at) VALUES (@id, @sy, @c, @s, @d, @now, @now) " +
|
||||
"ON CONFLICT (symbol) DO UPDATE SET cik = excluded.cik, sic = excluded.sic, description = excluded.description, updated_at = excluded.updated_at", cancellationToken,
|
||||
("id", Ids.NewId(clock)), ("sy", symbol), ("c", cik), ("s", sic), ("d", description), ("now", clock.UtcNow)), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return due.Count;
|
||||
}
|
||||
}
|
||||
@@ -219,6 +219,31 @@ public sealed partial class MarketDataService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sectors of the companies from the SEC (SPEC 8.7). Without the user's contact, which the SEC asks for in the
|
||||
/// request, nothing is asked.
|
||||
/// </summary>
|
||||
public async Task RefreshSectorsAsync(IReadOnlyCollection<string> symbols, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Offline || symbols.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (Edgar.UserAgent(await _secrets.RevealAsync(Edgar.ContactSecret, cancellationToken).ConfigureAwait(false)) is not { } agent)
|
||||
{
|
||||
await _states.RecordAsync(Edgar.Source, enabled: false, success: false, null,
|
||||
"Spento: manca il contatto che la SEC chiede nelle richieste (Impostazioni, Notizie e calendario). I settori delle società non si conoscono.", cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await StepAsync(Edgar.Source, async () =>
|
||||
{
|
||||
var read = await new CompanySectors(_db, _clock).RefreshAsync(new ApiHttp(_http, _clock, Edgar.Source), agent, symbols, cancellationToken).ConfigureAwait(false);
|
||||
return $"settori: {read} letti";
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>One round of the long work, in order; each step records its outcome and never stops the next.</summary>
|
||||
public async Task HistoryRoundAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -2,3 +2,35 @@
|
||||
-- one euro. Empty for prices in euro, for executions recorded before this migration and when no rate was known.
|
||||
|
||||
ALTER TABLE fills ADD COLUMN fx_rate {money};
|
||||
|
||||
-- The improvements in observation (SPEC 8.7): one row for each signal an improvement looked at, what it would have done
|
||||
-- with it (factor: 1 nothing, 0 no entry) and, once the operation of the signal is over, the effect on it as a share of
|
||||
-- what it would have invested. Nothing here changes a decision.
|
||||
CREATE TABLE shadow_cases (
|
||||
id {uuid} PRIMARY KEY,
|
||||
improvement TEXT NOT NULL,
|
||||
strategy TEXT NOT NULL,
|
||||
symbol TEXT NOT NULL,
|
||||
decided_day TEXT NOT NULL,
|
||||
decision_id {uuid},
|
||||
factor {float} NOT NULL,
|
||||
data {json} NOT NULL,
|
||||
effect {float},
|
||||
measured_at {timestamp},
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL,
|
||||
UNIQUE (improvement, strategy, symbol, decided_day)
|
||||
){strict};
|
||||
|
||||
CREATE INDEX shadow_cases_open ON shadow_cases (measured_at);
|
||||
|
||||
-- The sector of a company as the SEC files it (SIC code); sic is empty when the SEC does not know the symbol.
|
||||
CREATE TABLE company_sectors (
|
||||
id {uuid} PRIMARY KEY,
|
||||
symbol TEXT NOT NULL UNIQUE,
|
||||
cik TEXT,
|
||||
sic TEXT,
|
||||
description TEXT,
|
||||
created_at {timestamp} NOT NULL,
|
||||
updated_at {timestamp} NOT NULL
|
||||
){strict};
|
||||
@@ -32,6 +32,9 @@ public sealed record DiscoverySet
|
||||
public IReadOnlyList<Discovery> Found { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<NewsImpact> News { get; init; } = [];
|
||||
|
||||
/// <summary>What the improvements in observation would have been worth (SPEC 8.7).</summary>
|
||||
public IReadOnlyList<Discovery> Improvements { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -198,11 +201,13 @@ public sealed class DiscoveryDesk(Database db, IClock clock, LearningStore store
|
||||
public async Task<DiscoverySet> LatestAsync(CancellationToken cancellationToken) =>
|
||||
await store.StateAsync<DiscoverySet>(DiscoverySet.Key, cancellationToken).ConfigureAwait(false) ?? new DiscoverySet();
|
||||
|
||||
public async Task RefreshAsync(CancellationToken cancellationToken)
|
||||
public Task RefreshAsync(CancellationToken cancellationToken) => RefreshAsync([], cancellationToken);
|
||||
|
||||
public async Task RefreshAsync(IReadOnlyList<Discovery> improvements, CancellationToken cancellationToken)
|
||||
{
|
||||
var found = DiscoveryFinder.Of(await store.AllAsync(cancellationToken).ConfigureAwait(false));
|
||||
var news = await NewsAsync(cancellationToken).ConfigureAwait(false);
|
||||
var set = new DiscoverySet { At = clock.UtcNow, Found = found, News = news };
|
||||
var set = new DiscoverySet { At = clock.UtcNow, Found = found, News = news, Improvements = improvements };
|
||||
await db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, DiscoverySet.Key, set, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,9 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
|
||||
|
||||
public ModelStore Models { get; } = new(db);
|
||||
|
||||
/// <summary>The improvements in observation (SPEC 8.7).</summary>
|
||||
public ShadowDesk Shadow { get; } = new(db, clock, new LearningStore(db, clock));
|
||||
|
||||
/// <summary>The file of the first model; the one built into the program unless a test gives another.</summary>
|
||||
public FirstModelFile? First { get; init; } = FirstModel.Embedded;
|
||||
|
||||
@@ -214,7 +217,8 @@ public sealed partial class LearningDesk(Database db, IClock clock, SettingsStor
|
||||
var specs = data.Tradable.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal);
|
||||
var outside = await OrAsync(() => _outside.ReadAsync(at, specs, earnings, cancellationToken), () => Task.FromResult(OutsideView.Nothing)).ConfigureAwait(false);
|
||||
var gate = await OrAsync(() => GateAsync(cancellationToken), () => Task.FromResult(ModelGate.None)).ConfigureAwait(false);
|
||||
return new LearningTurn(strategy, stage, day, known, outside, gate, clock, ex => LogFailed(_logger, ex, strategy));
|
||||
var shadow = await OrAsync(() => Shadow.InputAsync(strategy, day, cancellationToken), () => Task.FromResult(ShadowInput.Nothing)).ConfigureAwait(false);
|
||||
return new LearningTurn(strategy, stage, day, known, outside, gate, clock, ex => LogFailed(_logger, ex, strategy), shadow, create);
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Learning left out of the decision of {Strategy}")]
|
||||
@@ -284,9 +288,12 @@ public sealed class LearningTurn
|
||||
private readonly IClock _clock;
|
||||
private readonly Action<Exception> _failed;
|
||||
private readonly CaseCollector _collector;
|
||||
private readonly OutsideView _outside;
|
||||
private readonly ShadowTurn _shadow;
|
||||
private readonly Dictionary<string, IReadOnlyList<ModelEstimate>> _estimates = new(StringComparer.Ordinal);
|
||||
|
||||
internal LearningTurn(string strategy, string stage, DateOnly day, IReadOnlyList<Example> live, OutsideView outside, ModelGate gate, IClock clock, Action<Exception> failed)
|
||||
internal LearningTurn(string strategy, string stage, DateOnly day, IReadOnlyList<Example> live, OutsideView outside, ModelGate gate, IClock clock, Action<Exception> failed,
|
||||
ShadowInput shadow, Func<IStrategy> create)
|
||||
{
|
||||
_strategy = strategy;
|
||||
_stage = stage;
|
||||
@@ -295,19 +302,31 @@ public sealed class LearningTurn
|
||||
_gate = gate;
|
||||
_clock = clock;
|
||||
_failed = failed;
|
||||
_outside = outside;
|
||||
_collector = new CaseCollector(strategy, (_, intent) => IsNew(intent.Symbol), outside, day);
|
||||
_shadow = new ShadowTurn(strategy, day, _collector, shadow, ProbabilityOf, create);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The correctives with the steps of learning around them: the examples are noted on what the strategy proposed, the
|
||||
/// multiplier comes after every other corrective and before risk.
|
||||
/// multiplier comes after every other corrective and before risk. The improvements in observation look at both ends and
|
||||
/// change nothing (SPEC 8.7).
|
||||
/// </summary>
|
||||
public IReadOnlyList<IIntentStage> Around(IReadOnlyList<IIntentStage> correctives)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(correctives);
|
||||
return [new SafeStage(_collector, _failed), .. correctives, new SafeStage(new ModelFilter(MultiplierOf), _failed)];
|
||||
return
|
||||
[
|
||||
new SafeStage(_collector, _failed), new SafeStage(_shadow.OnProposals, _failed), .. correctives,
|
||||
new SafeStage(new ModelFilter(MultiplierOf), _failed), new SafeStage(_shadow.OnFinal, _failed),
|
||||
];
|
||||
}
|
||||
|
||||
// What the model in charge would say of an entry that was not made.
|
||||
private double? ProbabilityOf(StrategyContext context, Intent intent) =>
|
||||
_gate.Estimate(new Example(Guid.Empty, _strategy, intent.Symbol, CaseSources.Live, context.Day, context.Now, intent.Reason, intent.TargetWeight ?? 0m, intent.Stop, intent.StopOffset,
|
||||
Clues.Of(_strategy, context, intent, _outside))).FirstOrDefault(e => e.InCharge)?.Probability;
|
||||
|
||||
private bool IsNew(string symbol) => _live[symbol].LastOrDefault() is not { } previous || !previous.IsOpenAfter(_day);
|
||||
|
||||
private double MultiplierOf(StrategyContext context, string symbol)
|
||||
@@ -351,10 +370,16 @@ public sealed class LearningTurn
|
||||
public async Task WriteAsync(DbSession s, Guid decisionId, Guid? account, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(s);
|
||||
await ApartAsync(s, () => WriteCasesAsync(s, decisionId, account, now, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
await ApartAsync(s, () => ShadowDesk.WriteAsync(s, _clock, decisionId, _shadow, _strategy, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ApartAsync(DbSession s, Func<Task> write, CancellationToken cancellationToken)
|
||||
{
|
||||
await s.ExecuteAsync("SAVEPOINT learning", cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await WriteCasesAsync(s, decisionId, account, now, cancellationToken).ConfigureAwait(false);
|
||||
await write().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
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;
|
||||
|
||||
/// <summary>An improvement in observation (SPEC 8.7): what it changes and for which strategies.</summary>
|
||||
public sealed record Improvement(string Key, string Name, string What, IReadOnlyList<string> Strategies);
|
||||
|
||||
/// <summary>The five of SPEC 8.7. None of them changes a decision: they are only computed beside the rules in force.</summary>
|
||||
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";
|
||||
|
||||
/// <summary>The yearly volatility of the whole portfolio above which the new entries would shrink.</summary>
|
||||
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<Improvement> 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]),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>What an improvement would have done with a signal. A factor of 1 leaves it as it is.</summary>
|
||||
public sealed record ShadowCase(string Improvement, string Strategy, string Symbol, DateOnly Day, double Factor, IReadOnlyDictionary<string, double> Numbers)
|
||||
{
|
||||
/// <summary>The entry that would have taken its place (the choice with the model).</summary>
|
||||
public ShadowEntry? Instead { get; init; }
|
||||
|
||||
/// <summary>Measured later on prices (the entry time), not on the outcome of the signal.</summary>
|
||||
public bool OnPrices { get; init; }
|
||||
}
|
||||
|
||||
public sealed record ShadowEntry(string Symbol, decimal Weight, decimal? StopOffset, string Reason, double? EarningsDays);
|
||||
|
||||
/// <summary>
|
||||
/// The portfolio of a strategy after its last decision, as returns: the daily returns its positions made in the last
|
||||
/// <see cref="Improvements.VolatilityWindow"/> days with the weights of now, as a share of the whole capital.
|
||||
/// </summary>
|
||||
public sealed record ShadowBook
|
||||
{
|
||||
/// <summary>A book older than this no longer says what the strategy holds.</summary>
|
||||
public const int MaxAgeDays = 10;
|
||||
|
||||
public string Day { get; init; } = "";
|
||||
|
||||
public IReadOnlyDictionary<string, double> Returns { get; init; } = new Dictionary<string, double>();
|
||||
|
||||
public static string KeyOf(string strategy) => "shadow_book:" + strategy;
|
||||
|
||||
public static ShadowBook Of(StrategyContext context, IReadOnlyDictionary<string, decimal> weights, decimal share)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(weights);
|
||||
var returns = new SortedDictionary<string, double>(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 };
|
||||
}
|
||||
|
||||
/// <summary>The yearly volatility of several books together; null without enough days.</summary>
|
||||
public static double? Volatility(IReadOnlyList<ShadowBook> books)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(books);
|
||||
var days = new SortedSet<string>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the improvements need from outside the decision, read before it.</summary>
|
||||
public sealed record ShadowInput(IReadOnlyList<ShadowBook> OtherBooks, IReadOnlyDictionary<string, string> Sectors)
|
||||
{
|
||||
public static readonly ShadowInput Nothing = new([], new Dictionary<string, string>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class ShadowTurn(string strategy, DateOnly day, CaseCollector collector, ShadowInput input, Func<StrategyContext, Intent, double?> probability, Func<IStrategy> create)
|
||||
{
|
||||
private readonly List<ShadowCase> _cases = [];
|
||||
|
||||
public IReadOnlyList<ShadowCase> Cases => _cases;
|
||||
|
||||
public ShadowBook? Book { get; private set; }
|
||||
|
||||
/// <summary>After the collector, on what the strategy proposed.</summary>
|
||||
public IIntentStage OnProposals => new Step(day, Proposals);
|
||||
|
||||
/// <summary>After every corrective, on what would be bought.</summary>
|
||||
public IIntentStage OnFinal => new Step(day, Final);
|
||||
|
||||
private sealed class Step(DateOnly day, Action<StrategyContext, IReadOnlyList<Intent>> look) : IIntentStage
|
||||
{
|
||||
public string Name => "shadow";
|
||||
|
||||
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> 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<Intent> 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<string, double>()) { 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<Intent> intents, HashSet<string> fresh)
|
||||
{
|
||||
var leaving = intents.Where(i => i.TargetWeight == 0m).Select(i => i.Symbol).ToHashSet(StringComparer.Ordinal);
|
||||
var count = new Dictionary<string, int>(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<Intent> intents, HashSet<string> 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<Intent> 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);
|
||||
if (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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>How many signals an improvement changed and what it would have been worth, on one alternative.</summary>
|
||||
public sealed record ImprovementLine(string? Label, int Cases, double? Mean, double? Error)
|
||||
{
|
||||
/// <summary>The interval that holds the mean effect 95 times in 100; null with too few cases.</summary>
|
||||
public (double Low, double High)? Interval => Mean is { } m && Error is { } e ? (m - (1.96 * e), m + (1.96 * e)) : null;
|
||||
}
|
||||
|
||||
/// <summary>An improvement as the pages show it.</summary>
|
||||
public sealed record ImprovementView(Improvement Improvement, int Examined, IReadOnlyList<ImprovementLine> Lines, string State, bool Waiting, string? Note)
|
||||
{
|
||||
public string Trust => Discovery.TrustOf(Lines.Count == 0 ? 0 : Lines.Max(l => l.Cases));
|
||||
}
|
||||
|
||||
/// <summary>Saves the shadow of each decision, measures it when the outcomes are known and sums it up.</summary>
|
||||
public sealed class ShadowDesk(Database db, IClock clock, LearningStore store)
|
||||
{
|
||||
/// <summary>Prices that never come (a suspended stock, a day without trades) are waited for this long.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>What the decision of a strategy needs from outside it.</summary>
|
||||
public async Task<ShadowInput> InputAsync(string strategy, DateOnly day, CancellationToken cancellationToken)
|
||||
{
|
||||
var books = new List<ShadowBook>();
|
||||
foreach (var (name, _, _) in StrategyNames.Base.Where(b => b.Name != strategy))
|
||||
{
|
||||
if (await store.StateAsync<ShadowBook>(ShadowBook.KeyOf(name), cancellationToken).ConfigureAwait(false) is { } book && book.Day.Length > 0
|
||||
&& Math.Abs(day.DayNumber - BarStore.ParseDay(book.Day).DayNumber) <= ShadowBook.MaxAgeDays)
|
||||
{
|
||||
books.Add(book);
|
||||
}
|
||||
}
|
||||
|
||||
var sectors = strategy == StrategyNames.EquityMomentum ? await _sectors.GroupsAsync(cancellationToken).ConfigureAwait(false) : new Dictionary<string, string>();
|
||||
return new ShadowInput(books, sectors);
|
||||
}
|
||||
|
||||
private sealed record Stored
|
||||
{
|
||||
public IReadOnlyDictionary<string, double> Numbers { get; init; } = new Dictionary<string, double>();
|
||||
|
||||
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)
|
||||
{
|
||||
await LearningStore.SaveStateAsync(s, clock, ShadowBook.KeyOf(strategy), book, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record Open(Guid Id, string Improvement, string Strategy, string Symbol, DateOnly Day, double Factor, Stored Data);
|
||||
|
||||
/// <summary>
|
||||
/// The effect of the cases whose outcome is known by now. Repeating it changes nothing. <paramref name="minutes"/> is
|
||||
/// null without the Alpaca keys, and the entry times wait.
|
||||
/// </summary>
|
||||
public async Task<int> MeasureAsync(Func<string, IReadOnlyList<Example>, CancellationToken, Task<LabelData?>> dataOf, IMarketCalendar? calendar,
|
||||
Func<string, DateTimeOffset, DateTimeOffset, CancellationToken, Task<IReadOnlyList<Bar>>>? 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<Stored>(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<bool> OutcomeAsync(Open o, Example example, Func<string, IReadOnlyList<Example>, CancellationToken, Task<LabelData?>> 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<string, double> { [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<bool> EntryTimeAsync(Open o, IMarketCalendar calendar, Func<string, DateTimeOffset, DateTimeOffset, CancellationToken, Task<IReadOnlyList<Bar>>> 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<string, double>
|
||||
{
|
||||
["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<int> SaveAsync(Open o, double? effect, IReadOnlyDictionary<string, double>? 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);
|
||||
|
||||
/// <summary>Every improvement with what it would have been worth so far, or what it still waits for.</summary>
|
||||
public async Task<IReadOnlyList<ImprovementView>> 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<Stored>(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<ImprovementLine> EntryLines(List<Row> 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<Row> 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.";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
internal static ImprovementLine Summary(string? label, IReadOnlyList<(DateOnly Day, double Effect)> values)
|
||||
{
|
||||
if (values.Count == 0)
|
||||
{
|
||||
return new ImprovementLine(label, 0, null, null);
|
||||
}
|
||||
|
||||
var mean = values.Average(v => v.Effect);
|
||||
if (values.Count < 2)
|
||||
{
|
||||
return new ImprovementLine(label, values.Count, mean, null);
|
||||
}
|
||||
|
||||
var n = values.Count;
|
||||
var simple = Math.Sqrt(values.Sum(v => (v.Effect - mean) * (v.Effect - mean)) / (n - 1) / n);
|
||||
var months = values.GroupBy(v => (v.Day.Year, v.Day.Month)).Select(g => g.Sum(v => v.Effect - mean)).ToList();
|
||||
var clustered = months.Count > 1 ? Math.Sqrt(months.Sum(x => x * x) * months.Count / (months.Count - 1)) / n : 0;
|
||||
return new ImprovementLine(label, n, mean, Math.Max(simple, clustered));
|
||||
}
|
||||
|
||||
/// <summary>The improvements with enough cases for a sentence, among the discoveries of SPEC 11.6.</summary>
|
||||
public static IReadOnlyList<Discovery> Discoveries(IReadOnlyList<ImprovementView> 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);
|
||||
})),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The numbers of the improvements in Italian.</summary>
|
||||
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) + "%";
|
||||
}
|
||||
}
|
||||
@@ -396,6 +396,41 @@ public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStr
|
||||
return intents;
|
||||
}
|
||||
|
||||
foreach (var c in Candidates(context))
|
||||
{
|
||||
if (slots == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (c.Distance <= 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c.Value > freeCash)
|
||||
{
|
||||
continue; // Not enough free capital for this candidate: it is dropped.
|
||||
}
|
||||
|
||||
intents.Add(c.Entry(equity));
|
||||
freeCash -= c.Value;
|
||||
slots--;
|
||||
}
|
||||
|
||||
return intents;
|
||||
}
|
||||
|
||||
/// <summary>A stock that could be bought at the next open, with the size it would have on its own.</summary>
|
||||
public sealed record Candidate(string Symbol, decimal Value, decimal Distance, double Strength)
|
||||
{
|
||||
public Intent Entry(decimal equity) => new(Symbol, Math.Round(Value / equity, 6, MidpointRounding.ToZero), Reasons.Entry) { StopOffset = Distance, Strength = Strength };
|
||||
}
|
||||
|
||||
/// <summary>Every stock with the signal of the day, the lowest RSI first: more than the free places, at times.</summary>
|
||||
public IReadOnlyList<Candidate> Candidates(StrategyContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var candidates = new List<(string Symbol, double Rsi, double Close, double Atr)>();
|
||||
foreach (var symbol in context.Universe)
|
||||
{
|
||||
@@ -418,37 +453,16 @@ public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStr
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var c in candidates.OrderBy(c => c.Rsi).ThenBy(c => c.Symbol, StringComparer.Ordinal))
|
||||
{
|
||||
if (slots == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// Risk of 0.4% of the reference equity at the stop distance, capped at 30% of the strategy's capital.
|
||||
return
|
||||
[
|
||||
.. candidates.OrderBy(c => c.Rsi).ThenBy(c => c.Symbol, StringComparer.Ordinal).Select(c =>
|
||||
{
|
||||
var distance = Math.Round((decimal)(c.Atr * _settings.AtrMultiple), 8);
|
||||
if (distance <= 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var value = _settings.RiskPerTrade * context.ReferenceEquity / distance * (decimal)c.Close;
|
||||
value = Math.Min(value, _settings.Cap * equity);
|
||||
if (value > freeCash)
|
||||
{
|
||||
continue; // Not enough free capital for this candidate: it is dropped.
|
||||
}
|
||||
|
||||
intents.Add(new Intent(c.Symbol, Math.Round(value / equity, 6, MidpointRounding.ToZero), Reasons.Entry)
|
||||
{
|
||||
StopOffset = distance,
|
||||
Strength = (_settings.EntryRsi - c.Rsi) / _settings.EntryRsi,
|
||||
});
|
||||
freeCash -= value;
|
||||
slots--;
|
||||
}
|
||||
|
||||
return intents;
|
||||
var value = distance <= 0m ? 0m : Math.Min(_settings.RiskPerTrade * context.ReferenceEquity / distance * (decimal)c.Close, _settings.Cap * context.Portfolio.Equity);
|
||||
return new Candidate(c.Symbol, value, distance, (_settings.EntryRsi - c.Rsi) / _settings.EntryRsi);
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
private string? ExitReason(StrategyContext context, string symbol, BarSeries bars, double close, int sessions)
|
||||
|
||||
@@ -632,10 +632,35 @@ public sealed partial class TradingService : IDisposable
|
||||
{
|
||||
await GuardAsync("stime di costo", () => Costs.MonthAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
await GuardAsync("stime di costo", () => RefreshCostsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
await GuardAsync("scoperte", () => Discoveries.RefreshAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
await GuardAsync("settori delle società", () => SectorsAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
await GuardAsync("migliorie in osservazione", () => MeasureShadowAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
await GuardAsync("scoperte", () => DiscoverAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// SPEC 8.7: the sectors of the stocks the momentum chooses from; no request without the contact the SEC asks for.
|
||||
private async Task SectorsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_market is { } market)
|
||||
{
|
||||
var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime);
|
||||
var members = await new UniverseStore(_db, _clock).AsOfAsync(Universes.Equity, today, cancellationToken).ConfigureAwait(false);
|
||||
await market.RefreshSectorsAsync([.. members.Select(m => m.Symbol)], cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task MeasureShadowAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var alpaca = _market is null ? null : await _market.AlpacaAsync(cancellationToken).ConfigureAwait(false);
|
||||
await Learning.Shadow.MeasureAsync(Engine.LabelDataAsync, _market?.UsCalendar, alpaca is null ? null : alpaca.FetchMinuteBarsAsync, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task DiscoverAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var views = await Learning.Shadow.LoadAsync(true, true, true, cancellationToken).ConfigureAwait(false);
|
||||
await Discoveries.RefreshAsync(Anubis.Learning.ShadowDesk.Discoveries(views), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The night of the model: once, however long the absence or the sleep of the computer (SPEC 5.6), and beside the others because it is long.</summary>
|
||||
public static ScheduledJob ModelJob(Func<CancellationToken, Task> run) =>
|
||||
new("modello", "Etichette e controllo del modello", Schedule.Daily(new TimeOnly(3, 0), Zones.Rome), run)
|
||||
|
||||
@@ -111,6 +111,13 @@ internal sealed class StockRig : IAsyncDisposable
|
||||
Engine = new LiveEngine(Rig.Db, Rig.Clock, Rig.Ledger, _stages, id => id == Alpaca.AccountId ? Manager : null, Rig.QuoteAsync, _calendar) { Earnings = earnings };
|
||||
}
|
||||
|
||||
/// <summary>The engine again, with the learning beside it.</summary>
|
||||
public void UseLearning(Learning.LearningDesk learning)
|
||||
{
|
||||
Engine.Dispose();
|
||||
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 the rules of SPEC 10.5 on single purchases.</summary>
|
||||
public void UseGate(News.IEntryGate gate)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Learning;
|
||||
using Anubis.Strategies;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>The improvements in observation of SPEC 8.7 (issue #74): computed, measured, shown, and never acting.</summary>
|
||||
[TestClass]
|
||||
public sealed class ShadowTests
|
||||
{
|
||||
private static readonly CancellationToken _none = CancellationToken.None;
|
||||
private static readonly DateOnly Monday = new(2025, 1, 6);
|
||||
|
||||
private static readonly IReadOnlyList<DateOnly> _days = StrategyData.BusinessDays(Monday, 260);
|
||||
|
||||
private static DateOnly Today => _days[^1];
|
||||
|
||||
private static BacktestInstrument Stock(string symbol, Func<int, double> close) =>
|
||||
new(StrategyData.Share(symbol), [.. _days.Select((d, i) => new DailyBar(d, close(i), close(i) * 1.01, close(i) * 0.99, close(i), 100_000))]);
|
||||
|
||||
private static StrategyContext Context(IReadOnlyList<BacktestInstrument> stocks, IReadOnlyDictionary<string, Holding>? holdings = null, DateOnly? day = null)
|
||||
{
|
||||
var data = new BacktestDataset(stocks.Any(s => s.Symbol == StrategyNames.MarketSymbol) ? stocks : [.. stocks, Stock(StrategyNames.MarketSymbol, _ => 400)], "USD");
|
||||
var at = day ?? Today;
|
||||
return new StrategyContext(at, new DateTimeOffset(at.ToDateTime(new TimeOnly(20, 20)), TimeSpan.Zero), [.. stocks.Select(s => s.Symbol)],
|
||||
new PortfolioView(10_000m, 10_000m, holdings ?? new Dictionary<string, Holding>()), s => data[s]!.SeriesThrough(at), s => data[s]?.Spec)
|
||||
{ PeriodsPerYear = 252 };
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
var collector = new CaseCollector(strategy, (_, _) => true, null, context.Day);
|
||||
var turn = new ShadowTurn(strategy, 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));
|
||||
return turn;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheFifthStockOfASectorWouldNotBeBought()
|
||||
{
|
||||
var stocks = "ABCDEFG".Select(c => Stock(c.ToString(), i => 50 + (i * 0.1))).ToList();
|
||||
var held = new Dictionary<string, Holding> { ["A"] = new(1m, 50m, null, Monday), ["B"] = new(1m, 50m, null, Monday) };
|
||||
var context = Context(stocks, held);
|
||||
var sectors = "ABCDEF".ToDictionary(c => c.ToString(), _ => "73");
|
||||
|
||||
// B leaves: A and the three strongest fill the four places, F is the fifth. G has no known sector.
|
||||
var turn = Turn(StrategyNames.EquityMomentum, context,
|
||||
[new Intent("B", 0m, "exit"), Entry("C", 4), Entry("D", 3), Entry("E", 2), Entry("F", 1), Entry("G", 0.5)], new ShadowInput([], sectors));
|
||||
var found = turn.Cases.Where(c => c.Improvement == Improvements.SectorCap).ToDictionary(c => c.Symbol, c => c.Factor);
|
||||
CollectionAssert.AreEquivalent(new[] { "C", "D", "E", "F", "G" }, found.Keys);
|
||||
Assert.AreEqual(0.0, found["F"]);
|
||||
Assert.IsTrue(found.Where(f => f.Key != "F").All(f => f.Value == 1));
|
||||
Assert.IsFalse(Turn(StrategyNames.EquityMomentum, context, [Entry("C", 4)]).Cases.Any(c => c.Improvement == Improvements.SectorCap), "without any sector there is nothing to say");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheMarketFilterLooksAtSpyAgainstItsAverage()
|
||||
{
|
||||
foreach (var (slope, expected) in new[] { (0.3, 1.0), (-0.3, 0.0) })
|
||||
{
|
||||
var context = Context([Stock("AAA", i => 50), Stock(StrategyNames.MarketSymbol, i => 400 + (i * slope))]);
|
||||
var made = Turn(StrategyNames.EquityMeanrev, context, [Entry("AAA")]).Cases.Single(c => c.Improvement == Improvements.MarketFilter);
|
||||
Assert.AreEqual(expected, made.Factor);
|
||||
}
|
||||
|
||||
// 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());
|
||||
turn.OnProposals.Apply(other, collector.Apply(other, [Entry("AAA")]));
|
||||
Assert.IsEmpty(turn.Cases);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheVolatilityOfTheWholePortfolioShrinksTheNewEntries()
|
||||
{
|
||||
// A stock that moves 2% up and down every day: 32% a year. At 100% of the momentum, 45% of the capital, it makes 14%.
|
||||
var stocks = new[] { Stock("AAA", i => i % 2 == 0 ? 100 : 102), Stock("BBB", i => 50) };
|
||||
var context = Context(stocks);
|
||||
var alone = Turn(StrategyNames.EquityMomentum, context, [Entry("AAA", weight: 1m)]);
|
||||
var own = ShadowBook.Volatility([alone.Book!])!.Value;
|
||||
Assert.AreEqual(0.45 * 0.02 * Math.Sqrt(252), own, 0.002);
|
||||
var made = alone.Cases.Single(c => c.Improvement == Improvements.VolatilityCap);
|
||||
Assert.AreEqual(Improvements.MaxVolatility / own, made.Factor, 1e-6);
|
||||
|
||||
// A small entry is left alone, unless the others already move the whole.
|
||||
var small = Turn(StrategyNames.EquityMomentum, context, [Entry("AAA", weight: 0.2m)]);
|
||||
Assert.AreEqual(1.0, small.Cases.Single(c => c.Improvement == Improvements.VolatilityCap).Factor);
|
||||
var crowded = Turn(StrategyNames.EquityMomentum, context, [Entry("AAA", weight: 0.2m)], new ShadowInput([alone.Book!], new Dictionary<string, string>()));
|
||||
Assert.IsLessThan(1.0, crowded.Cases.Single(c => c.Improvement == Improvements.VolatilityCap).Factor);
|
||||
|
||||
// A candidate is no part of the portfolio.
|
||||
var candidate = Turn(StrategyNames.StockAthBreakout, context, [Entry("AAA", weight: 1m)]);
|
||||
Assert.IsNull(candidate.Book);
|
||||
Assert.AreEqual(Improvements.EntryTime, candidate.Cases.Single().Improvement);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheModelWouldChooseOtherCandidates()
|
||||
{
|
||||
// Four stocks fall for three days above their long average; three places.
|
||||
double Dip(int i, double speed) => i < 257 ? 50 + (i * 0.3) : 50 + (256 * 0.3) - ((i - 256) * speed);
|
||||
var stocks = new[] { ("AAA", 3.0), ("BBB", 2.5), ("CCC", 2.0), ("DDD", 1.5) }.Select(s => Stock(s.Item1, i => Dip(i, s.Item2))).Append(Stock(StrategyNames.MarketSymbol, i => 400 + i)).ToList();
|
||||
var context = Context(stocks);
|
||||
var candidates = new EquityMeanrev().Candidates(context);
|
||||
Assert.HasCount(4, candidates);
|
||||
var proposed = new EquityMeanrev().Decide(context);
|
||||
Assert.HasCount(3, proposed);
|
||||
var left = candidates.Single(c => proposed.All(p => p.Symbol != c.Symbol)).Symbol;
|
||||
var worst = proposed[0].Symbol;
|
||||
|
||||
var turn = Turn(StrategyNames.EquityMeanrev, context, proposed, probability: (_, i) => i.Symbol == worst ? 0.3 : i.Symbol == left ? 0.8 : 0.5);
|
||||
var cases = turn.Cases.Where(c => c.Improvement == Improvements.ModelChoice).ToDictionary(c => c.Symbol, c => c);
|
||||
Assert.AreEqual(0.0, cases[worst].Factor);
|
||||
Assert.AreEqual(left, cases[worst].Instead!.Symbol);
|
||||
Assert.AreEqual(2, cases.Values.Count(c => c.Factor == 1 && c.Instead is null));
|
||||
|
||||
// Without a probability for each of them there is no comparison.
|
||||
Assert.IsFalse(Turn(StrategyNames.EquityMeanrev, context, proposed, probability: (_, i) => i.Symbol == left ? null : 0.5).Cases.Any(c => c.Improvement == Improvements.ModelChoice));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheEffectCountsTheMonthsNotTheSignals()
|
||||
{
|
||||
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))]);
|
||||
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("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);
|
||||
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)] }]));
|
||||
}
|
||||
|
||||
/// <summary>The same decisions with and without the shadow, also when it cannot be written; then its measure.</summary>
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheShadowChangesNoDecisionAndIsMeasuredOnce()
|
||||
{
|
||||
var from = new DateOnly(2026, 6, 1);
|
||||
var last = from.AddDays(21);
|
||||
var fills = new List<string>();
|
||||
foreach (var mode in new[] { "without", "with", "broken" })
|
||||
{
|
||||
await using var rig = await StockRig.CreateAsync(from, last);
|
||||
var desk = new LearningDesk(rig.Rig.Db, rig.Rig.Clock) { First = null };
|
||||
if (mode != "without")
|
||||
{
|
||||
rig.UseLearning(desk);
|
||||
}
|
||||
|
||||
if (mode == "broken")
|
||||
{
|
||||
await rig.Rig.Db.WriteAsync(s => s.ExecuteAsync("DROP TABLE shadow_cases", _none), _none);
|
||||
}
|
||||
|
||||
for (var day = from; day <= last; day = day.AddDays(1))
|
||||
{
|
||||
await rig.SessionAsync(day);
|
||||
}
|
||||
|
||||
fills.Add(string.Join("; ", await rig.Rig.Db.ReadAsync(s => s.QueryAsync("SELECT i.symbol, f.quantity, f.price FROM fills f JOIN instruments i ON i.id = f.instrument_id ORDER BY f.executed_at, f.id",
|
||||
r => $"{r.Text("symbol")} {r.Money("quantity")} {r.Money("price")}"), _none)));
|
||||
if (mode == "broken")
|
||||
{
|
||||
Assert.IsGreaterThan(0L, await desk.Store.CountAsync(CaseSources.Live, _none), "the examples are saved all the same");
|
||||
}
|
||||
else if (mode == "with")
|
||||
{
|
||||
await MeasureAsync(rig, desk);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsGreaterThan(50, fills[0].Length);
|
||||
Assert.AreEqual(fills[0], fills[1]);
|
||||
Assert.AreEqual(fills[0], fills[2]);
|
||||
}
|
||||
|
||||
private static async Task MeasureAsync(StockRig rig, LearningDesk desk)
|
||||
{
|
||||
var db = rig.Rig.Db;
|
||||
var before = await desk.Shadow.LoadAsync(true, true, false, _none);
|
||||
var time = before.Single(v => v.Improvement.Key == Improvements.EntryTime);
|
||||
Assert.AreEqual((int)await desk.Store.CountAsync(CaseSources.Live, _none), time.Examined, "every signal is examined");
|
||||
Assert.AreEqual(time.Examined, before.Single(v => v.Improvement.Key == Improvements.MarketFilter).Examined);
|
||||
Assert.IsGreaterThan(0, time.Examined);
|
||||
Assert.AreEqual("In attesa di un modello per la mean reversion", before.Single(v => v.Improvement.Key == Improvements.ModelChoice).State);
|
||||
|
||||
// As if the filter had stopped them all. Then the outcomes of the night and the measure, with prices that rise 1% by
|
||||
// a quarter past and 2% by half past.
|
||||
await db.WriteAsync(s => s.ExecuteAsync("UPDATE shadow_cases SET factor = 0, effect = NULL, measured_at = NULL WHERE improvement = @i", _none, ("i", Improvements.MarketFilter)), _none);
|
||||
await new LearningCycle(db, rig.Rig.Clock, desk, rig.Engine.LabelDataAsync).LabelAsync(_none);
|
||||
Task<IReadOnlyList<Bar>> Minutes(string symbol, DateTimeOffset start, DateTimeOffset until, CancellationToken ct) => Task.FromResult<IReadOnlyList<Bar>>(
|
||||
[.. Enumerable.Range(0, 35).Select(m => new Bar(start.AddMinutes(m), m < 15 ? 100 : m < 30 ? 101 : 102, 103, 99, 100, 10))]);
|
||||
Assert.IsGreaterThan(0, await desk.Shadow.MeasureAsync(rig.Engine.LabelDataAsync, new WeekdayCalendar(), Minutes, _none));
|
||||
Assert.AreEqual(0, await desk.Shadow.MeasureAsync(rig.Engine.LabelDataAsync, new WeekdayCalendar(), Minutes, _none), "once and for all");
|
||||
|
||||
var after = await desk.Shadow.LoadAsync(true, true, false, _none);
|
||||
time = after.Single(v => v.Improvement.Key == Improvements.EntryTime);
|
||||
Assert.AreEqual((100.0 / 101) - 1, time.Lines[0].Mean!.Value, 1e-6);
|
||||
Assert.AreEqual((100.0 / 102) - 1, time.Lines[1].Mean!.Value, 1e-6);
|
||||
StringAssert.Contains(time.Note, "0,00% dopo 5 minuti, +1,00% dopo 15, +2,00% dopo 30");
|
||||
var labelled = (await desk.Store.LiveAsync(StrategyNames.EquityMeanrev, _none)).Where(e => e.Label?.Result is not null).ToList();
|
||||
var filter = after.Single(v => v.Improvement.Key == Improvements.MarketFilter).Lines.Single();
|
||||
Assert.AreEqual(labelled.Count, filter.Cases);
|
||||
Assert.AreEqual(-labelled.Average(e => e.Label!.Result!.Value), filter.Mean!.Value, 1e-6, "not entering gives up the result");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheSecIsAskedOnlyWithTheContactOfTheUser()
|
||||
{
|
||||
await using var rig = await TradingRig.CreateAsync();
|
||||
var http = new FakeHttp()
|
||||
.On("company_tickers.json", """{"0":{"cik_str":320193,"ticker":"AAPL","title":"Apple Inc."},"1":{"cik_str":1067983,"ticker":"BRK-B","title":"Berkshire"}}""")
|
||||
.On("CIK0000320193.json", """{"sic":"3571","sicDescription":"Electronic Computers"}""")
|
||||
.On("CIK0001067983.json", """{"sic":"","sicDescription":""}""");
|
||||
var bus = new EventBus();
|
||||
var secrets = new SecretStore(rig.Db, rig.Clock, new byte[32]);
|
||||
using var market = new MarketDataService(rig.Db, rig.Clock, bus, new SettingsStore(rig.Db, rig.Clock, bus), secrets, null, http);
|
||||
await market.RefreshSectorsAsync(["AAPL", "BRK.B", "ZZZ"], _none);
|
||||
Assert.IsEmpty(http.Requests, "no contact, no request");
|
||||
Assert.IsFalse((await new SourceStateStore(rig.Db, rig.Clock).ListAsync(_none)).Single(s => s.Source == Edgar.Source).Enabled);
|
||||
|
||||
await secrets.SetAsync(Edgar.ContactSecret, "prova@esempio.it", "test");
|
||||
await market.RefreshSectorsAsync(["AAPL", "BRK.B", "ZZZ"], _none);
|
||||
Assert.HasCount(3, http.Requests);
|
||||
foreach (var request in http.Requests)
|
||||
{
|
||||
StringAssert.EndsWith(request.RequestUri!.Host, ".sec.gov");
|
||||
Assert.AreEqual($"Anubis/{AnubisInfo.Version} prova@esempio.it", string.Join(' ', request.Headers.NonValidated["User-Agent"]));
|
||||
}
|
||||
|
||||
var groups = await new CompanySectors(rig.Db, rig.Clock).GroupsAsync(_none);
|
||||
Assert.AreEqual("35", groups.Single().Value, "a company without a code has no sector");
|
||||
await market.RefreshSectorsAsync(["AAPL", "BRK.B", "ZZZ"], _none);
|
||||
Assert.HasCount(3, http.Requests, "known for three months");
|
||||
Assert.IsNull(Edgar.UserAgent("due parole"));
|
||||
Assert.IsNull(Edgar.UserAgent("a\r\nX-Altro:b"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheLaboratoryShowsTheImprovementsAndWhatTheyWaitFor()
|
||||
{
|
||||
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", System.Net.HttpStatusCode.NotFound));
|
||||
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
|
||||
await server.SignInFirstTimeAsync();
|
||||
var page = System.Net.WebUtility.HtmlDecode(await server.TextAsync("/laboratorio"));
|
||||
foreach (var improvement in Improvements.All)
|
||||
{
|
||||
StringAssert.Contains(page, improvement.Name);
|
||||
}
|
||||
|
||||
StringAssert.Contains(page, "In attesa delle chiavi Alpaca");
|
||||
StringAssert.Contains(page, "In osservazione");
|
||||
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Contatto per la SEC");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user