Skip to content
TotalFinance

Portfolio · @insiderfinance/totalfinance

@insiderfinance/totalfinance/portfolio

import { … } from '@insiderfinance/totalfinance/portfolio'
stable-by-law (pre-1.0; not a 1.0 stability guarantee)iface 159type 60const 12fn 30JSON ↗
fn

isModelPortfolio

#

Whether a value is a structurally valid, untampered model artifact (a predicate: never throws).

Signature
import { isModelPortfolio } from '@insiderfinance/totalfinance/portfolio';

export declare function isModelPortfolio(value: unknown): value is ModelPortfolio;
Fields, parameters and returned members (1)
Name · typeMeaning · unitRequired · default
(value)unknown—unitless by nameRequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

isPortfolioLedgerSnapshot

#

Structural test for a (current-version) serialized ledger envelope.

Signature
import { isPortfolioLedgerSnapshot } from '@insiderfinance/totalfinance/portfolio';

export declare function isPortfolioLedgerSnapshot(value: unknown): value is PortfolioLedgerSnapshot;
Fields, parameters and returned members (1)
Name · typeMeaning · unitRequired · default
(value)unknown—unitless by nameRequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

mergeTradePolicies

#

The stricter of every policy given: the minimum of each bound, the intersection of each allow list, the stricter unverifiable handling.

Signature
import { mergeTradePolicies } from '@insiderfinance/totalfinance/portfolio';

export declare function mergeTradePolicies(input: MergeTradePoliciesInput): TradePolicy;
Fields, parameters and returned members (20)

Loading 20 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

monitorPortfolio

#

Evaluate one explicit valuation against the policy and the prior monitor state — see the module comment for the decisions. Pure: same inputs, same alerts and state.

Signature
import { monitorPortfolio } from '@insiderfinance/totalfinance/portfolio';

export declare function monitorPortfolio(input: MonitorPortfolioInput): MonitorPortfolioResult;
Fields, parameters and returned members (43)

Loading 43 members…

Example
import { monitorPortfolio } from '@insiderfinance/totalfinance/portfolio/policy';

const first = monitorPortfolio({
  portfolio: ledger.state,
  market,
  asOf: '2026-08-20',
  policy: { limits: { maximumPositionWeight: 0.25, maximumDrawdown: 0.1 } },
  previousState: null,
});
const next = monitorPortfolio({ ...sameInputs, asOf: '2026-08-21', previousState: first.state });
next.alerts; // [{ key: 'concentration-limit:AAPL', state: 'raised', value: 0.31, threshold: 0.25, … }]

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

normalizeTradePlan

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import { normalizeTradePlan } from '@insiderfinance/totalfinance/portfolio';

export declare function normalizeTradePlan(input: NormalizeTradePlanInput): ExecutionPlan;
Fields, parameters and returned members (24)

Loading 24 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

portfolioEventContentHash

#

The event's content identity and the CONFLICT boundary for duplicate (sourceId, eventId) delivery: the sha256: content hash (Gate B canonical JSON) of the envelope EXCLUDING provenance — two deliveries of the same economic fact under different source labels are the SAME event (Gate B Decision 3: provenance is outside every identity). The envelope is fully validated first; a malformed envelope never acquires a confident-looking hash.

Signature
import { portfolioEventContentHash } from '@insiderfinance/totalfinance/portfolio';

export declare function portfolioEventContentHash(envelope: PortfolioEventEnvelope): string;
Fields, parameters and returned members (13)

Loading 13 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

portfolioEventsFromFill

#

