hledger-lib
Safe HaskellNone
LanguageGHC2021

Hledger.Data.Lots

Description

Lot tracking for investment accounting.

This module implements two pipeline stages (see doc/SPEC-finalising.md):

  1. Classification (journalClassifyLotPostings): identifies lot postings and tags them as acquire, dispose, transfer-from, or transfer-to.
  2. Calculation (journalCalculateLots): walks transactions in date order, accumulating a map from commodities to their lots, and:
  • For acquire postings: generates lot names from cost basis and appends them to the account name as subaccounts.
  • For dispose postings: selects an existing lot subaccount matched by the posting's lot selector, using the configured reduction method (FIFO by default, configurable per account/commodity via lots: tag). If needed and if the lot selector permits it, selects multiple lots, splitting the posting into one per lot. Dispose postings with a transacted price (selling price) generate gain postings. Bare disposes without a price (e.g. fee deductions) get lot subaccounts but no gain.
  • For transfer postings: selects lots from the source account (like dispose) and recreates them under the destination account. The lot's cost basis is preserved through the transfer. Multi-lot transfers are supported (eg via {} to transfer all lots).

For background, see doc/SPEC-lots.md and doc/PLAN-lots.md.

Errors

User-visible errors from this module. See also Hledger.Data.Errors and doc/ERRORS.md.

