Export the operations for the tax return
Every execution, dividend and correction of a world, with its value in euro at the ECB rate of its own Italian day or the last one before it, and for sales the cost of what was sold. Costs come from the executions of the whole account, so the method (LIFO by default, or FIFO) can be changed at any time. A missing rate leaves the cell empty and says so. The ECB download no longer leaves holes after a pause, and each execution keeps the reference rate in force when it happened (SPEC 6.8). refs #73 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3cd214ae78
commit
9d1a4f2f69
11 files changed
+890
-13
No files matched your search
@@ -319,6 +319,57 @@
|
||||
}
|
||||
<p class="hint"><a href="/api/data/quality?format=md&days=30">Rapporto sulla qualità dei dati degli ultimi 30 giorni</a></p>
|
||||
|
||||
<h3 id="dichiarazione">Esportazione per la dichiarazione</h3>
|
||||
<p class="hint">Tutte le operazioni con il controvalore in euro al cambio della BCE del giorno di ciascuna, o l'ultimo precedente. È un elenco per te o per il tuo commercialista, non un calcolo delle tasse.</p>
|
||||
@if (Shell.IsDemo)
|
||||
{
|
||||
<p class="note">Nella modalità dimostrativa non ci sono operazioni da esportare.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/azioni/impostazioni/@_taxMethod.Key" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/impostazioni#dichiarazione" />
|
||||
<label for="metodo-lotti">@Anubis.Trading.TaxExport.MethodSetting.Label</label>
|
||||
<select id="metodo-lotti" name="valore" data-autosubmit>
|
||||
<option value="lifo" selected="@(_taxMethod.Value == "lifo")">@Label("lifo")</option>
|
||||
<option value="fifo" selected="@(_taxMethod.Value == "fifo")">@Label("fifo")</option>
|
||||
</select>
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
</form>
|
||||
@if (_taxChoices.Count == 0)
|
||||
{
|
||||
<p class="note">Nessuna operazione da esportare finora.</p>
|
||||
}
|
||||
@foreach (var (world, years) in _taxChoices)
|
||||
{
|
||||
var real = world == Anubis.Trading.Worlds.Real;
|
||||
<form method="get" action="/api/dichiarazione.csv" class="form-inline">
|
||||
<input type="hidden" name="mondo" value="@(real ? "reale" : "simulazione")" />
|
||||
<label for="anno-@world">@(real ? "Soldi veri" : "Simulazione: solo per prova, non va dichiarata")</label>
|
||||
<select id="anno-@world" name="anno">
|
||||
@foreach (var year in years)
|
||||
{
|
||||
<option value="@year">@year</option>
|
||||
}
|
||||
<option value="tutti">Tutti gli anni</option>
|
||||
</select>
|
||||
<button class="btn btn-small" type="submit">Esporta le operazioni</button>
|
||||
<button class="btn btn-small" type="submit" name="dettaglio" value="lotti">Esporta il dettaglio degli acquisti venduti</button>
|
||||
</form>
|
||||
}
|
||||
<details>
|
||||
<summary>Cosa c'è e cosa non c'è</summary>
|
||||
<ul class="hint">
|
||||
<li>Il costo di ciò che vendi segue gli acquisti del solo bot su quel conto. Se sullo stesso conto compri o vendi anche a mano, il conto va rifatto insieme.</li>
|
||||
<li>Il risultato può essere diverso da quello della pagina Operazioni, che usa il prezzo medio e non gli acquisti uno per uno.</li>
|
||||
<li>I dividendi sono lordi e alla data di stacco. Ritenute e piccole commissioni di legge di Alpaca non sono nel registro: prendile dai documenti del broker.</li>
|
||||
<li>Una riga senza cambio resta vuota e lo dice nella nota; un cambio provvisorio diventa definitivo appena la BCE pubblica quello del giorno.</li>
|
||||
<li>Il capitale affidato e gli spostamenti fra strategie non sono operazioni e non ci sono.</li>
|
||||
</ul>
|
||||
</details>
|
||||
}
|
||||
|
||||
</section>
|
||||
|
||||
<section class="panel" id="notizie">
|
||||
@@ -590,6 +641,8 @@
|
||||
IReadOnlyList<StrategyCapital> Strategies);
|
||||
private sealed record LimitField(string Key, string Label, string Value, bool ReadOnly);
|
||||
private readonly List<LimitField> _limits = [];
|
||||
private SettingValue _taxMethod = new(Anubis.Trading.TaxExport.MethodSetting.Key, "lifo", false, null);
|
||||
private IReadOnlyList<(string World, IReadOnlyList<int> Years)> _taxChoices = [];
|
||||
private bool _anyLive;
|
||||
private string _pdt = "off";
|
||||
private string _scenarios = "";
|
||||
@@ -631,6 +684,8 @@
|
||||
_history = await services.Settings.HistoryAsync(null, 50, ct);
|
||||
_meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct);
|
||||
_sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct);
|
||||
_taxMethod = await services.Settings.GetAsync(Anubis.Trading.TaxExport.MethodSetting.Key, ct);
|
||||
_taxChoices = await Anubis.Trading.TaxExport.ChoicesAsync(services.Db, ct);
|
||||
foreach (var rule in Anubis.News.NewsRuleSettings.All)
|
||||
{
|
||||
_newsRules.Add(await services.Settings.GetAsync(rule.Key, ct));
|
||||
@@ -864,6 +919,8 @@
|
||||
"auto" => "Come il sistema",
|
||||
"light" => "Chiaro",
|
||||
"dark" => "Scuro",
|
||||
"lifo" => "Ultimo comprato, primo venduto (LIFO)",
|
||||
"fifo" => "Primo comprato, primo venduto (FIFO)",
|
||||
"EUR" => "Euro (EUR)",
|
||||
"USD" => "Dollaro (USD)",
|
||||
"active" => "Attivo",
|
||||
|
||||
@@ -191,6 +191,33 @@ internal static partial class Endpoints
|
||||
"text/csv; charset=utf-8", $"anubis-operazioni-{day}.csv");
|
||||
});
|
||||
|
||||
// The operations for the tax return (SPEC 4.6, 13.5): one world and one Italian year, or all of them.
|
||||
api.MapGet("/dichiarazione.csv", async (AnubisHost host, IClock clock, string? anno, string? mondo, string? dettaglio, CancellationToken ct) =>
|
||||
{
|
||||
int? year = null;
|
||||
if (!string.IsNullOrEmpty(anno) && anno != "tutti")
|
||||
{
|
||||
if (!int.TryParse(anno, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parsed) || parsed is < 1999 or > 9999)
|
||||
{
|
||||
return Error(StatusCodes.Status400BadRequest, "valore_non_valido", "L'anno non è valido.");
|
||||
}
|
||||
|
||||
year = parsed;
|
||||
}
|
||||
|
||||
if (mondo is not (null or "" or "reale" or "simulazione") || dettaglio is not (null or "" or "lotti"))
|
||||
{
|
||||
return Error(StatusCodes.Status400BadRequest, "valore_non_valido", "La scelta non è valida.");
|
||||
}
|
||||
|
||||
var world = mondo == "reale" ? Anubis.Trading.Worlds.Real : Anubis.Trading.Worlds.Simulated;
|
||||
var services = host.Services!;
|
||||
var method = Anubis.Trading.TaxExport.Method((await services.Settings.GetAsync(Anubis.Trading.TaxExport.MethodSetting.Key, ct).ConfigureAwait(false)).Value);
|
||||
var report = await Anubis.Trading.TaxExport.LoadAsync(services.Db, world, year, method, ct).ConfigureAwait(false);
|
||||
var name = $"anubis-dichiarazione-{year?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "tutti"}{(dettaglio == "lotti" ? "-lotti" : "")}{(world == Anubis.Trading.Worlds.Real ? "" : "-simulazione")}.csv";
|
||||
return Results.File(dettaglio == "lotti" ? report.LotsCsv() : report.Csv(), "text/csv; charset=utf-8", name);
|
||||
});
|
||||
|
||||
// The technical logs of the data folder as one zip (SPEC 13.6, "Diario e sistema"). They are redacted when
|
||||
// written (JsonLog); only the files the log writer names, read while it keeps writing the newest one.
|
||||
api.MapGet("/registri.zip", (AnubisHost host, ShellData shell, IClock clock) =>
|
||||
|
||||
@@ -273,7 +273,7 @@ internal static partial class Forms
|
||||
var back = Back(form, "/impostazioni");
|
||||
var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key);
|
||||
var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key);
|
||||
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key &&
|
||||
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key && key != Anubis.Trading.TaxExport.MethodSetting.Key &&
|
||||
!news && !model)
|
||||
{
|
||||
return Results.Redirect(With(back, "errore", "impostazione"));
|
||||
|
||||
@@ -206,7 +206,7 @@ public static class Format
|
||||
private static string CsvValue(object? cell) => cell switch
|
||||
{
|
||||
null => "",
|
||||
decimal d => d.ToString(CultureInfo.InvariantCulture).Replace('.', ','),
|
||||
decimal d => (d / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ','),
|
||||
double f => f.ToString("R", CultureInfo.InvariantCulture).Replace('.', ','),
|
||||
int or long => Convert.ToString(cell, CultureInfo.InvariantCulture)!,
|
||||
DateOnly date => date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
|
||||
|
||||
@@ -45,7 +45,7 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead
|
||||
public static readonly SettingDefinition TelegramStatus = new("telegram.status", "Stato periodico su Telegram", "never", ["never", "hourly", "daily"]);
|
||||
|
||||
public static readonly IReadOnlyList<SettingDefinition> All =
|
||||
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All];
|
||||
[Theme, Currency, BotState, CentralBankMeetings, TelegramStatus, Trading.TaxExport.MethodSetting, .. Risk.RiskSettings.All, Risk.Scenarios.Setting, .. News.NewsRuleSettings.All, .. News.NewsModelSettings.All, .. Learning.LearningSettings.All];
|
||||
|
||||
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
|
||||
|
||||
|
||||
@@ -47,13 +47,21 @@ public sealed class ReferenceSources(
|
||||
|
||||
private readonly MoodStore _mood = new(db, clock);
|
||||
|
||||
/// <summary>Reference rates: the whole history the first time, the last 90 days after a pause, otherwise the day's file.</summary>
|
||||
// The first answer after a start repairs what a past pause may have skipped.
|
||||
private bool _fxRepaired;
|
||||
|
||||
/// <summary>
|
||||
/// Reference rates: the whole history the first time and after a long pause, the last 90 days when a working day is
|
||||
/// missing or at the first reading after a start, otherwise the day's file. No day is ever skipped: the tax export
|
||||
/// needs the rate of each one (SPEC 4.6).
|
||||
/// </summary>
|
||||
public Task<bool> RefreshFxAsync(CancellationToken cancellationToken) => RunAsync(Ecb.Source, async () =>
|
||||
{
|
||||
var latest = await _fx.LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false);
|
||||
var today = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime);
|
||||
IReadOnlyList<FxRate> rates;
|
||||
if (latest is null)
|
||||
var expected = today.AddDays(today.DayOfWeek switch { DayOfWeek.Monday => -3, DayOfWeek.Sunday => -2, _ => -1 });
|
||||
if (latest is null || latest.Date < today.AddDays(-85))
|
||||
{
|
||||
var zip = await http.GetBytesAsync(Ecb.History, null, null, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new MarketDataException("BCE: archivio storico dei cambi non trovato.", retryable: true);
|
||||
@@ -61,11 +69,12 @@ public sealed class ReferenceSources(
|
||||
}
|
||||
else
|
||||
{
|
||||
var url = latest.Date < today.AddDays(-4) ? Ecb.Last90Days : Ecb.Daily;
|
||||
var url = !_fxRepaired || latest.Date < expected ? Ecb.Last90Days : Ecb.Daily;
|
||||
rates = Ecb.ParseXml(await http.GetStringAsync(url, null, null, cancellationToken).ConfigureAwait(false), Currencies);
|
||||
}
|
||||
|
||||
await _fx.UpsertAsync(rates, cancellationToken).ConfigureAwait(false);
|
||||
_fxRepaired = true;
|
||||
return $"{rates.Count} cambi";
|
||||
}, cancellationToken);
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
-- The reference exchange rate in force when an execution happened (SPEC 6.8): units of the instrument's currency for
|
||||
-- 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};
|
||||
@@ -107,6 +107,19 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
/// <summary>Quantities below this are zero: decimal arithmetic on 18 decimals leaves nothing larger.</summary>
|
||||
public const decimal Dust = 0.000000000001m;
|
||||
|
||||
/// <summary>The executions Anubis writes by itself, which are not trades on the market: a residue written off, an alignment chosen by the user.</summary>
|
||||
public const string ResiduePrefix = "ANURESIDUE";
|
||||
|
||||
public const string AdjustmentPrefix = "ANUADJUST";
|
||||
|
||||
private const string DividendWord = "Dividendo ";
|
||||
|
||||
/// <summary>The note of a dividend: the only place that says which stock paid it, so it is written and read here.</summary>
|
||||
public static string DividendNote(string symbol, decimal perShare) => $"{DividendWord}{symbol} {Format.Quantity(perShare)} per azione";
|
||||
|
||||
public static string? DividendSymbol(string? note) =>
|
||||
note is not null && note.StartsWith(DividendWord, StringComparison.Ordinal) ? note[DividendWord.Length..].Split(' ')[0] : null;
|
||||
|
||||
public LotMethod LotMethod { get; init; } = LotMethod.Lifo;
|
||||
|
||||
/// <summary>Gives (positive) or takes back (negative) capital to a strategy. It counts as a flow, not a result.</summary>
|
||||
@@ -171,13 +184,16 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
decimal? slippage = fill.ReferencePrice is > 0m
|
||||
? DbValues.Money((fill.Side == OrderSide.Buy ? fill.Price - fill.ReferencePrice.Value : fill.ReferencePrice.Value - fill.Price) / fill.ReferencePrice.Value * 10_000m)
|
||||
: null;
|
||||
// SPEC 6.8: the reference rate in force when it happened, as known now; the tax export uses the one published for its day.
|
||||
var rate = quoteCurrency == "EUR" ? null : await s.FirstOrDefaultAsync("SELECT rate FROM fx_rates WHERE base = 'EUR' AND quote = @q AND rate_date <= @d ORDER BY rate_date DESC",
|
||||
r => (decimal?)r.Money("rate"), ("q", quoteCurrency), ("d", Data.BarStore.DayText(Data.Zones.DayIn(fill.ExecutedAt, Data.Zones.Frankfurt)))).ConfigureAwait(false);
|
||||
var fillId = Ids.NewId(clock);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO fills (id, account_id, order_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at, strategy, reference_price, slippage_bp) " +
|
||||
"VALUES (@id, @a, @o, @i, @e, @side, @q, @p, @fee, @fc, @at, @now, @st, @ref, @slip)", cancellationToken,
|
||||
"INSERT INTO fills (id, account_id, order_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at, strategy, reference_price, slippage_bp, fx_rate) " +
|
||||
"VALUES (@id, @a, @o, @i, @e, @side, @q, @p, @fee, @fc, @at, @now, @st, @ref, @slip, @fx)", cancellationToken,
|
||||
("id", fillId), ("a", fill.AccountId), ("o", fill.OrderId), ("i", fill.InstrumentId), ("e", fill.ExecutionId), ("side", Wire.Text(fill.Side)),
|
||||
("q", fill.Quantity), ("p", fill.Price), ("fee", fill.Fee), ("fc", fill.FeeCurrency), ("at", fill.ExecutedAt), ("now", now),
|
||||
("st", fill.Strategy), ("ref", fill.ReferencePrice), ("slip", slippage)).ConfigureAwait(false);
|
||||
("st", fill.Strategy), ("ref", fill.ReferencePrice), ("slip", slippage), ("fx", rate)).ConfigureAwait(false);
|
||||
|
||||
var trade = await OpenTradeAsync(s, fill.AccountId, fill.InstrumentId, fill.Strategy).ConfigureAwait(false);
|
||||
var feeValue = feeInKind ? DbValues.Money(fill.Fee * fill.Price) : quoteFee;
|
||||
@@ -268,7 +284,7 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
}
|
||||
|
||||
var (_, quote) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false);
|
||||
var outcome = await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, "ANURESIDUE" + Ids.NewId(clock).ToString("N"), OrderSide.Sell,
|
||||
var outcome = await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, ResiduePrefix + Ids.NewId(clock).ToString("N"), OrderSide.Sell,
|
||||
position.Quantity, price, 0m, quote, clock.UtcNow)
|
||||
{ ExitReason = "residue" }, cancellationToken).ConfigureAwait(false);
|
||||
var value = DbValues.Money(position.Quantity * price);
|
||||
@@ -297,11 +313,11 @@ public sealed class Ledger(Database db, IClock clock)
|
||||
|
||||
var (_, quote) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false);
|
||||
var side = delta > 0m ? OrderSide.Buy : OrderSide.Sell;
|
||||
await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, "ANUADJUST" + Ids.NewId(clock).ToString("N"), side,
|
||||
var outcome = await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, AdjustmentPrefix + Ids.NewId(clock).ToString("N"), side,
|
||||
Math.Abs(delta), price, 0m, quote, clock.UtcNow)
|
||||
{ ExitReason = "adjustment" }, cancellationToken).ConfigureAwait(false);
|
||||
var value = DbValues.Money(delta * price);
|
||||
await AddCashAsync(s, accountId, strategy, quote, value, LedgerKinds.Adjustment, null, note, clock.UtcNow, cancellationToken).ConfigureAwait(false);
|
||||
await AddCashAsync(s, accountId, strategy, quote, value, LedgerKinds.Adjustment, outcome.FillId, note, clock.UtcNow, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
using System.Globalization;
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
|
||||
namespace Anubis.Trading;
|
||||
|
||||
public enum TaxKind
|
||||
{
|
||||
Split,
|
||||
Purchase,
|
||||
Sale,
|
||||
Dividend,
|
||||
Residue,
|
||||
Adjustment,
|
||||
Correction,
|
||||
}
|
||||
|
||||
/// <summary>An event of the ledgers as the tax export reads it. <see cref="Quantity"/> is the traded one; a split has only its ratio.</summary>
|
||||
internal sealed record TaxEvent(Guid Account, Guid? Instrument, DateTimeOffset At, TaxKind Kind, string Id)
|
||||
{
|
||||
public string Strategy { get; init; } = "";
|
||||
|
||||
public bool Entering { get; init; }
|
||||
|
||||
public decimal Quantity { get; init; }
|
||||
|
||||
public decimal Price { get; init; }
|
||||
|
||||
public decimal Fee { get; init; }
|
||||
|
||||
public string FeeCurrency { get; init; } = "";
|
||||
|
||||
/// <summary>Money of a dividend or of a correction; units per share of a split.</summary>
|
||||
public decimal Amount { get; init; }
|
||||
|
||||
public string Currency { get; init; } = "";
|
||||
|
||||
public string? Symbol { get; init; }
|
||||
|
||||
public string Note { get; init; } = "";
|
||||
}
|
||||
|
||||
internal sealed record TaxAccount(string Name, string Broker, string World);
|
||||
|
||||
internal sealed record TaxInstrument(string Symbol, string Name, string AssetClass, string? Base, string Quote);
|
||||
|
||||
/// <summary>A row of the export. Amounts in euro are null when no rate is known: never zero.</summary>
|
||||
public sealed record TaxRow(string World, string Account, DateTimeOffset At, DateOnly Day, TaxKind Kind, string Symbol, string Name, string AssetClass, string Strategy, string Id)
|
||||
{
|
||||
/// <summary>A sale or an incoming quantity, for the label of residues and adjustments.</summary>
|
||||
public bool Entering { get; init; }
|
||||
|
||||
public decimal? Quantity { get; init; }
|
||||
|
||||
public decimal? Price { get; init; }
|
||||
|
||||
public string Currency { get; init; } = "";
|
||||
|
||||
public decimal? Gross { get; init; }
|
||||
|
||||
public decimal? Fee { get; init; }
|
||||
|
||||
public string? FeeCurrency { get; init; }
|
||||
|
||||
public decimal? Rate { get; init; }
|
||||
|
||||
public DateOnly? RateDate { get; init; }
|
||||
|
||||
public decimal? GrossEur { get; init; }
|
||||
|
||||
public decimal? FeeEur { get; init; }
|
||||
|
||||
public decimal? CostEur { get; init; }
|
||||
|
||||
public decimal? ResultEur { get; init; }
|
||||
|
||||
public decimal? FxEffectEur { get; init; }
|
||||
|
||||
public bool MissingRate { get; init; }
|
||||
|
||||
public bool Provisional { get; init; }
|
||||
|
||||
public string Note { get; init; } = "";
|
||||
}
|
||||
|
||||
/// <summary>A sale and one of the purchases it consumes: the detail behind <see cref="TaxRow.CostEur"/>.</summary>
|
||||
public sealed record TaxLot(string World, string Account, string Symbol, DateOnly Bought, DateOnly Sold, decimal Quantity, decimal? CostEur, decimal? ProceedsEur, string SaleId)
|
||||
{
|
||||
public decimal? ResultEur => ProceedsEur - CostEur;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The operations for the tax return (SPEC 4.6, 6.8, 7.5): each with its value in euro at the ECB rate of its own
|
||||
/// Italian day, or the last one before it, and for sales the cost of what was sold. The costs are computed again from
|
||||
/// the executions, in the order of the purchases and for the whole account: what a strategy bought and another sold is
|
||||
/// one holding for the law. The stored lots are not used, so the method can be changed at any time (ADR 0020).
|
||||
/// </summary>
|
||||
public sealed record TaxReport(string World, int? Year, LotMethod Method, IReadOnlyList<TaxRow> Rows, IReadOnlyList<TaxLot> Lots)
|
||||
{
|
||||
public int MissingRates => Rows.Count(r => r.MissingRate);
|
||||
|
||||
public int Provisional => Rows.Count(r => r.Provisional);
|
||||
|
||||
private string MethodName => Method == LotMethod.Lifo ? "LIFO" : "FIFO";
|
||||
|
||||
private static string WorldName(string world) => world == Worlds.Real ? "soldi veri" : "simulazione";
|
||||
|
||||
private static decimal? Cents(decimal? value) => value is { } v ? Math.Round(v, 2, MidpointRounding.AwayFromZero) : null;
|
||||
|
||||
// Trailing zeros dropped, so both database engines give the same text.
|
||||
private static decimal? Plain(decimal? value) => value is { } v ? v / 1.000000000000000000000000000000000m : null;
|
||||
|
||||
public byte[] Csv() => Format.Csv(
|
||||
["Ambiente", "Conto", "Data", "Ora", "Operazione", "Strumento", "Nome", "Tipo", "Strategia", "Quantità", "Prezzo", "Valuta", "Controvalore", "Commissione", "Valuta commissione",
|
||||
"Cambio EUR/USD BCE", "Data del cambio", "Controvalore EUR", "Commissione EUR", $"Costo EUR ({MethodName})", "Risultato EUR", "Effetto cambio EUR", "Identificativo", "Nota"],
|
||||
Rows.Select(r => (IReadOnlyList<object?>)
|
||||
[
|
||||
WorldName(r.World), r.Account, r.Day, TimeZoneInfo.ConvertTime(r.At, Zones.Rome).ToString("HH:mm:ss", CultureInfo.InvariantCulture), Operation(r), r.Symbol, r.Name,
|
||||
r.AssetClass switch { "" => "", "crypto" => "crypto", _ => "azione" }, r.Strategy, Plain(r.Quantity), Plain(r.Price), r.Currency, Plain(r.Gross), Plain(r.Fee), r.FeeCurrency,
|
||||
Plain(r.Rate), r.RateDate, Cents(r.GrossEur), Cents(r.FeeEur), Cents(r.CostEur), Cents(r.ResultEur), Cents(r.FxEffectEur), r.Id, r.Note,
|
||||
]));
|
||||
|
||||
/// <summary>One row for each purchase consumed by a sale, with its own date and cost.</summary>
|
||||
public byte[] LotsCsv() => Format.Csv(
|
||||
["Ambiente", "Conto", "Strumento", "Comprato il", "Venduto il", "Quantità", $"Costo EUR ({MethodName})", "Ricavo EUR", "Risultato EUR", "Vendita"],
|
||||
Lots.Select(l => (IReadOnlyList<object?>)
|
||||
[WorldName(l.World), l.Account, l.Symbol, l.Bought, l.Sold, Plain(l.Quantity), Cents(l.CostEur), Cents(l.ProceedsEur), Cents(l.ResultEur), l.SaleId]));
|
||||
|
||||
private static string Operation(TaxRow r) => r.Kind switch
|
||||
{
|
||||
TaxKind.Purchase => "Acquisto",
|
||||
TaxKind.Sale => "Vendita",
|
||||
TaxKind.Dividend => "Dividendo",
|
||||
TaxKind.Split => "Frazionamento",
|
||||
TaxKind.Residue => "Residuo tolto dal registro",
|
||||
TaxKind.Adjustment => r.Quantity is null ? "Allineamento della liquidità" : r.Entering ? "Allineamento in entrata" : "Allineamento in uscita",
|
||||
_ => "Storno",
|
||||
};
|
||||
}
|
||||
|
||||
public static class TaxExport
|
||||
{
|
||||
public static readonly SettingDefinition MethodSetting = new("tax.lot_method", "Metodo per il costo delle vendite", "lifo", ["lifo", "fifo"]);
|
||||
|
||||
public static LotMethod Method(string value) => value == "fifo" ? LotMethod.Fifo : LotMethod.Lifo;
|
||||
|
||||
/// <summary>The worlds with an operation and the Italian years of those operations, for the choices of the page.</summary>
|
||||
public static async Task<IReadOnlyList<(string World, IReadOnlyList<int> Years)>> ChoicesAsync(Database db, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
var (accounts, _, events, _) = await ReadAsync(db, cancellationToken).ConfigureAwait(false);
|
||||
return events.GroupBy(e => accounts[e.Account].World)
|
||||
.Select(g => (g.Key, (IReadOnlyList<int>)[.. g.Select(e => Zones.DayIn(e.At, Zones.Rome).Year).Distinct().OrderDescending()]))
|
||||
.OrderBy(g => g.Key, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
/// <summary>The report of a world, for one Italian year or (null) for all of them. The costs always come from the whole history.</summary>
|
||||
public static async Task<TaxReport> LoadAsync(Database db, string world, int? year, LotMethod method, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
var (accounts, instruments, events, rates) = await ReadAsync(db, cancellationToken).ConfigureAwait(false);
|
||||
var (rows, lots) = Build(events.Where(e => accounts[e.Account].World == world), accounts, instruments, rates, method);
|
||||
return new TaxReport(world, year, method, [.. rows.Where(r => year is null || r.Day.Year == year)], [.. lots.Where(l => year is null || l.Sold.Year == year)]);
|
||||
}
|
||||
|
||||
private static Task<(Dictionary<Guid, TaxAccount> Accounts, Dictionary<Guid, TaxInstrument> Instruments, List<TaxEvent> Events, List<FxRate> Rates)> ReadAsync(
|
||||
Database db, CancellationToken cancellationToken) =>
|
||||
db.ReadAsync(async s =>
|
||||
{
|
||||
var accounts = (await s.QueryAsync("SELECT id, name, broker, environment FROM accounts",
|
||||
r => (Id: r.Id("id"), Account: new TaxAccount(r.Text("name"), r.Text("broker"), TradingEnvironments.World(r.Text("environment"))))).ConfigureAwait(false))
|
||||
.ToDictionary(a => a.Id, a => a.Account);
|
||||
var instruments = (await s.QueryAsync("SELECT id, symbol, name, asset_class, base_currency, quote_currency FROM instruments",
|
||||
r => (Id: r.Id("id"), Instrument: new TaxInstrument(r.Text("symbol"), r.TextOrNull("name") ?? "", r.Text("asset_class"), r.TextOrNull("base_currency"), r.Text("quote_currency"))))
|
||||
.ConfigureAwait(false)).ToDictionary(i => i.Id, i => i.Instrument);
|
||||
var events = (await s.QueryAsync(
|
||||
"SELECT id, account_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, strategy FROM fills ORDER BY executed_at, id",
|
||||
r => new TaxEvent(r.Id("account_id"), r.Id("instrument_id"), r.Moment("executed_at"),
|
||||
r.Text("execution_id") is var e && e.StartsWith(Ledger.ResiduePrefix, StringComparison.Ordinal) ? TaxKind.Residue
|
||||
: e.StartsWith(Ledger.AdjustmentPrefix, StringComparison.Ordinal) ? TaxKind.Adjustment
|
||||
: Wire.Side(r.Text("side")) == OrderSide.Buy ? TaxKind.Purchase : TaxKind.Sale,
|
||||
e)
|
||||
{
|
||||
Strategy = r.TextOrNull("strategy") ?? "",
|
||||
Entering = Wire.Side(r.Text("side")) == OrderSide.Buy,
|
||||
Quantity = r.Money("quantity"),
|
||||
Price = r.Money("price"),
|
||||
Fee = r.Money("fee"),
|
||||
FeeCurrency = r.Text("fee_currency"),
|
||||
}).ConfigureAwait(false)).ToList();
|
||||
|
||||
// The counterpart of a quantity aligned by the user is already in its execution. Rows written before the
|
||||
// link between the two existed are recognised by account, strategy, instant and value.
|
||||
var aligned = events.Where(e => e.Kind == TaxKind.Adjustment).Select(e => (e.Account, e.Strategy, e.At.ToUnixTimeSeconds(), DbValues.Money(e.Entering ? e.Quantity * e.Price : -e.Quantity * e.Price))).ToHashSet();
|
||||
var cash = await s.QueryAsync(
|
||||
"SELECT id, account_id, strategy, currency, amount, kind, fill_id, note, occurred_at FROM cash_ledger WHERE kind IN ('dividend', 'reversal', 'adjustment') ORDER BY occurred_at, id",
|
||||
r => (Fill: r.IdOrNull("fill_id"), Event: new TaxEvent(r.Id("account_id"), null, r.Moment("occurred_at"), r.Text("kind") switch
|
||||
{
|
||||
LedgerKinds.Dividend => TaxKind.Dividend,
|
||||
LedgerKinds.Adjustment => TaxKind.Adjustment,
|
||||
_ => TaxKind.Correction,
|
||||
}, r.Id("id").ToString("N"))
|
||||
{
|
||||
Strategy = r.TextOrNull("strategy") ?? "",
|
||||
Amount = r.Money("amount"),
|
||||
Currency = r.Text("currency"),
|
||||
Note = r.TextOrNull("note") ?? "",
|
||||
Symbol = r.Text("kind") == LedgerKinds.Dividend ? Ledger.DividendSymbol(r.TextOrNull("note")) : null,
|
||||
})).ConfigureAwait(false);
|
||||
events.AddRange(cash.Where(c => c.Event.Kind != TaxKind.Adjustment ||
|
||||
(c.Fill is null && !aligned.Contains((c.Event.Account, c.Event.Strategy, c.Event.At.ToUnixTimeSeconds(), c.Event.Amount)))).Select(c => c.Event));
|
||||
|
||||
var applied = await s.QueryAsync("SELECT a.account_id, a.source_key, c.symbol, c.ex_date, c.ratio FROM applied_actions a JOIN corporate_actions c ON c.source_key = a.source_key",
|
||||
r => (Account: r.Id("account_id"), Key: r.Text("source_key"), Symbol: r.Text("symbol"), Day: BarStore.ParseDay(r.Text("ex_date")), Ratio: r.MoneyOrNull("ratio"))).ConfigureAwait(false);
|
||||
foreach (var split in applied.Where(a => a.Ratio is > 0m))
|
||||
{
|
||||
// The instrument of that account with this symbol: the one that was traded there.
|
||||
foreach (var instrument in events.Where(e => e.Account == split.Account && e.Instrument is { } i && instruments[i].Symbol == split.Symbol).Select(e => e.Instrument!.Value).Distinct().ToList())
|
||||
{
|
||||
events.Add(new TaxEvent(split.Account, instrument, new DateTimeOffset(split.Day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), TaxKind.Split, split.Key) { Amount = split.Ratio!.Value });
|
||||
}
|
||||
}
|
||||
|
||||
var rates = await s.QueryAsync("SELECT base, quote, rate_date, rate, source FROM fx_rates WHERE base = 'EUR' ORDER BY quote, rate_date",
|
||||
r => new FxRate(r.Text("base"), r.Text("quote"), BarStore.ParseDay(r.Text("rate_date")), r.Money("rate"), r.Text("source"))).ConfigureAwait(false);
|
||||
return (accounts, instruments, events, rates.ToList());
|
||||
}, cancellationToken);
|
||||
|
||||
private sealed class Lot(DateTimeOffset at, decimal units, decimal cost, decimal? costEur)
|
||||
{
|
||||
public DateTimeOffset At { get; } = at;
|
||||
|
||||
public decimal Units { get; set; } = units;
|
||||
|
||||
public decimal Cost { get; set; } = cost;
|
||||
|
||||
public decimal? CostEur { get; set; } = costEur;
|
||||
}
|
||||
|
||||
internal static (List<TaxRow> Rows, List<TaxLot> Lots) Build(IEnumerable<TaxEvent> events, IReadOnlyDictionary<Guid, TaxAccount> accounts,
|
||||
IReadOnlyDictionary<Guid, TaxInstrument> instruments, IReadOnlyList<FxRate> rates, LotMethod method)
|
||||
{
|
||||
var byCurrency = rates.GroupBy(r => r.Quote, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.OrderBy(r => r.Date).ToList(), StringComparer.Ordinal);
|
||||
var rows = new List<TaxRow>();
|
||||
var details = new List<TaxLot>();
|
||||
var held = new Dictionary<(Guid, Guid), List<Lot>>();
|
||||
|
||||
// On a tie a split comes first (it is at midnight of the ex-date, before that day's trades), then purchases.
|
||||
foreach (var e in events.OrderBy(e => e.At).ThenBy(e => e.Kind).ThenBy(e => e.Id, StringComparer.Ordinal))
|
||||
{
|
||||
var account = accounts[e.Account];
|
||||
var instrument = e.Instrument is { } id ? instruments[id] : null;
|
||||
var day = Zones.DayIn(e.At, Zones.Rome);
|
||||
var row = new TaxRow(account.World, account.Name, e.At, day, e.Kind, instrument?.Symbol ?? e.Symbol ?? "", instrument?.Name ?? "", instrument?.AssetClass ?? "", e.Strategy, e.Id)
|
||||
{
|
||||
Entering = e.Entering,
|
||||
};
|
||||
if (instrument is null)
|
||||
{
|
||||
rows.Add(Money(row, e, RateOf(e.Currency, day, byCurrency)));
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = (e.Account, e.Instrument!.Value);
|
||||
if (!held.TryGetValue(key, out var lots))
|
||||
{
|
||||
held[key] = lots = [];
|
||||
}
|
||||
|
||||
if (e.Kind == TaxKind.Split)
|
||||
{
|
||||
var before = lots.Sum(l => l.Units);
|
||||
foreach (var lot in lots)
|
||||
{
|
||||
lot.Units *= e.Amount;
|
||||
}
|
||||
|
||||
if (before > Ledger.Dust)
|
||||
{
|
||||
rows.Add(row with { Quantity = before * (e.Amount - 1m), Note = $"ogni azione diventa {Format.Quantity(e.Amount)}: il costo totale non cambia" });
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
rows.Add(Traded(row, e, instrument, RateOf(instrument.Quote, day, byCurrency), lots, method, details));
|
||||
}
|
||||
|
||||
return (rows, details);
|
||||
}
|
||||
|
||||
private static TaxRow Money(TaxRow row, TaxEvent e, RateOn rate)
|
||||
{
|
||||
var note = e.Kind switch
|
||||
{
|
||||
TaxKind.Dividend => "lordo, alla data di stacco: ritenute e data di pagamento sono nei documenti del broker",
|
||||
TaxKind.Adjustment => "correzione scelta dall'utente: non è un guadagno né una perdita",
|
||||
_ => e.Note,
|
||||
};
|
||||
return Rated(row with { Currency = e.Currency, Gross = e.Amount, GrossEur = rate.Eur(e.Amount) }, rate, note);
|
||||
}
|
||||
|
||||
private static TaxRow Traded(TaxRow row, TaxEvent e, TaxInstrument instrument, RateOn rate, List<Lot> lots, LotMethod method, List<TaxLot> details)
|
||||
{
|
||||
var coin = instrument.Base ?? (instrument.Symbol.Contains('-', StringComparison.Ordinal) ? instrument.Symbol.Split('-')[0] : null);
|
||||
var inKind = coin is not null && e.FeeCurrency == coin ? e.Fee : 0m;
|
||||
var quoteFee = e.FeeCurrency == instrument.Quote ? e.Fee : 0m;
|
||||
var gross = e.Quantity * e.Price;
|
||||
var notes = new List<string>();
|
||||
if (e.Fee > 0m && inKind == 0m && quoteFee == 0m)
|
||||
{
|
||||
notes.Add($"commissione in {e.FeeCurrency}: non è nel costo, valutala a parte");
|
||||
}
|
||||
|
||||
row = row with
|
||||
{
|
||||
Quantity = e.Quantity,
|
||||
Price = e.Price,
|
||||
Currency = instrument.Quote,
|
||||
Gross = gross,
|
||||
Fee = e.Fee,
|
||||
FeeCurrency = e.Fee > 0m ? e.FeeCurrency : null,
|
||||
GrossEur = rate.Eur(gross),
|
||||
FeeEur = e.Fee == 0m ? 0m : inKind > 0m ? rate.Eur(inKind * e.Price) : quoteFee > 0m ? rate.Eur(quoteFee) : null,
|
||||
};
|
||||
|
||||
if (e.Entering)
|
||||
{
|
||||
// A fee kept in the coin leaves fewer units for the same money.
|
||||
lots.Add(new Lot(e.At, e.Quantity - inKind, gross + quoteFee, rate.Eur(gross + quoteFee)));
|
||||
if (e.Kind == TaxKind.Adjustment)
|
||||
{
|
||||
notes.Add("quantità portata nel registro su scelta dell'utente, al prezzo di mercato: il costo vero va preso dai tuoi documenti");
|
||||
}
|
||||
|
||||
return Rated(row, rate, notes);
|
||||
}
|
||||
|
||||
var selling = e.Kind == TaxKind.Sale;
|
||||
var moved = e.Quantity + inKind;
|
||||
var proceeds = gross - quoteFee;
|
||||
var proceedsEur = rate.Eur(proceeds);
|
||||
var left = moved;
|
||||
var cost = 0m;
|
||||
decimal? costEur = 0m;
|
||||
foreach (var lot in method == LotMethod.Lifo ? Enumerable.Reverse(lots) : lots)
|
||||
{
|
||||
if (left <= Ledger.Dust)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var take = Math.Min(left, lot.Units);
|
||||
var part = take / lot.Units;
|
||||
var (lotCost, lotCostEur) = (lot.Cost * part, lot.CostEur * part);
|
||||
cost += lotCost;
|
||||
costEur += lotCostEur;
|
||||
if (selling)
|
||||
{
|
||||
details.Add(new TaxLot(row.World, row.Account, row.Symbol, Zones.DayIn(lot.At, Zones.Rome), row.Day, take, lotCostEur, proceedsEur * (take / moved), e.Id));
|
||||
}
|
||||
|
||||
(lot.Units, lot.Cost, lot.CostEur) = (lot.Units - take, lot.Cost - lotCost, lot.CostEur - lotCostEur);
|
||||
left -= take;
|
||||
}
|
||||
|
||||
lots.RemoveAll(l => l.Units <= Ledger.Dust);
|
||||
if (!selling)
|
||||
{
|
||||
notes.Add(e.Kind == TaxKind.Residue ? "resta sul conto, non è una vendita: nessun guadagno e nessuna perdita" : "tolto dal registro su scelta dell'utente: non è una vendita");
|
||||
return Rated(row, rate, notes);
|
||||
}
|
||||
|
||||
if (left > Ledger.Dust)
|
||||
{
|
||||
notes.Add("non trovo gli acquisti di tutta la quantità venduta: costo da calcolare a mano");
|
||||
return Rated(row, rate, notes);
|
||||
}
|
||||
|
||||
if (costEur is null)
|
||||
{
|
||||
notes.Add("manca il cambio di un acquisto: costo da calcolare a mano");
|
||||
}
|
||||
|
||||
return Rated(row with
|
||||
{
|
||||
CostEur = costEur,
|
||||
ResultEur = proceedsEur - costEur,
|
||||
FxEffectEur = instrument.Quote == "EUR" ? null : proceedsEur - costEur - rate.Eur(proceeds - cost),
|
||||
}, rate, notes);
|
||||
}
|
||||
|
||||
private static TaxRow Rated(TaxRow row, RateOn rate, params IEnumerable<string> notes)
|
||||
{
|
||||
var all = notes.Where(n => n.Length > 0).ToList();
|
||||
if (rate.Missing)
|
||||
{
|
||||
all.Add($"cambio della BCE mancante per {row.Currency}: importi in euro da calcolare a mano");
|
||||
}
|
||||
else if (rate.Provisional)
|
||||
{
|
||||
all.Add("cambio provvisorio: la BCE non ha ancora pubblicato quello del giorno");
|
||||
}
|
||||
|
||||
return row with { Rate = rate.Rate, RateDate = rate.Date, MissingRate = rate.Missing, Provisional = rate.Provisional, Note = string.Join("; ", all) };
|
||||
}
|
||||
|
||||
/// <summary>The rate of a day: euro needs none, an unknown one leaves the amounts empty.</summary>
|
||||
private readonly record struct RateOn(decimal? Rate, DateOnly? Date, bool Missing, bool Provisional)
|
||||
{
|
||||
public decimal? Eur(decimal amount) => Missing ? null : Rate is { } r ? amount / r : amount;
|
||||
}
|
||||
|
||||
private static RateOn RateOf(string currency, DateOnly day, Dictionary<string, List<FxRate>> rates)
|
||||
{
|
||||
if (currency == "EUR")
|
||||
{
|
||||
return new RateOn(null, null, false, false);
|
||||
}
|
||||
|
||||
var known = rates.GetValueOrDefault(currency) ?? [];
|
||||
var rate = known.LastOrDefault(r => r.Date <= day);
|
||||
return rate is null || rate.Date < day.AddDays(-EuroHistory.MaxRateAgeDays) || rate.Rate <= 0m
|
||||
? new RateOn(null, null, true, false)
|
||||
: new RateOn(rate.Rate, rate.Date, false, rate.Date < day && known[^1].Date <= day);
|
||||
}
|
||||
}
|
||||
@@ -885,7 +885,7 @@ public sealed partial class TradingService : IDisposable
|
||||
{
|
||||
var amount = Math.Round(quantity * action.CashAmount!.Value, 2, MidpointRounding.ToZero);
|
||||
await Ledger.RecordDividendAsync(account.AccountId, strategy, amount, currency, exDate,
|
||||
$"Dividendo {action.Symbol} {Format.Quantity(action.CashAmount!.Value)} per azione", cancellationToken, appliedKey: key + ":" + strategy).ConfigureAwait(false);
|
||||
Ledger.DividendNote(action.Symbol, action.CashAmount!.Value), cancellationToken, appliedKey: key + ":" + strategy).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await MarkAppliedAsync(account.AccountId, key, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Reference in new issue
Block a user