Functional Weave
Code in Python

inventory.valuation-fifo

FIFO stock valuation and cost of sales from a stock movement ledger, in exact money.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 18 tests, run in TypeScript, Python and Rust.

What it does

First in, first out: each issue is costed from the oldest stock still on hand, so what remains is valued at the most recent purchase prices. This is the method IAS 2 and FRS 102 section 13 allow alongside weighted average cost (LIFO is not permitted under either).

The ledger is one item's movements in date order: receipts carry a unit cost, issues carry none and take their cost from the layers they consume. An issue that spans several receipts is costed from each in turn, oldest first, and a receipt that is partly used stays as a smaller layer. The result gives the closing quantity and value, the remaining layers, the cost of sales, and the cost of each issue in ledger order (to post each one to the ledger).

For example

  • fifo_valuation(movements ×5, GBP) → closing quantity 70, closing value £385.00, cost of sales £965.00, issue costs £620.00, £345.00, layers ×1 an issue spans two receipts, a later one spans the rest of the second and a third
  • fifo_valuation(movements ×3, GBP) → closing quantity 10, closing value £20.00, cost of sales £10.00, issue costs £10.00, layers ×1 an issue that exactly empties the oldest layer removes it
  • fifo_valuation(movements ×3, GBP) → closing quantity 0, closing value £0.00, cost of sales £16.00, issue costs £16.00, layers issuing everything leaves no layers and nothing to value

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

def fifo_valuation(movements: Sequence[StockMovement], currency: str) -> FifoValuation
movementsStockMovement[]the ledger for one item, in date order; same-day lines in the order they happened
currencystringthe valuation currency, so an empty ledger still has one
returnsFifoValuation

The types it declares, generated into your project

@dataclass(frozen=True)
class StockMovement:
    """One line of the stock ledger."""

    date: str
    #: positive for a receipt, negative for an issue; never zero
    quantity: int
    #: the cost of one unit on a receipt; null on an issue, which takes its cost from stock
    unit_cost: Optional[Money]

@dataclass(frozen=True)
class StockLayer:
    """Units still in stock from one receipt."""

    #: the date of the receipt
    date: str
    quantity: int
    unit_cost: Money

@dataclass(frozen=True)
class FifoValuation:
    """What is left, what it is worth, and what the issues cost."""

    closing_quantity: int
    closing_value: Money
    #: the cost of every issue together
    cost_of_sales: Money
    #: the cost of each issue, in ledger order
    issue_costs: List[Money]
    #: what is left, oldest first
    layers: List[StockLayer]

Your code names it in one line, in the file that uses it

from fune.inventory.valuation_fifo import fifo_valuation  # inventory.valuation-fifo@^1
impl/python.py · 71 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import List, Optional, Sequence

from .dates_add_days import epoch_day_from_iso  ← from dates.add-days ^1.0.0 · built alongside by fune
from .inventory_valuation_fifo_types import FifoValuation, StockLayer, StockMovement
from .money_amount import Money, assert_same_currency, money  ← from money.amount ^1.0.0 · built alongside by fune


def fifo_valuation(movements: Sequence[StockMovement], currency: str) -> FifoValuation:
    """Value stock first in, first out, and cost each issue from the oldest layers.

    Every cost is a whole quantity times a unit cost, so nothing is rounded and
    closing value plus cost of sales always equals what was received.
    """
    zero = money(0, currency)
    # [date, quantity, unit cost]: mutable while issues consume them.
    layers: List[list] = []
    issue_costs: List[Money] = []
    cost_of_sales = 0
    previous_day: Optional[int] = None
    previous_date = ""
    for line in movements:
        day = epoch_day_from_iso(line.date)
        if previous_day is not None and day < previous_day:
            raise ValueError("movements must be in date order: %s comes after %s" % (line.date, previous_date))
        previous_day = day
        previous_date = line.date
        if isinstance(line.quantity, bool) or not isinstance(line.quantity, int) or line.quantity == 0:
            raise ValueError(
                "quantity must be a non-zero whole number, received %r on %s" % (line.quantity, line.date)
            )
        if line.quantity > 0:
            if line.unit_cost is None:
                raise ValueError("a receipt needs a unitCost: %d on %s" % (line.quantity, line.date))
            assert_same_currency(zero, line.unit_cost)
            if line.unit_cost.minor < 0:
                raise ValueError(
                    "unitCost must not be negative, received %d on %s" % (line.unit_cost.minor, line.date)
                )
            layers.append([line.date, line.quantity, line.unit_cost])
            continue
        if line.unit_cost is not None:
            raise ValueError(
                "an issue takes its cost from stock, so its unitCost must be null: %d on %s"
                % (line.quantity, line.date)
            )
        wanted = -line.quantity
        on_hand = sum(layer[1] for layer in layers)
        if wanted > on_hand:
            raise ValueError(
                "insufficient stock: an issue of %d on %s exceeds the %d on hand" % (wanted, line.date, on_hand)
            )
        cost = 0
        while wanted > 0:
            oldest = layers[0]
            used = min(wanted, oldest[1])
            cost += used * oldest[2].minor
            oldest[1] -= used
            wanted -= used
            if oldest[1] == 0:
                layers.pop(0)
        issue_costs.append(money(cost, currency))
        cost_of_sales += cost
    closing_quantity = sum(layer[1] for layer in layers)
    closing_value = sum(layer[1] * layer[2].minor for layer in layers)
    return FifoValuation(
        closing_quantity=closing_quantity,
        closing_value=money(closing_value, currency),
        cost_of_sales=money(cost_of_sales, currency),
        issue_costs=issue_costs,
        layers=[StockLayer(date=d, quantity=q, unit_cost=c) for d, q, c in layers],
    )

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 2 dependencies, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add inventory.valuation-fifo
Download for Python inventory.valuation-fifo-1.0.0-python.fune · 16,388 bytes sha256 d72e621a4ed16c3cd151be3c30720ffd47a39697b41603c70a49e64d9e594c8c

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./inventory.valuation-fifo-1.0.0-python.fune, or fetch it from a terminal with fune pull inventory.valuation-fifo@1.0.0:python.