Map one NormalizedFill to the economic events the ledger folds: exactly one trade.fill (id = fillId) followed by one cost.charge per non-zero cost component (id = <fillId>:cost:<component>, relatesToEventId = the fill), in the fixed order commission → exchange fees → regulatory fees → slippage adjustment. The mapping is deterministic and the ids are derived from the fill, so an identical fill delivered twice folds once (the ledger's duplicate boundary) and a replay emits identical envelopes. Every envelope passes the same validator a hand-written one would.

Signature
import { portfolioEventsFromFill } from '@insiderfinance/totalfinance/portfolio';

export declare function portfolioEventsFromFill(input: PortfolioEventsFromFillInput): PortfolioEventEnvelope[];
Fields, parameters and returned members (5)
Name · typeMeaning · unitRequired · default
(input)PortfolioEventsFromFillInput—unitless by nameRequiredNo @default declared
(input).fillNormalizedFill—unitless by nameRequiredNo @default declared
(input).provenanceProvenance

Where the fill came from; {} when there is no further detail. Outside the event identity.

unitless by name
OptionalNo @default declared
(input).recordedTimestampMsnumber

When the events are recorded — supplied, never read from a clock.

epoch milliseconds (UTC instant)
RequiredNo @default declared
(input).sourceIdstring

The system that produced the fill — 'backtest:<runId>', a broker import id, a paper account.

unitless by name
RequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

portfolioLedgerContentHash

#

The ledger's content identity: sha256: over the canonical envelope with provenance removed at BOTH levels — the ledger's own and every event's (Gate B Decision 3: identical economic facts from two vendors are the SAME ledger; dedup and replay comparison depend on that). baseCurrency and lotRelief ARE covered: they change the derived economics, so two ledgers differing only in relief policy must never collide. The envelope is fully validated through the read path first — a malformed envelope never acquires a confident-looking hash (the Gate B serial-landing lesson) — and identity is defined over the CURRENT grammar: hash an older stored version by reading it with its registered migrations and hashing ledger.toJSON().

Signature
import { portfolioLedgerContentHash } from '@insiderfinance/totalfinance/portfolio';

export declare function portfolioLedgerContentHash(snapshot: PortfolioLedgerSnapshot): string;
Fields, parameters and returned members (8)
Name · typeMeaning · unitRequired · default
(snapshot)PortfolioLedgerSnapshot—unitless by nameRequiredNo @default declared
(snapshot).baseCurrencystring—ISO-4217 currency codeRequiredNo @default declared
(snapshot).eventsPortfolioEventEnvelope[]—unitless by nameRequiredNo @default declared
(snapshot).kind'totalfinance.portfolio-ledger'—unitless by nameRequiredNo @default declared
(snapshot).lotReliefLotReliefPolicy

The lot-relief policy the fold runs under — INSIDE the content identity (it changes P&L).

unitless by name
RequiredNo @default declared
(snapshot).portfolioIdstring—unitless by nameOptionalNo @default declared
(snapshot).provenanceProvenance

Ledger-level provenance — caller-supplied, preserved, OUTSIDE the content identity.

unitless by name
OptionalNo @default declared
(snapshot).schemaVersionnumber—unitless by nameRequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

portfolioPerformanceInputs

#

Derive the EXACT valuations + externalCashFlows series FC4's flow-aware calls consume, from a ledger and explicit per-date marks. The identity test in test/performance-seam.test.ts proves ledger-derived series → timeWeightedReturn/moneyWeightedReturn equal the same FC4 calls on hand-built series (the FC7 exit-gate hook, closed in this slice).

Signature
import { portfolioPerformanceInputs } from '@insiderfinance/totalfinance/portfolio';

export declare function portfolioPerformanceInputs(input: PortfolioPerformanceInputsInput): PortfolioPerformanceInputsResult;
Fields, parameters and returned members (14)

Loading 14 members…

Example
import { timeWeightedReturn } from '@insiderfinance/totalfinance/performance';
import { portfolioPerformanceInputs } from '@insiderfinance/totalfinance/portfolio/performance';

const series = portfolioPerformanceInputs({ ledger, valuationMarks });
const twr = timeWeightedReturn({
  valuations: series.valuations,
  externalCashFlows: series.externalCashFlows,
  flowTiming: 'at-flow-timestamp',
  annualization: 'none',
});

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

portfolioPnl

#

Reconciled P&L between two valuation marks — see the module comment for the identity and the conversion convention. Never mutates the ledger; every number is base currency unless the row says otherwise.

Signature
import { portfolioPnl } from '@insiderfinance/totalfinance/portfolio';

export declare function portfolioPnl(input: PortfolioPnlInput): PortfolioPnlResult;
Fields, parameters and returned members (31)

Loading 31 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

portfolioSnapshot

#

Value a portfolio state against an explicit market snapshot at an explicit instant.

Signature
import { portfolioSnapshot } from '@insiderfinance/totalfinance/portfolio';

export declare function portfolioSnapshot(input: PortfolioSnapshotInput): PortfolioSnapshotResult;
Fields, parameters and returned members (22)

Loading 22 members…

Example
import { createMarketSnapshot } from '@insiderfinance/totalfinance/core/artifacts';
import { applyPortfolioEvents, portfolioSnapshot } from '@insiderfinance/totalfinance/portfolio';

const state = applyPortfolioEvents({ portfolio: { baseCurrency: 'USD' }, events });
const market = createMarketSnapshot({
  asOf: '2026-08-20',
  observations: { spots: { AAPL: { price: 232.5, currency: 'USD' } } },
});
const valued = portfolioSnapshot({ portfolio: state, asOf: '2026-08-20', market });
valued.netAssetValue; // cash + positions, in USD

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

portfolioTimeline

#

NAV, cash, flows, exposure, drawdown, and P&L components through time — see the module comment.

Signature
import { portfolioTimeline } from '@insiderfinance/totalfinance/portfolio';

export declare function portfolioTimeline(input: PortfolioTimelineInput): PortfolioTimelineResult;
Fields, parameters and returned members (29)

Loading 29 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

preflightTradePlan

#

Public declaration. Read the signature and member contracts below; no additional behaviour is inferred.

Signature
import { preflightTradePlan } from '@insiderfinance/totalfinance/portfolio';

export declare function preflightTradePlan(input: PreflightTradePlanInput): PreflightReport;
Fields, parameters and returned members (63)

Loading 63 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

proposePortfolioRebalance

#

Propose a rebalance of the ledger's managed book toward the policy's targets at asOf — a plan, never an execution. See the module comment for the laws and the accepted example.

Signature
import { proposePortfolioRebalance } from '@insiderfinance/totalfinance/portfolio';

export declare function proposePortfolioRebalance(input: ProposePortfolioRebalanceInput): ProposePortfolioRebalanceResult;
Fields, parameters and returned members (57)

Loading 57 members…

Example
import { createMarketSnapshot } from '@insiderfinance/totalfinance/core/artifacts';
import { proposePortfolioRebalance } from '@insiderfinance/totalfinance/portfolio/policy';

const proposal = proposePortfolioRebalance({
  portfolio: ledger.state,
  market: createMarketSnapshot({ asOf: '2026-08-29', observations: { spots: { SPY: { price: 120, currency: 'USD' }, AGG: { price: 100, currency: 'USD' } } } }),
  asOf: '2026-08-29',
  scope: 'drift-only',
  policy: {
    targets: [
      { group: { tag: 'equity' }, weight: 0.6 },
      { group: { tag: 'fixed-income' }, weight: 0.3 },
      { group: { assetClass: 'cash' }, weight: 0.1 },
    ],
    driftBand: 0.03,
    maximumTurnover: 0.15,
    minimumCash: 5_000,
  },
  instrumentClassification: { SPY: { tags: ['equity'] }, AGG: { tags: ['fixed-income'] } },
  defaultLotSize: 1,
});
proposal.trades; // sell SPY, buy AGG — only what is outside the 3% band
proposal.plan.contentHash; // 'sha256:…' — a normalized plan for preflight

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

readPortfolioLedgerSnapshot

#

The ONE door back in for stored ledgers: validates the envelope (closed key set, kind, version) BEFORE reading any event, applies explicitly registered migrations for older versions, refuses newer versions, then restores by RE-FOLDING the events through createPortfolioLedger — full re-validation and deterministic replay in one step — and reports the exact migrations applied.

Signature
import { readPortfolioLedgerSnapshot } from '@insiderfinance/totalfinance/portfolio';

export declare function readPortfolioLedgerSnapshot(input: ReadPortfolioLedgerSnapshotInput): { ledger: PortfolioLedger; migrationsApplied: AppliedMigration[]; };
Fields, parameters and returned members (5)
Name · typeMeaning · unitRequired · default
(input)ReadPortfolioLedgerSnapshotInput—unitless by nameRequiredNo @default declared
(input).migrationsArtifactMigrationRegistry

Explicitly registered migrations for OLDER stored versions — never module-global state.

unitless by name
OptionalNo @default declared
(input).snapshotunknown—unitless by nameRequiredNo @default declared
return.ledgerPortfolioLedger—unitless by nameRequiredNo @default declared
return.migrationsAppliedAppliedMigration[]—unitless by nameRequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

reconcileExecution

#

Reconcile an execution (Decision 8). Pure: the journal (events or a folded state), the ledger, the fills, and the optional external snapshot are inputs; the tolerance is explicit; the result is a content-addressed totalfinance.reconciliation-report.

Signature
import { reconcileExecution } from '@insiderfinance/totalfinance/portfolio';

export declare function reconcileExecution(input: ReconcileExecutionInput): ReconciliationReport;
Fields, parameters and returned members (66)

Loading 66 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

reconcilePortfolio

#

Compare a derived state with a normalized external snapshot at asOf — see the module comment.

Signature
import { reconcilePortfolio } from '@insiderfinance/totalfinance/portfolio';

export declare function reconcilePortfolio(input: ReconcilePortfolioInput): ReconcilePortfolioResult;
Fields, parameters and returned members (26)

Loading 26 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

requireNormalizedFill

#

Validate a NormalizedFill at a public boundary: a closed plain-data record whose numbers are finite, whose quantity is positive, whose settlement never precedes the fill, whose cost components are non-negative, and whose derivative terms come with their multiplier. The economic laws a fill must satisfy inside the ledger (a future settles by variation margin, a lot selection names real lots, …) are enforced by the event validator the mapped events pass through.

Signature
import { requireNormalizedFill } from '@insiderfinance/totalfinance/portfolio';

export declare function requireNormalizedFill(functionName: string, label: string, fill: unknown): asserts fill is NormalizedFill;
Fields, parameters and returned members (3)
Name · typeMeaning · unitRequired · default
(fill)unknown—unitless by nameRequiredNo @default declared
(functionName)string—unitless by nameRequiredNo @default declared
(label)string—unitless by nameRequiredNo @default declared

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

requirePortfolioEventEnvelope

#

Validate one PortfolioEventEnvelope at a public boundary (Law 12 closed request): known keys at every level, identity strings, finite explicit timestamps, the schema version, the envelope/payload discriminator agreement, and the full per-variant payload contract. The guard validates its own functionName and label first (the requireFundamentalPeriod precedent) so its teaching errors always name the real boundary.

Signature
import { requirePortfolioEventEnvelope } from '@insiderfinance/totalfinance/portfolio';

export declare function requirePortfolioEventEnvelope(functionName: string, label: string, envelope: PortfolioEventEnvelope): asserts envelope is PortfolioEventEnvelope;
Fields, parameters and returned members (15)

Loading 15 members…

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.

fn

resolveModelTargets

#

The targets a model makes effective at asOf: the latest tactical set covering the instant, else the glide path (stepped or interpolated), else the strategic set. An instant before the strategic set is effective is a typed refusal — a model has no targets there.

Signature
import { resolveModelTargets } from '@insiderfinance/totalfinance/portfolio';

export declare function resolveModelTargets(input: ResolveModelTargetsInput): ResolvedTargets;
Fields, parameters and returned members (10)
Name · typeMeaning · unitRequired · default
(input)ResolveModelTargetsInput—unitless by nameRequiredNo @default declared
(input).asOfstring | number

The instant to resolve at ('YYYY-MM-DD', zoned ISO datetime, or epoch ms).

an instant: epoch milliseconds or a YYYY-MM-DD / zoned ISO string (the resolveAsOf convention)
RequiredNo @default declared
(input).modelModelPortfolio—unitless by nameRequiredNo @default declared
return.effectiveFromnumber | null

The effective-from instant of the winning set (null for inline targets).

unitless by name
RequiredNo @default declared
return.interpolation{ fraction: number; from: EpochMs; to: EpochMs; }

Present when a linear glide path interpolated between two points.

unitless by name
OptionalNo @default declared
return.interpolation.fractionnumber—unitless by nameRequiredNo @default declared
return.interpolation.fromnumber—unitless by nameRequiredNo @default declared
return.interpolation.tonumber—unitless by nameRequiredNo @default declared
return.sourceResolvedTargetSource—unitless by nameRequiredNo @default declared
return.targetsAllocationTarget[]—unitless by nameRequiredNo @default declared
Example
const effective = resolveModelTargets({ model, asOf: '2026-06-30' });
effective.source; // 'strategic' | 'tactical' | 'glide-path'

Stability: stable-by-law (pre-1.0; not a 1.0 stability guarantee). Units come from declared names; “unitless by name” means the name alone does not establish a unit. See conventions and errors and warnings.