journalCalculateLots:

  • validateUserLabels: "lot id is not unique: commodity X, date D, label L"
  • processAcquirePosting: "acquire posting has no cost basis", "...has multiple cost basis amounts", "X is lotful but this acquire posting has no cost basis or price", "...has no lot cost", "duplicate lot id: {...} for commodity X"
  • processDisposePosting: "dispose posting has no cost basis", "...has no transacted price (selling price)" / "(buying price, to cover the short)", "...has non-negative quantity" / "non-positive quantity (a short position is covered by a positive posting)", "SPECID requires a lot selector", "lot ... has no cost basis (internal error)", "lot subaccount ... does not match resolved lot"
  • groupIndexedTransferPostings: "transfer-to/from posting ... has no matching ... posting", "Mismatched transfer quantities for lot-tracked commodity X", "... posting has no lotful commodity"
  • processTransferGroup: "transfer-from posting has no cost basis", "...has multiple cost basis amounts", "lot transfers should have no transacted price", "transfer-from posting has non-negative quantity", "transfer-to posting has no single positive X amount", "could not distribute transferred lots exactly (internal error)", "lot ... has no cost basis (internal error)", "lot cost basis ... does not match transfer-to cost basis"
  • selectLots: "SPECID requires an explicit lot selector", "no X lots available for transfer/disposal from account Y on DATE" (with a hint to use a liability account for a short position), and on any lot error, a hint naming a later same-date entry which adds the commodity to an empty source account (see laterSupplyHint), "no lots matching {...} for commodity X in account Y on DATE", "lot selector is ambiguous, matches N lots in account Y", "Insufficient lots for commodity X in account Y"
  • validateGlobalCompliance: "METHOD: lot(s) on other account(s) have higher priority than the lots in ACCT"
  • poolWeightedAvgCost: "no lots with cost basis available for averaging", "cannot average lots with different cost commodities", "cannot average lots with zero total quantity"
  • foldMPostings (via isUnclassifiedLotfulPosting): "X is declared lotful ... but this posting was not classified" (exempt: zero-amount lotful postings; in a liability account, notes that short lots can't be transferred yet)
Synopsis

Documentation

journalHasLotFeatures :: Journal -> Bool Source #

Does this journal use lots at all ? True if any commodity is declared lotful, any account declaration has a lots: tag, or any posting (in transactions, periodic transaction rules or auto posting rules) has a cost basis annotation or a lot subaccount name. When false, the lot-related finalisation stages would all be no-ops, so journalFinalise skips them.

transactionHasLotfulAmounts :: Set CommoditySymbol -> Transaction -> Bool Source #

Could this transaction involve lots ? True if any of its amounts has a cost basis annotation or is in one of the given lotful commodities. A cheap test, broader than any of the lot stages' own triggers, so they can skip the (usually many) transactions for which it is false.

journalClassifyLotPostings :: Bool -> Journal -> Journal Source #

Classify lot-related postings by adding ptype tags. Must be called after journalAddAccountTypes so account types are available, and after transaction balancing, so that all posting amounts (including ones inferred from elided amounts or balance assignments) are known: classification then gives the same result for every entry shape as if all amounts had been written explicitly (#2686, #2690, #2692). The verbosetags parameter controls whether the ptype tags will be made visible in comments. Before classification, try to auto-split lot transfers with fees into a transfer portion and a dispose portion, so both get classified correctly.

journalStripBalancerCopiedBases :: Journal -> Journal Source #

Remove balancer-copied cost basis annotations (see hasBalancerCopiedBasis) from postings that lot classification left unclassified, now that lot processing has used them as evidence. Lot-processed (classified) postings are left alone: lot calculation legitimately gives machinery-derived cost bases to postings whose amounts were inferred, eg the per-lot fragments of an elided transfer source.

transactionAutoSplitFeeOutflows :: Bool -> (AccountName -> Maybe AccountType) -> (CommoditySymbol -> Bool) -> (AccountName -> Bool) -> Transaction -> Transaction Source #

Detect a lot transfer with a fee - an unpriced negative lotful asset posting (bare in a lotful commodity, or carrying a cost basis annotation) whose absolute quantity exceeds the positive quantities received by asset accounts, where the excess matches a non-asset posting (typically a fee paid in the lotful commodity) - and split it into a transfer portion (matching the positive sum) and a dispose portion, so classification can correctly tag the two roles. When the fee counterpart has a transacted price, the dispose portion carries it (and a gain will be calculated); otherwise the dispose portion is priceless (lots are still reduced, but no gain is calculated).

If no such pattern is found, the transaction is returned unchanged. The transfer portion inherits the original's identity (poriginal preserves the unsplit quantity, so plain print shows the user's original entry). The dispose portion is tagged `_feesplit-posting` so plain print hides it, and `_generated-posting` to mark its provenance; -x or --verbose-tags reveals it. The dispose portion(s) come first, then the transfer portion, which keeps the original posting's balance assertion, so it is still checked after the full original quantity has been posted.

journalCalculateLots :: Bool -> Journal -> Either String Journal Source #

Calculate detailed lot movements by walking transactions in date order. Handles acquire postings (generating lot names as subaccounts), dispose postings (matching to existing lots using FIFO, splitting if needed), and transfer postings (moving lots between accounts, preserving cost basis). The verbosetags parameter controls whether generated-posting tags are made visible in comments. All lot selection/classification failures are hard errors. Same-date transactions are processed in parse order, never reordered.

journalCheckAcquireBasis :: Journal -> Either String Journal Source #

Check that no acquire-shaped posting (a real posting with a positive amount, in an asset account) writes both a per-unit cost basis and a transacted cost which disagree. In an acquisition these are the same thing, what the units cost; a typo in either would silently miscalculate gains. (Real-world cases of a basis differing from what was paid, like a gift with carryover basis, are written with the difference funded by a separate posting.)

They may agree only at the precision of the written basis: typically a non-terminating unit cost rendered to 8 decimal places by print (as a basis annotation or in a lot subaccount name), re-read alongside its exact @@ total cost. Then the exact transacted unit cost replaces the written basis, so nothing is lost in the round trip.

This runs before transaction balancing, so that such an entry gets this error rather than an unbalanced-transaction error; it needs only the amounts as written (after journalInferPostingsTransactedCost).

journalCheckLotsMethodCoherence :: Journal -> Either String Journal Source #

Check that global (*ALL) reduction methods are used coherently: when any account holding a lot-tracked commodity resolves to a global method, every account holding that commodity must resolve to the same method. Mixing a global method with any other is rejected, because the global validation (and, for AVERAGEALL, the global pool updates) only make sense when every account participates. Local methods (FIFO, LIFO, HIFO, SPECID, AVERAGE) may be mixed per account freely.

journalAveragePoolTotals :: Journal -> Maybe Day -> Map (AccountName, CommoditySymbol) (Quantity, Amount) Source #

The units and total cost basis of each AVERAGE or AVERAGEALL lot pool, from the journal's lot postings dated before the given date (if any), keyed by base account and commodity. Dividing gives the pool's running average cost: acquisitions carry their acquisition cost and disposals and transfers the then-current average, so the quantity-weighted sum works out to the pool's average. An AVERAGE pool is one account's lots; an AVERAGEALL pool is the lots in all accounts with the same lot direction (long lots in asset accounts, or short lots in liability accounts). Pools with no units, or with cost bases in several commodities, are omitted. The lot subaccount names of AVERAGE lots leave out the cost (it changes as the pool is re-averaged), so this is how reports and generated entries (holdings, close) find it.

journalAveragePoolCosts :: Journal -> Maybe Day -> Map (AccountName, CommoditySymbol) Amount Source #

The average cost of each AVERAGE or AVERAGEALL lot pool, as of (just before) the given date, keyed by base account and commodity. Exact, displayed with at most 8 decimal places. See journalAveragePoolTotals.

journalCollapseLotDetail :: Journal -> Journal Source #

Collapse lot-tracking detail from a journal for display when --lots is off. Makes these targeted changes to each transaction:

  • drops postings tagged _lot-parent-assertion (synthetic balance-assertion carriers added when splitting a posting into lot subaccounts);
  • strips any lot subaccount (the trailing {...} component) from each remaining posting's account name;
  • merges per-lot split fragments back into one posting (see mergeLotSplits).

Lot-inferred cost basis annotations (acostbasis) are kept on the amounts: print shows them, so that lot entries are self-describing and can be re-read without the commodity's lots: declaration (under the default method). A merged multi-lot posting gets an unspecified basis ({}), meaning "lots selected by the account's method".

Postings tagged _feesplit-posting (synthetic fee fragments from auto-split) are retained so transactions stay balanced in reports like print.

print relies on its existing transactionWithMostlyOriginalPostings logic to revert pamount to poriginal when displaying non-explicit output (carrying the inferred basis over).

Journals with no lot content are returned unchanged.

journalTagGainPostings :: Bool -> Bool -> Journal -> Either String Journal Source #

Apply transactionTagGainPostings to each transaction. In lenient (--ignore-lots) mode, amountless gain postings are left untagged, for the balancer to infer like any other posting.

transactionTagGainPostings Source #

Arguments

:: Bool

also tag amountless Gain-typed postings (not in lenient mode)

-> Bool

also add visible tags

-> (AccountName -> Maybe AccountType)

account type lookup

-> (CommoditySymbol -> Bool)

is this a lotful commodity ?

-> (AccountName -> Bool)

does this account use lots: NONE ?

-> Transaction 
-> Transaction 

In a disposal transaction, tag the user-written realised gain postings with _ptype:gain, so that the transaction balancer sets them aside (see transactionCheckBalanced).

A disposal balances at cost basis: the dispose posting counts as its quantity times its basis, and the gain posting accounts for the difference from the transacted proceeds. The basis is not known until lot matching, which runs after balancing; but since q*B + q*(T-B) == q*T, balancing the non-gain postings at transacted cost is equivalent, and that is what the balancer does. Whether the gain amount is right is checked afterwards by journalAddOrCheckGainPostings.

Disposal transactions are recognised by shape, since classification has not run yet: a real posting with a negative lotful or cost-basis amount (postingHasDisposeShape; this also matches transfer sources, where a gain posting is later rejected by journalAddOrCheckGainPostings, the gain being zero). Gain postings are recognised in one of two ways:

  1. By account type: real postings on a Gain-typed account. These may be amountless (unless the first argument is false, in lenient --ignore-lots mode, where there'll be no lot matching to fill the amount in): the balancer leaves such a posting alone and journalAddOrCheckGainPostings sets its amount to the calculated gain.
  2. Heuristically, when there is no Gain-typed posting: real, amountful postings whose account type is not Asset, Liability or Equity (or a subtype), and which don't carry a lotful or cost-basis amount; accepted only if all postings have amounts and the remaining postings sum to zero at transacted cost (a well-formed disposal), or to an unpriced sale: a lot commodity net sold plus one other commodity net received (which balancing cost inference will resolve). A net purchase with a cash fee posting is not mistaken for a disposal with a gain. This lets a gain posting be written on any account without declaring it type:G, for simple entries.

Virtual (parenthesised) postings are ignored throughout, as the balancer and the lot machinery ignore them. A transaction which already has a tagged gain posting is returned unchanged, so this is safe to run repeatedly: it runs as a journalFinalise step, and again inside the balancer for callers which balance single entries (hledger add, hledger-web).

journalAddOrCheckGainPostings :: Bool -> Journal -> Either String Journal Source #

For each disposal transaction with a transacted price, add a realised-gain posting to a Gain-type account (default revenues:gain) with the negated gain amount; or if the transaction already has gain posting(s) (user-written; see transactionTagGainPostings), check that their sum matches the calculated gain.

With the gain posting present, the disposal balances at cost basis, and no counter posting is needed: hledger records gains by the historical cost convention, in which unrealised gains are not posted (though they can be reported from market prices).

The gain amount is the disposal gain: for each dispose posting amount with both a cost basis and a transacted cost, contribute aquantity * (B - T) (equivalently: cost-basis value minus transacted-cost value). Acquire and other postings do not contribute. Eg for -5 AAPL {$50} @ $70: gain contribution is -5 * ($50 - $70) = $100.

Runs after journalCalculateLots so that cost basis is populated on dispose postings. The generated posting carries the _generated-posting hidden tag, visible as generated-posting: in print --verbose-tags.

isDisposePosting :: Posting -> Bool Source #

Check if a posting is a dispose posting (has _ptype:dispose tag).

isGainPosting :: Posting -> Bool Source #

Check if a posting is a gain posting (has _ptype:gain tag): user-written and tagged by transactionTagGainPostings, or generated by journalAddOrCheckGainPostings.

isSetAsideGainPosting :: Transaction -> Posting -> Bool Source #

Is this a gain posting which the transaction balancer should set aside ? A disposal's gain posting is set aside so that the entry, with the disposal counted at transacted cost, balances at cost basis (see transactionTagGainPostings). But when the entry has equity conversion postings (a posting tagged as a cost posting), the disposal's cost is ignored and the conversion postings carry the cost basis instead, so the gain posting counts like any other.

lotBaseAccount :: AccountName -> AccountName Source #

Strip any trailing lot subaccount (a final :{...} component) from an account name. E.g., "assets:broker:{2026-01-15, $50}" becomes "assets:broker".

lotDirectionOf :: (AccountName -> Maybe AccountType) -> AccountName -> Maybe LotDirection Source #

The lot direction of an account (or of a lot subaccount's base account): Long for asset accounts, Short for liability accounts (which hold short positions), none for other account types. See LotDirection.

journalLotDirection :: Journal -> AccountName -> Maybe LotDirection Source #

The lot direction of an account in this journal. See lotDirectionOf.

lotSubaccountName :: AccountName -> Maybe Text Source #

Extract the lot subaccount name (the {...} component) from an account name, or Nothing if there is none. E.g., "assets:broker:{2026-01-15, $50}" returns Just "{2026-01-15, $50}".

mergeCostBasis :: CostBasis -> CostBasis -> Either String CostBasis Source #

Merge two CostBasis values. For each field, if both are Just, they must agree (returns error if not); otherwise takes whichever is Just. The first argument is typically the account-name basis (more complete), the second is the amount's existing basis.

parseLotName :: (String -> Maybe Amount) -> Text -> Either String CostBasis Source #

Parse a lot name (as produced by showLotName) back into a CostBasis. The input should be the full {...} string including braces. Parts are comma-separated and all optional: date (YYYY-MM-DD), label ("LABEL"), and cost (parsed by the supplied callback). The callback avoids an import cycle (Lots.hs cannot import Read-layer parsers).

resolveReductionMethodForAccount :: Journal -> AccountName -> CommoditySymbol -> (ReductionMethod, String) Source #

Resolve which reduction method is in effect for an account and commodity, and where it came from: the account's (inherited) lots: tag if any, else the commodity's lots: tag value if any, else FIFO.

showLotName :: CostBasis -> Text Source #

Render a lot name in the consolidated hledger format for use as a subaccount name. Format: {YYYY-MM-DD, COST} or {YYYY-MM-DD, "LABEL", COST}. The cost amount is rendered using its own intrinsic style. Callers that want the journal's canonical commodity styles applied (eg when building a lot subaccount name) should pre-style the CostBasis with styleLotCbCost.