The whole function, every language, is one file too: inventory.valuation-fifo-1.0.0.fune, 24,834 bytes, sha256 f514605cd88d7e8ffd9f8428614b212c31641f671a5e882c438070f9332702a0. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

# fune: before inventory.valuation-fifo

after — your function gets the result and the arguments, and returns the final result.

# fune: after inventory.valuation-fifo

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

# fune: replace dates.add-days in inventory.valuation-fifo
# fune: replace money.amount in inventory.valuation-fifo

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show inventory.valuation-fifo --steps.

# fune: step inventory.valuation-fifo after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
an issue spans two receipts, a later one spans the rest of the second and a third movements ×5, GBP → closing quantity 70, closing value £385.00, cost of sales £965.00, issue costs £620.00, £345.00, layers ×1
an issue that exactly empties the oldest layer removes it movements ×3, GBP → closing quantity 10, closing value £20.00, cost of sales £10.00, issue costs £10.00, layers ×1
issuing everything leaves no layers and nothing to value movements ×3, GBP → closing quantity 0, closing value £0.00, cost of sales £16.00, issue costs £16.00, layers
receipts only: every layer is still there, oldest first movements ×2, GBP → closing quantity 5, closing value £49.99, cost of sales £0.00, issue costs , layers ×2
same-day lines are taken in ledger order: a receipt then an issue on one day movements ×4, GBP → closing quantity 2, closing value £6.00, cost of sales £16.00, issue costs £2.50, £13.50, layers ×1
a free receipt (a sample) is a layer at zero cost movements ×3, GBP → closing quantity 1, closing value £7.00, cost of sales £7.00, issue costs £7.00, layers ×1
restocking after running out starts a fresh layer movements ×4, GBP → closing quantity 3, closing value £3.90, cost of sales £7.60, issue costs £5.00, £2.60, layers ×1
an empty ledger is nothing, in the given currency , EUR → closing quantity 0, closing value €0.00, cost of sales €0.00, issue costs , layers
an issue larger than the stock on hand is an error movements ×2, GBP → error: insufficient stock: an issue of 11 on 2026-01-02 exceeds the 10 on hand
an issue before any receipt is an error movements ×1, GBP → error: insufficient stock
Show the other 8 tests
CaseArgumentsExpected
a ledger out of date order is an error movements ×2, GBP → error: movements must be in date order: 2026-01-04 comes after 2026-01-05
a receipt with no unit cost is an error movements ×1, GBP → error: a receipt needs a unitCost
an issue with a unit cost is an error movements ×2, GBP → error: its unitCost must be null
a zero quantity is an error movements ×1, GBP → error: quantity must be a non-zero whole number
a fractional quantity is an error movements ×1, GBP → error: quantity must be a non-zero whole number
a negative unit cost is an error movements ×1, GBP → error: unitCost must not be negative
a cost in another currency is an error movements ×1, GBP → error: currency mismatch
an impossible date is an error movements ×1, GBP → error: is not a real calendar date

More from the author

**Exact money.** Unit costs are `Money` in minor units and every cost is quantity times unit cost, so nothing is rounded and closing value plus cost of sales always equals the total of the receipts. A unit cost that has fractions of a penny cannot be expressed; use `inventory.valuation-weighted-average`, or cost in a smaller unit (per 100) and scale the quantities.

**Errors, not guesses.** An issue larger than the stock on hand is an error rather than negative stock: FIFO has no cost for units that were never received. So are a ledger out of date order, a zero quantity, a receipt with no unit cost or a negative one, an issue with a unit cost, and a cost in another currency. Returns to supplier and customer returns are not modelled: post a customer return as a receipt at the cost it was issued at.

Sources: IAS 2 *Inventories*, paragraphs 25-27 (IFRS Foundation); FRS 102 section 13 *Inventories*, paragraph 13.18 (Financial Reporting Council).

Files

PathBytes
README.md1,705
impl/python.py3,169
impl/rust.rs5,090
impl/typescript.ts3,072
vectors.json7,102