hledger-2.0: Hledger/Cli/Commands/Holdings.hs
{-|
The @holdings@ command shows a report of investment holdings (lot-tracked assets).
Work in progress; see doc/SPEC-holdings.md.
Currently it shows the Date, Age, Units, Unit/Avg cost, Price, Cost,
Value, Weight, UGain, UGain%, RGain and XIRR columns, one row per
account (or lot subaccount, with --lots) and held commodity. In tree
mode, positions are grouped into account sections: a heading row per
account showing its subtree's totals, its positions beneath it named
by their commodity, and with --lots each position's lots beneath it.
The report computation (holdingsReport) is exported for reuse by other
UIs; the holdings command renders it in the usual output formats.
-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
module Hledger.Cli.Commands.Holdings (
holdingsmode
,holdings
,HoldingsReport(..)
,HoldingsReportOpts(..)
,HoldingsTotals(..)
,HoldingsLine(..)
,Holding(..)
,holdingsReport
,holdingsReportAsChart
,holdingsReportsAsChart
,holdingsPeriodReports
,holdingsPeriodsTitle
,holdingsUnpricedNote
,holdingsClosedHidden
,holdingsClosedNote
,totalsLeftOut
,showage
,showPercentWith
) where
import Control.Applicative ((<|>))
import Control.Monad (guard)
import Data.Aeson (Value, object, (.=))
import Data.Decimal (roundTo)
import Data.Default (def)
import Data.List.Extra (find, intercalate, intersperse, minimumBy, nubSort, nubSortOn, sortOn, transpose)
import Data.Map.Strict qualified as M
import Data.Set qualified as S
import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, maybeToList)
import Data.Ord (Down(..), comparing)
import Data.Text qualified as T
import Data.Text.Lazy qualified as TL
import Data.Time.Calendar (Day, addDays, diffDays)
import System.Console.ANSI (Color(..), ColorIntensity(..))
import System.Console.CmdArgs.Explicit (flagNone, flagReq)
import Safe (headMay)
import Text.Printf (printf)
import Hledger
import Hledger.Cli.Chart (chartFlag, chartRequested, chartWidthFlag, unitAmount, writeChart)
import Hledger.Cli.CliOptions
import Hledger.Cli.CompoundBalanceCommand (titleInterval)
import Hledger.Cli.Commands.Balance.Internal (addTotalBorders)
import Hledger.Cli.Commands.Print (roundFromRawOpts)
import Hledger.Cli.Utils (unsupportedOutputFormatError, warnIfLargeMultiPeriodReport, writeOutputLazyText)
import Hledger.Cli.Xirr (xirr)
import Hledger.Utils.I18n qualified as I18n
import Hledger.Write.Chart (Chart(..), ChartLabel(..), Mark(..), Panel(..), BarLayout(..), Series(..), SeriesRole(..), XAxis(..))
import Hledger.Write.Csv (CSV, printCSV, printTSV)
import Hledger.Write.Html (Html, htmlAsLazyText, titledTableHtml, toHtml)
import Hledger.Write.Ods (printFods)
import Hledger.Write.Spreadsheet (addHeaderBorders, headerCell)
import Hledger.Write.Spreadsheet qualified as Ods
import System.IO qualified as IO
import Text.Blaze.Html5 ((!))
import Text.Blaze.Html5 qualified as H
import Text.Blaze.Html5.Attributes qualified as A
import Text.Tabular.AsciiWide
-- | Command line options for this command.
holdingsmode = hledgerCommandMode
$(embedFileRelative "Hledger/Cli/Commands/Holdings.txt")
(flattreeflags True ++
[flagNone ["no-elide"] (setboolopt "no-elide") "in tree mode, don't squash boring parent accounts; in list mode, also show parent accounts (usually zero, hidden without -E)"
,flagNone ["full-names"] (setboolopt "full-names") "in tree mode, show full account names instead of indented leaf names"
,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "omit N leading account name parts; in tree mode, remove the first N levels"
,flagNone ["sort-amount","S"] (setboolopt "sort-amount") "sort by value (or with -B, cost) instead of account name, largest first"
,flagNone ["no-total","N"] (setboolopt "no-total") "omit the final total row"
,flagNone ["change"] (setboolopt "change") "show gains during the report period, or with a report interval, during each period (default with a start date and no interval)"
,flagNone ["cumulative"] (setboolopt "cumulative") "with a report interval, show gains from the report start date to each period's end"
,flagNone ["historical","H"] (setboolopt "historical") "show gains since acquisition, ignoring the report start date (default with a report interval)"
,flagReq ["round"] (\s opts -> Right $ setopt "round" s opts) "TYPE" $
intercalate "\n"
["how much rounding or padding should be done when displaying amounts ?"
,"none - show original decimal digits"
,"soft - just add or remove decimal zeros"
," to match precision"
,"hard - round amounts to precision (default)"
,"all - also round cost amounts to precision"
]
,chartFlag
,chartWidthFlag
,outputFormatFlag ["txt","csv","tsv","html","fods","json","svg"]
,outputFileFlag
,outputViewFlag])
cligeneralflagsgroups1
hiddenflags
([], Just $ argsFlag "[QUERY]")
-- | One holding: one commodity held in one displayed account (or lot
-- subaccount), with its report attributes. Each holding is one row of
-- the text/html/fods table and one record of the csv/tsv/json output.
-- A commodity fully disposed from a displayed account also gets a
-- holding, with zero units, so its realised gain stays visible.
data Holding = Holding {
hAccount :: AccountName
,hCommodity :: CommoditySymbol
,hDate :: Maybe Day -- ^ acquisition date, when the lots share one
,hAge :: Maybe Integer -- ^ days held at the report date
,hUnits :: Amount -- ^ units held, styled
,hUnitCost :: Maybe Amount -- ^ unit or average cost
,hPrice :: [Amount] -- ^ market price(s) at the valuation date (several if the lots' value commodities differ)
,hCost :: [Amount] -- ^ total cost basis (multiple amounts if cost commodities are mixed)
,hValue :: [Amount] -- ^ market value, when all lots are priced (multiple amounts if value commodities are mixed)
,hWeight :: Maybe Quantity -- ^ percentage of the portfolio's value, unrounded
,hUgain :: [Amount] -- ^ unrealised gain, when values and costs cover the same commodities
,hUgainPct :: Maybe Quantity -- ^ unrealised gain percent, unrounded
,hRgain :: [Amount] -- ^ realised gain, from disposals so far
,hXirr :: Maybe Double -- ^ annualised internal rate of return percent
,hFlows :: [(Day, Amount)] -- ^ its dated cashflows (negative = money invested), which XIRR is calculated from; not displayed
}
-- Machine-readable fields for the csv/tsv output: full account name, age
-- in days, bare units and rounded gain percent numbers, machine-format
-- amounts (no digit group marks).
holdingCsv :: Holding -> [T.Text]
holdingCsv h =
[hAccount h
,hCommodity h
,maybe "" showDate (hDate h)
,maybe "" (T.pack . show) (hAge h)
,T.pack $ showAmountWith machineFmt{displayCommodity=False} (hUnits h)
,maybe "" showamt (hUnitCost h)
,showamts (hPrice h)
,T.pack $ showMixedAmountWith machineFmt $ mixed $ hCost h
,showamts (hValue h)
,maybe "" (T.pack . show . roundTo 1) (hWeight h)
,showamts (hUgain h)
,maybe "" (T.pack . show . roundTo 1) (hUgainPct h)
,showamts (hRgain h)
,maybe "" (T.pack . printf "%.1f") (hXirr h)
]
where
showamt = T.pack . showAmountWith machineFmt
showamts [] = ""
showamts as = T.pack $ showMixedAmountWith machineFmt $ mixed as
-- | Machine-readable fields for a period's totals, in the csv/tsv output with a report interval: like 'holdingCsv'.
periodTotalsCsv :: Day -> (M.Map CommoditySymbol AmountStyle, HoldingsTotals) -> [T.Text]
periodTotalsCsv d (_, tot) =
[showDate d
,maybe "" (T.pack . showAmountWith machineFmt{displayCommodity=False}) (htUnits tot)
,maybe "" showamt (htAvgCost tot)
,maybe "" showamt (htPrice tot)
,showamts (htCost tot)
,maybe "" showamts (htValue tot)
,maybe "" showamts (htUgain tot)
,maybe "" (T.pack . show . roundTo 1) (htUgainPct tot)
,showamts (htRgain tot)
,maybe "" (T.pack . printf "%.1f") (htXirr tot)
,T.intercalate ", " (htUnpriced tot)
]
where
showamt a = showamts [a]
showamts [] = ""
showamts as = T.pack $ showMixedAmountWith machineFmt $ mixed as
-- | A period's totals, in the json output with a report interval: like 'holdingJson'.
periodTotalsJson :: Day -> (M.Map CommoditySymbol AmountStyle, HoldingsTotals) -> Value
periodTotalsJson d (_, tot) = object
["date" .= d
,"units" .= (aquantity <$> htUnits tot)
,"avgcost" .= (showamts . (:[]) <$> htAvgCost tot)
,"unitprice" .= (showamts . (:[]) <$> htPrice tot)
,"totalcost" .= showamts (htCost tot)
,"totalvalue" .= (showamts <$> htValue tot)
,"ugain" .= (showamts <$> htUgain tot)
,"ugainpct" .= (roundTo 1 <$> htUgainPct tot)
,"rgain" .= mshowamts (htRgain tot)
,"xirr" .= htXirr tot
,"unpriced" .= htUnpriced tot
]
where
showamts = T.pack . showMixedAmountWith machineFmt . mixed
mshowamts as = case as of [] -> Nothing; _ -> Just $ showamts as
holdingJson :: Holding -> Value
holdingJson h = object
["account" .= hAccount h
,"commodity" .= hCommodity h
,"date" .= hDate h
,"age" .= hAge h
,"units" .= aquantity (hUnits h)
,"unitcost" .= (showamt <$> hUnitCost h)
,"unitprice" .= mshowamts (hPrice h)
,"totalcost" .= showamts (hCost h)
,"totalvalue" .= mshowamts (hValue h)
,"weight" .= (roundTo 1 <$> hWeight h)
,"ugain" .= mshowamts (hUgain h)
,"ugainpct" .= (roundTo 1 <$> hUgainPct h)
,"rgain" .= mshowamts (hRgain h)
,"xirr" .= hXirr h
]
where
showamt = T.pack . showAmountWith machineFmt
showamts = T.pack . showMixedAmountWith machineFmt . mixed
mshowamts as = case as of [] -> Nothing; _ -> Just $ showamts as
-- | Show an age in days compactly: in days, or if a year or more,
-- in years with one decimal digit (approximating years as 365 days):
-- eg 44d, 1.1y.
showage :: Integer -> T.Text
showage d
| d >= 365 = T.pack (show (roundTo 1 (fromIntegral d / 365))) <> "y"
| otherwise = T.pack (show d) <> "d"
-- | Show a percentage (eg for the Weight, UGain% and XIRR columns) as a
-- "%" commodity amount, using the given styles' display style for the
-- "%" commodity (eg from a commodity directive or -c, or
-- holdingsReport's default): eg 64.3%.
showPercentWith :: M.Map CommoditySymbol AmountStyle -> Quantity -> T.Text
showPercentWith styles p =
T.pack $ showAmountWith noCostFmt{displayZeroCommodity=True} $
styleAmounts styles nullamt{acommodity="%", aquantity=p}
-- | Options for the holdings report, besides the usual ReportSpec.
data HoldingsReportOpts = HoldingsReportOpts {
hroLots :: Bool -- ^ show each lot (one row per lot subaccount) rather than aggregating them per account, like --lots
,hroRounding :: Rounding -- ^ how much rounding or padding to apply to displayed amounts, like --round
,hroPriceOracle :: Maybe PriceOracle
-- ^ the journal's price oracle, if already made (for the report options' --infer-market-prices),
-- so that several reports can share it and its cache; otherwise the report makes one
}
-- | The grand totals of a holdings report, summed over its topmost
-- displayed rows (which include everything below them) - except RGain
-- and XIRR, which cover all the lots within the query and end date,
-- including fully disposed lots, commodities and accounts, which have
-- no row unless -E is used; so the totals are the same in list or tree
-- mode, with or without --lots or -E (#2769). Absent components
-- (Nothing or empty) are shown as blank cells.
-- Units, and the average cost per unit, are present only when the
-- holdings are all in one commodity (a multi-commodity total would
-- widen the column for everyone, and a multi-commodity average is
-- not meaningful); the average also needs a single cost commodity.
-- Value and gains are absent unless all holdings have a market price.
data HoldingsTotals = HoldingsTotals {
htUnits :: Maybe Amount -- ^ total units held, when all in one commodity
,htAvgCost :: Maybe Amount -- ^ their average unit cost, when also in one cost commodity
,htPrice :: Maybe Amount -- ^ their unit market price, when they are in one commodity with one price (shown with a report interval)
,htCost :: [Amount] -- ^ total cost basis, per cost commodity
,htValue :: Maybe [Amount] -- ^ total market value, per value commodity, of the holdings whose value is known (see htUnpriced)
,htWeight :: Maybe Quantity -- ^ percent of the portfolio's value, unrounded
,htUgain :: Maybe [Amount] -- ^ total unrealised gain, when values and costs are comparable (of the holdings whose value is known)
,htUgainPct :: Maybe Quantity -- ^ total unrealised gain percent, unrounded (likewise)
,htRgain :: [Amount] -- ^ total realised gain, per cost commodity
,htXirr :: Maybe Double -- ^ the portfolio's annualised internal rate of return percent (likewise)
,htFlows :: [(Day, Amount)] -- ^ the dated cashflows (negative = money invested) which XIRR is calculated from
-- (of the holdings whose value is known); not displayed
,htValuedCost :: [Amount] -- ^ the total cost of the holdings counted in the value; not displayed
,htUnpriced :: [CommoditySymbol]
-- ^ the commodities left out of the value, UGain, UGain%, XIRR and cashflows:
-- those held with no market price for some lot, so whose value is unknown
-- (and in period gains, those left out at the start or the end; see holdingsPeriodGains)
}
-- | One display line of the holdings report.
data HoldingsLine
-- | An account heading row (tree mode): an account with subaccounts
-- or several commodities, showing its subtree's totals.
= HoldingsHeading {
hlIndent :: Int -- ^ tree indent depth, 0 at top level
,hlAccount :: AccountName -- ^ the full account name
,hlDisplay :: T.Text -- ^ the name to display: the leaf name, or a squashed chain like b:c
,hlTotals :: HoldingsTotals -- ^ the account's subtree totals (see hrAccountTotals)
}
-- | A holding's line: a position, lot, or depth-clipped aggregate,
-- one line per held commodity.
| HoldingsPosition {
hlIndent :: Int -- ^ tree indent depth, 0 at top level and in list mode
,hlAccount :: AccountName -- ^ the account (or lot subaccount) the line belongs to
,hlDisplay :: T.Text -- ^ the name to display: the account name (list mode, or a combined tree row), its commodity (a position under its account's heading), or a lot's name
,hlIsLot :: Bool -- ^ is this a lot subaccount's line ?
,hlHolding :: Holding
}
-- | A computed holdings report: the display lines and totals shown by
-- the holdings command, renderable by any UI.
data HoldingsReport = HoldingsReport {
hrDate :: Day -- ^ the date holdings are shown at: the day before the (exclusive) report end date if specified, otherwise today
,hrLines :: [HoldingsLine]
-- ^ the display lines in display order: flat holdings in list
-- mode, or account sections in tree mode
,hrRows :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]
-- ^ the holdings as flat records, for machine-readable output:
-- each holding, paired with its report row (a row holding
-- several commodities repeats on several lines)
,hrTotals :: HoldingsTotals -- ^ the grand totals row's components
,hrAccountTotals :: AccountName -> HoldingsTotals
-- ^ the totals of the lots at or under any one account, computed
-- like the grand totals row (eg for an account heading row);
-- Weight is relative to the whole portfolio's value
,hrTotalsExcluding :: [CommoditySymbol] -> HoldingsTotals
-- ^ the grand totals as computed (before any period gains), leaving
-- these commodities out of the value, gains and cashflows too
-- (as if unpriced; see htUnpriced)
,hrAccountTotalsExcluding :: [CommoditySymbol] -> AccountName -> HoldingsTotals
-- ^ likewise for an account's totals
,hrUnitCostHeading :: T.Text -- ^ what the unit cost column shows: "Unit cost", "Avg cost", or "Unit/Avg cost"
,hrStyles :: M.Map CommoditySymbol AmountStyle
-- ^ the journal's display styles with hroRounding applied, plus a
-- style for the "%" commodity, for showing the percent columns
-- (see showPercentWith)
,hrGainsPeriod :: Maybe DateSpan
-- ^ when the report has a start date: the report period, from it to
-- the report date (inclusive), which the gain columns (UGain, UGain%,
-- RGain, XIRR) then cover instead of each holding's whole life
-- (see holdingsPeriodGains)
,hrKeepLot :: (AccountName, CommoditySymbol) -> Bool
-- ^ which lots (lot subaccount, commodity) this report counts: all,
-- or with change:/balance: terms, those of the lines shown
}
-- | Chart a holdings report: a bar for each holding (a commodity in an account, or a lot), in each of its commodities' panels
-- (see 'holdingsBarsChart'). Holdings are labelled by account (with --drop applied) and commodity, also in tree mode,
-- since account headings are not drawn. Their values are not marked, since each bar's solid part reaches its value
-- (cost basis and gain, or the part of the cost basis still worth, with the part lost beyond it, hatched).
holdingsReportAsChart :: ReportOpts -> T.Text -> HoldingsReport -> Chart
holdingsReportAsChart ropts title rpt =
holdingsBarsChart ropts MarkNone (hrStyles rpt) title (XCategories $ map label positions) [holdingBarParts h | (_, _, h) <- positions]
where
-- each holding's account, whether it is a lot, and the holding
positions = [(a, islot, h) | HoldingsPosition{hlAccount = a, hlIsLot = islot, hlHolding = h} <- hrLines rpt]
-- eg "assets:broker AAPL", or for a lot, "assets:broker AAPL {2024-01-10, $150}"
label (acct, islot, h) = ChartLabel (name acct) (name $ accountNameDrop (drop_ ropts) acct) 0 Nothing True []
where
name a
| islot = T.unwords [parentAccountName a, hCommodity h, accountLeafName a]
| otherwise = a <> " " <> hCommodity h
-- | Chart holdings reports at the ends of some periods: a bar for each period, showing all the holdings then,
-- as their total cost basis and their net unrealised gain or loss (see 'holdingsBarsChart').
-- Periods are labelled by their end dates, the holdings' dates.
-- When the reports' gain columns cover each period, or the time since the first period's start
-- (see 'holdingsPeriodReports'), the chart shows those gains instead (see 'holdingsGainsChart'),
-- since the holdings' unrealised gains in this chart are always since acquisition.
-- As in the table, the periods whose values and gains exclude holdings with no market price are starred,
-- and a note says which.
holdingsReportsAsChart :: ReportOpts -> BalanceAccumulation -> T.Text -> [(DateSpan, HoldingsReport)] -> Chart
holdingsReportsAsChart ropts accum title rpts = chart{chNotes = maybeToList note}
where
chart = case accum of
Historical -> holdingsBarsChart ropts MarkLine (maybe M.empty (hrStyles . snd) $ headMay rpts) title xaxis
[ mconcat $ map (holdingBarParts . snd) $ hrRows r | (_, r) <- rpts ]
_ -> holdingsGainsChart ropts title xaxis
[ (fromMaybe [] $ htUgain tot, htRgain tot) | (_, r) <- rpts, let tot = hrTotals r ]
xaxis = XPeriods [(spn, showDate (hrDate r) <> if null (leftout r) then "" else "*") | (spn, r) <- rpts]
leftout = totalsLeftOut . hrTotals
note = case nubSort $ concatMap (leftout . snd) rpts of
[] -> Nothing
cs -> Just $ ("* " <>) $
-- TRANSLATORS: a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".
I18n.trf (translations_ ropts) "Values and gains exclude holdings with no market price: {commodities}"
[("commodities", T.intercalate ", " $ map quoteCommoditySymbolIfNeeded cs)]
-- | A chart of holdings' gains at some x positions (eg period ends), from their unrealised and realised gains there:
-- a bar for each, in each commodity's panel, diverging from zero: gains (revenue colour) above, losses (expense colour) below,
-- the realised ones solid, the unrealised ones hatched, since they are not yet final. The net gain is their total,
-- drawn as a line over time, like other reports' totals.
holdingsGainsChart :: ReportOpts -> T.Text -> XAxis -> [([Amount], [Amount])] -> Chart
holdingsGainsChart ReportOpts{translations_} title xaxis gains =
Chart{chTitle = title, chXAxis = xaxis, chPanels = map panel $ commoditiesByUse amts, chNotes = []}
where
amts = concat [us ++ rs | (us, rs) <- gains]
tr = I18n.tr translations_
panel c = Panel
{ pnUnit = unitAmount c amts
, pnSeries = [ Series (ChartLabel name name 0 typ False []) role mark vals 0 0
| (name, typ, role, mark, valueof) <- specs
, let vals = [valueof (quantityOf us) (quantityOf rs) | (us, rs) <- gains]
, any isJust vals ]
, pnGroupNames = []
, pnScale = Nothing
, pnLayout = Diverging
, pnCounts = False
, pnSummary = []
, pnValueLabels = []
}
where
-- each series: its name, type, role, mark, and value from the unrealised and realised gains, if any
specs =
[ (tr "Realised gain", Just Revenue, SeriesItem, MarkBar, \_ r -> r >>= positive)
, (tr "Unrealised gain", Just Revenue, SeriesProvisional, MarkBar, \u _ -> u >>= positive)
, (tr "Realised loss", Just Expense, SeriesItem, MarkBar, \_ r -> r >>= negative)
, (tr "Unrealised loss", Just Expense, SeriesProvisional, MarkBar, \u _ -> u >>= negative)
, (tr "Net gain", Nothing, SeriesTotal, MarkLine, \u r -> if isJust u || isJust r then Just (fromMaybe 0 u + fromMaybe 0 r) else Nothing)
]
positive q = if q > 0 then Just q else Nothing
negative q = if q < 0 then Just q else Nothing
quantityOf as = case [aquantity a | a <- as, acommodity a == c] of
[] -> Nothing
qs -> Just $ sum qs
-- | The commodities of these amounts, most used first (then by name): a chart's panels, in order.
commoditiesByUse :: [Amount] -> [CommoditySymbol]
commoditiesByUse amts = map fst $ sortOn (\(c, n) -> (Down n, c)) $ M.toList $ M.fromListWith (+) [(acommodity a, 1 :: Int) | a <- amts]
-- | A holding's amounts, for a bar in a holdings chart: its market value and cost basis, if it has a market price
-- (or if its value is not comparable with its cost basis, its value twice, as having no gain or loss);
-- and its cost basis, if it has no market price.
holdingBarParts :: Holding -> ([Amount], [Amount], [Amount])
holdingBarParts h
| null (hValue h) = ([], [], hCost h)
| comparable = (hValue h, hCost h, [])
| otherwise = (hValue h, hValue h, [])
where
-- the value and cost are in the same commodities (as for UGain, which can't be
-- checked instead, since with a start date it can be blank for another reason)
comparable = not (null $ hCost h) && commodities (hValue h) == commodities (hCost h)
commodities = nubSort . map acommodity
-- | A chart of holdings: a bar at each x position, in each commodity's panel, from the market value, cost basis
-- and cost basis without a market price, of one or more holdings there (see 'holdingBarParts').
-- Holdings with a market price are drawn as their cost basis and their unrealised gain, stacked, reaching their value;
-- or with an unrealised loss, as the part of their cost basis they are worth, and the part lost (hatched), reaching their cost basis.
-- Holdings without a market price are drawn as their cost basis, beyond those, in a muted colour.
-- The market values are the chart's total, drawn with the given mark: none for separate holdings, whose bars' solid parts
-- reach their values (shown as text), or a line over time, like other reports' totals. Graphical charts show the unrealised gain percents
-- instead (with these styles, for the % commodity), where there is a market price, since the axis shows the values.
holdingsBarsChart :: ReportOpts -> Mark -> M.Map CommoditySymbol AmountStyle -> T.Text -> XAxis -> [([Amount], [Amount], [Amount])] -> Chart
holdingsBarsChart ReportOpts{translations_} totalmark styles title xaxis parts =
Chart{chTitle = title, chXAxis = xaxis, chPanels = map panel $ commoditiesByUse amts, chNotes = []}
where
amts = concat [vs ++ ks ++ us | (vs, ks, us) <- parts]
tr = I18n.tr translations_
panel c = Panel
{ pnUnit = unitAmount c amts
, pnSeries = [ Series (ChartLabel name name 0 typ False []) role mark vals 0 0
| ((name, typ, role, mark), vals) <- zip specs $ transpose [barValues vs ks us | (vs, ks, us) <- parts]
, any isJust vals || role == SeriesTotal ] -- the values, even if none, so that a cost is not shown as one
, pnGroupNames = []
, pnScale = Nothing
, pnLayout = Diverging
, pnCounts = False
, pnSummary = []
, pnValueLabels = [gainPercent (quantityOf vs) (quantityOf ks) | (vs, ks, _) <- parts]
}
where
-- eg +12.5%, -3.0%
gainPercent mv mk = case (mv, mk) of
(Just v, Just k) | k /= 0 -> let p = (v - k) / abs k * 100 in Just $ (if p > 0 then "+" else "") <> showPercentWith styles p
_ -> Nothing
specs =
[ (tr "Cost", Just Asset, SeriesItem, MarkBar)
, (tr "Unrealised gain", Just Revenue, SeriesItem, MarkBar)
, (tr "Unrealised loss", Just Expense, SeriesShortfall, MarkBar)
, (tr "No market price", Nothing, SeriesOther, MarkBar)
, (tr "Value", Nothing, SeriesTotal, totalmark)
]
-- A bar's values for those series, in this commodity: the value and cost basis, the smaller of them
-- stacked with the difference, a gain or loss; then the cost basis without a market price.
-- (Values and costs are of one sign, negative for a short position, whose gain is a smaller value.)
barValues vs ks us = case (quantityOf vs, quantityOf ks) of
(Just v, Just k) ->
let (base, end) = if abs v <= abs k then (v, k) else (k, v)
ugain = v - k
in [Just base, nonzero (ugain > 0) (end - base), nonzero (ugain < 0) (end - base), quantityOf us, Just v]
_ -> [Nothing, Nothing, Nothing, quantityOf us, Nothing]
quantityOf as = case [aquantity a | a <- as, acommodity a == c] of
[] -> Nothing
qs -> Just $ sum qs
nonzero ok q = if ok && q /= 0 then Just q else Nothing
-- | Compute the holdings report: the assets held in lot-tracked accounts
-- as of the report end date, one line per account (or per lot, with
-- hroLots) and held commodity, plus grand totals. In tree mode the
-- display lines are instead account sections (see holdingsTreeLines),
-- while the flat records (hrRows) keep the list-mode shape.
--
-- The journal must have its lot detail (lot subaccounts and synthetic
-- postings) uncollapsed, as the holdings command receives it
-- (see maybePrepareLotDetail); this report aggregates lots itself.
-- A --value=then valuation strategy is not supported; callers reject it.
holdingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
holdingsReport hro0 rspec@ReportSpec{_rsReportOpts=ropts'} j'
| accountlistmode_ ropts' == ALTree = treeHoldingsReport hro rspec j'
| otherwise = flatHoldingsReport hro rspec j'
where
-- one price oracle for all the flat reports this needs (making one, and
-- filling its cache, is costly with many prices)
hro = hro0{hroPriceOracle = hroPriceOracle hro0 <|> Just (journalPriceOracle (infer_prices_ ropts') j')}
-- | -S's sort key for a holding, or an account's holdings, with this
-- market value (empty if unpriced) and cost: priced things first, largest
-- value first, then unpriced things, largest cost first; or at cost
-- (-B), everything by cost. Amounts of different commodities are
-- compared, and summed, by their quantities alone.
holdingsSortKey :: Bool -> [Amount] -> [Amount] -> (Bool, Down Quantity)
holdingsSortKey atcost val cost
| atcost = (False, Down $ sumq cost)
| null val = (True, Down $ sumq cost)
| otherwise = (False, Down $ sumq val)
where sumq = sum . map aquantity
-- | The tree-mode holdings report: the flat report, with its display
-- lines grouped into account sections. With hroLots, a second flat
-- report gives each position's lots, shown beneath it, and provides
-- the flat records and unit cost heading, as list mode would.
treeHoldingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
treeHoldingsReport hro rspec@ReportSpec{_rsReportOpts=ropts'} j' =
prpt{ hrLines = holdingsTreeLines ropts' prpt mlrpt
, hrRows = hrRows mrpt
, hrUnitCostHeading = hrUnitCostHeading mrpt
}
where
flatrspec = rspec{_rsReportOpts = ropts'{accountlistmode_ = ALFlat}}
prpt = flatHoldingsReport hro{hroLots = False} flatrspec j'
mlrpt | hroLots hro = Just $ flatHoldingsReport hro{hroLots = True} flatrspec j'
| otherwise = Nothing
mrpt = fromMaybe prpt mlrpt
-- | Group a flat holdings report's lines into account sections, as tree
-- mode displays them: an account with subaccounts or several
-- commodities is a heading line showing its subtree's totals, with its
-- own positions beneath it named by their commodity, then its
-- subaccounts; an account holding one commodity with no subaccounts is
-- a single combined line carrying its figures. Boring parents - those
-- with no positions of their own and a single child - are squashed into
-- their child like the balance reports' tree mode, unless no-elide is
-- set; only accounts with holdings exist here, so the squashing
-- considers holding rows alone (#2779). With a lots report given, each
-- position's lots are beneath it. Sibling accounts, the top level
-- included, are in account name order, or with -S, sorted by their
-- subtree's totals, as on their headings (see holdingsSortKey); an
-- account's positions, and their lots, keep the flat report's order.
-- --drop removes the first N levels: the tree's roots are the accounts
-- at level N+1 (a shallower account's own positions, a rare case, show
-- as top-level rows).
holdingsTreeLines :: ReportOpts -> HoldingsReport -> Maybe HoldingsReport -> [HoldingsLine]
holdingsTreeLines ropts prpt mlrpt =
concatMap node $ sortOn (acctOrder . fst) $
[(a, False) | a <- allaccts, accountNameLevel a == dropn + 1] ++
[(a, True) | dropn > 0, a <- M.keys posByAcct, accountNameLevel a <= dropn]
where
dropn = drop_ ropts
noelide = no_elide_ ropts
-- sibling accounts' order: with -S, by their subtree's totals; then
-- by their first row in the flat report (without -S, account name order)
acctOrder a = (subtreeSortKey, M.lookup a subtreeIxMap)
where
subtreeSortKey
| sort_amount_ ropts = Just $ holdingsSortKey (conversionop_ ropts == Just ToCost) (fromMaybe [] $ htValue t) (htCost t)
| otherwise = Nothing
where t = hrAccountTotals prpt a
node (a, False) = treeNode 0 a
node (a, True) =
concat [ HoldingsPosition 0 a (accountNameDrop dropn a) False h : lotLines 1 a h
| h <- M.findWithDefault [] a posByAcct ]
posByAcct = M.fromListWith (flip (++)) [(hAccount h, [h]) | (_, h) <- hrRows prpt]
lotsByPos = case mlrpt of
Nothing -> M.empty
Just lr -> M.fromListWith (flip (++))
[ ((lotBaseAccount a, hCommodity h), [h])
| (_, h) <- hrRows lr, let a = hAccount h, isJust (lotSubaccountName a) ]
-- each account's subtree's first flat row, ordering subtrees as the
-- flat report's sort ordered their rows
subtreeIxMap = M.fromListWith min
[(a, ix) | (ix, (_, h)) <- zip [0 :: Int ..] (hrRows prpt), a <- expandAccountName (hAccount h)]
allaccts = M.keys subtreeIxMap
kidsMap = M.map (sortOn acctOrder) $ M.fromListWith (++)
[(parentAccountName a, [a]) | a <- allaccts, accountNameLevel a > 1]
kidsOf a = M.findWithDefault [] a kidsMap
-- squash boring parents into their child
elide disp acct
| not noelide, M.notMember acct posByAcct, [c] <- kidsOf acct =
elide (disp <> ":" <> accountLeafName c) c
| otherwise = (disp, acct)
treeNode d acct0 = case (M.findWithDefault [] acct posByAcct, kidsOf acct) of
([h], []) -> HoldingsPosition d acct disp False h : lotLines (d+1) acct h
(own, kids) ->
HoldingsHeading d acct disp (hrAccountTotals prpt acct) :
concat [ HoldingsPosition (d+1) acct (hCommodity h) False h : lotLines (d+2) acct h
| h <- own ] ++
concatMap (treeNode (d+1)) kids
where (disp, acct) = elide (accountLeafName acct0) acct0
lotLines d acct h =
[ HoldingsPosition d (hAccount lh) (fromMaybe (hAccount lh) $ lotSubaccountName $ hAccount lh) True lh
| lh <- M.findWithDefault [] (acct, hCommodity h) lotsByPos ]
-- | The flat (list-mode) holdings report; also the building block of
-- the tree-mode report. When the query has a start date, the gain
-- columns cover the report period (see holdingsPeriodGains); this needs
-- a second report, of the same lots as of the day before the start date.
flatHoldingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReport hro rspec@ReportSpec{_rsQuery=q, _rsReportOpts=ropts} j =
case queryStartDate False q of
Nothing -> endrpt
Just start -> holdingsPeriodGains start startrpt endrpt
where
startrpt = flatHoldingsReportAt (Just $ hrKeepLot endrpt) hro startrspec j
-- empty_, so that holdings sold off before the start date are seen too
startrspec = rspec{ _rsQuery = And [filterQuery (not . queryIsDateOrDate2) q, Date $ DateSpan Nothing (Just $ Exact start)]
, _rsRowQuery = Any
, _rsReportOpts = ropts{empty_ = True} }
where
endrpt = flatHoldingsReportAt Nothing hro rspec j
-- | Make a holdings report's gain columns cover the period since this
-- start date, given the report of the same lots as of the day before it:
--
-- - UGain is the change in unrealised gain during the period
--
-- - UGain% is that as a percentage of the value at the start plus the
-- net cost added since (so with nothing held at the start, it is the
-- usual gain relative to cost)
--
-- - XIRR is the annualised rate of return over the period, counting the
-- value at the start as money invested then.
--
-- (RGain and the cashflows are already limited to the period, by
-- flatHoldingsReportAt.) These are left blank when a value needed is not
-- known (no market price) or the amounts are in several commodities.
holdingsPeriodGains :: Day -> HoldingsReport -> HoldingsReport -> HoldingsReport
holdingsPeriodGains start startrpt rpt = rpt
{ hrLines = map periodLine $ hrLines rpt
, hrRows = [(r, periodHolding h) | (r, h) <- hrRows rpt]
, hrTotals = periodTotals (hrTotalsExcluding startrpt) (hrTotalsExcluding rpt)
, hrAccountTotals = accountPeriodTotals
, hrGainsPeriod = Just $ DateSpan (Just $ Exact start) (Just $ Exact $ addDays 1 $ hrDate rpt)
}
where
periodLine l@HoldingsHeading{} = l{hlTotals = accountPeriodTotals $ hlAccount l}
periodLine l@HoldingsPosition{} = l{hlHolding = periodHolding $ hlHolding l}
startholdings = M.fromList [((hAccount h, hCommodity h), h) | (_, h) <- hrRows startrpt]
periodHolding h = h{hUgain = fromMaybe [] mugain, hUgainPct = mpct, hXirr = mxirr}
where
(mugain, mpct, mxirr) = periodFigures mstartvalue mstartugain (maybe [] hCost mstarth) mendvalue mendugain (hCost h) (hFlows h)
mstarth = M.lookup (hAccount h, hCommodity h) startholdings
(mstartvalue, mstartugain) = maybe (Just [], Just []) valueAndUgain mstarth
(mendvalue, mendugain) = valueAndUgain h
-- a holding's value and unrealised gain, if known; nothing held is worth nothing
valueAndUgain h'
| amountLooksZero (hUnits h') = (Just [], Just [])
| otherwise = (nonEmpty $ hValue h', nonEmpty $ hUgain h')
nonEmpty as = if null as then Nothing else Just as
-- Period totals from the start and end totals leaving out some
-- commodities. Both leave out the same ones, those whose value is
-- unknown at the start or the end, so the period's figures compare
-- the same holdings.
periodTotals stx tx = t{htUgain = mugain, htUgainPct = mpct, htXirr = mxirr}
where
excl = nubSort $ htUnpriced (stx []) ++ htUnpriced (tx [])
st = stx excl
t = tx excl
(mugain, mpct, mxirr) = periodFigures (htValue st) (totalUgain st) (htValuedCost st) (htValue t) (totalUgain t) (htValuedCost t) (htFlows t)
totalUgain t'
| htValue t' == Just [] && all amountLooksZero (htValuedCost t') = Just [] -- nothing (valued) held
| otherwise = htUgain t'
accountPeriodTotals a = periodTotals (\x -> hrAccountTotalsExcluding startrpt x a) (\x -> hrAccountTotalsExcluding rpt x a)
-- From the value and unrealised gain (when known) and the cost, at the
-- start and at the end, and the period's cashflows: the period's UGain,
-- UGain% and XIRR.
periodFigures :: Maybe [Amount] -> Maybe [Amount] -> [Amount] -> Maybe [Amount] -> Maybe [Amount] -> [Amount] -> [(Day, Amount)]
-> (Maybe [Amount], Maybe Quantity, Maybe Double)
periodFigures mv0 mu0 cost0 mv1 mu1 cost1 flows = (mugain, mpct, mxirr)
where
mugain = do
u0 <- mu0
u1 <- mu1
Just $ case u1 ++ map negate u0 of
[] -> []
as -> amounts $ mixed as
mpct = do
[g] <- mugain
v0 <- mv0
let costs = filter (not . amountLooksZero) $ cost0 ++ cost1
total = sum . map aquantity
guard $ all ((== acommodity g) . acommodity) $ v0 ++ costs
let base = total v0 + total cost1 - total cost0
guard $ base /= 0
Just $ 100 * aquantity g / abs base
mxirr = do
v0 <- mv0
opening <- case filter (not . amountLooksZero) v0 of
[] -> Just []
[v] -> Just [(addDays (-1) start, negate v)]
_ -> Nothing
let flows' = opening ++ flows
-- the value at the end; nothing held is worth zero of the cashflows' commodity
v1 <- case (mv1, flows') of
(Just [v], _) -> Just v
(Just [], (_, a):_) -> Just a{aquantity = 0}
_ -> Nothing
holdingsXirr (hrDate rpt) flows' v1
-- | The annualised internal rate of return, as a percentage, implied by
-- dated cashflows (negative = money invested) plus a final value amount
-- at the report date, when they are all in one commodity. Calculated
-- like roi's IRR (see xirr for the special cases, eg -100% when nothing
-- is left of the money invested). Nothing if it has no solution (eg an
-- infinite rate) or can not be solved.
-- Not for a short position, whose flows are a long position's with the
-- signs reversed: the rate solving those is the same, so it would report
-- a winning short as a loss. A short is recognised by a negative final
-- value (units owed), or when closed, by money received rather than
-- invested in the earliest flow.
holdingsXirr :: Day -> [(Day, Amount)] -> Amount -> Maybe Double
holdingsXirr reportdate flows finalv = do
guard $ not $ null flows
guard $ all ((== acommodity finalv) . acommodity . snd) flows
let earliest = aquantity $ snd $ minimumBy (comparing fst) flows
isshort = aquantity finalv < 0 || (aquantity finalv == 0 && earliest > 0)
guard $ not isshort
either (const Nothing) Just $ xirr reportdate $ (reportdate, aquantity finalv) : [(d, aquantity a) | (d, a) <- flows]
-- | The flat holdings report with its gain columns covering each
-- holding's whole life up to the report end date - except RGain and the
-- cashflows (and so XIRR), which are limited to the report period when
-- the query has a start date (flatHoldingsReport then finishes the job).
-- If a lot filter is given, just those lots are counted, and the query's
-- change:/balance: terms are not consulted.
flatHoldingsReportAt :: Maybe ((AccountName, CommoditySymbol) -> Bool) -> HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport
flatHoldingsReportAt mkeeplot HoldingsReportOpts{hroLots=showlots, hroRounding=rounding, hroPriceOracle=mpriceoracle}
rspec@ReportSpec{_rsQuery=q, _rsReportOpts=ropts} j =
HoldingsReport
{ hrDate = reportdate
, hrLines = displaylines
, hrRows = rowlines
, hrTotals = totalsExcluding []
, hrAccountTotals = accountTotalsExcluding []
, hrTotalsExcluding = totalsExcluding
, hrAccountTotalsExcluding = accountTotalsExcluding
, hrUnitCostHeading = unitcostheading
, hrStyles = pctstyles
, hrGainsPeriod = Nothing
, hrKeepLot = keeplot
}
where
-- The date this report shows holdings at: the day before the (exclusive)
-- report end date if specified, otherwise today.
mend = queryEndDate False q
reportdate = maybe (_rsDay rspec) (addDays (-1)) mend
-- The report start date, if any. Realised gains and cashflows are
-- limited to the period from then on.
mstart = queryStartDate False q
inperiod d = maybe True (d >=) mstart
-- The query used to select lot subaccount postings: the report query
-- without its date terms (holdings are cumulative to the end date,
-- added here) and depth terms (--depth only clips the displayed rows;
-- the lots beneath still count).
endq = And [filterQuery (\x -> not $ queryIsDateOrDate2 x || queryIsDepth x) q
,Date $ DateSpan Nothing (Exact <$> mend)]
-- The postings contributing to each lot subaccount, keyed by account
-- and commodity (so amounts in different commodities, not expected in
-- a lot subaccount but possible, don't merge wrongly).
lotpostings :: [((AccountName, CommoditySymbol), (Day, Amount))]
lotpostings =
[ ((paccount p, acommodity a), (postingDate p, a))
| p <- journalPostings j
, isJust $ lotSubaccountName $ paccount p
, endq `matchesPosting` p
, a <- amountsRaw $ pamount p
]
-- The units held in each lot subaccount.
lotmap :: M.Map (AccountName, CommoditySymbol) Amount
lotmap = M.fromListWith (+) [(k, amountStripCost a) | (k, (_, a)) <- lotpostings]
-- Each lot subaccount's cashflows in the cost commodity, for XIRR:
-- each posting's transacted cost if any (so, proceeds when disposing),
-- otherwise its cost basis value. Negative = money invested.
-- A posting with no transacted cost (eg a transfer between accounts, or
-- an opening balance) is dated on its lot's acquisition date, not its own
-- date, so that an account receiving lots measures from when they were
-- acquired, like its UGain and Age (and the totals row, in which a
-- transfer's two postings cancel). With a start date, no earlier than
-- that, since gains are measured from then.
flowmap :: M.Map (AccountName, CommoditySymbol) [(Day, Amount)]
flowmap = matchingLots $ M.fromListWith (++)
[ (k, [(fd, negate flowamt)])
| (k, (d, a)) <- lotpostings
, inperiod d
, Just (fd, flowamt) <- [case acost a of
Just _ -> Just (d, amountCost a)
Nothing -> do
cb <- acostbasis a
c <- cbCost cb
let acqdate = maybe d (\acq -> maybe acq (max acq) mstart) $ cbDate cb
Just (acqdate, multiplyAmount (aquantity a) c)]
]
-- Each lot subaccount's realised gains, in the cost commodity: for each
-- dispose posting with a transacted price and a cost basis, its cost
-- basis minus its transacted cost. For a sale (negative) that is the
-- proceeds minus the basis of the units sold; for a short cover
-- (positive, in a liability account) it is the short-sale basis minus
-- the cost of buying the units back.
-- The gains get their commodity's display style, since the cost bases
-- they are derived from can have more precision (eg from inferred
-- per-unit costs).
rgainmap :: M.Map (AccountName, CommoditySymbol) Amount
rgainmap = matchingLots allrgainmap
allrgainmap = M.map (styleAmounts styles) $ M.fromListWith (+)
[ ((paccount p, acommodity a), basis - transacted)
| p <- journalPostings j
, isDisposePosting p
, isJust $ lotSubaccountName $ paccount p
, endq `matchesPosting` p
, inperiod $ postingDate p
, a <- amountsRaw $ pamount p
, isJust $ acost a
, isJust $ cbCost =<< acostbasis a
, let basis = amountCostBasis a
transacted = amountCost a
, acommodity basis == acommodity transacted
]
-- The current average unit cost of each AVERAGE/AVERAGEALL pool, as of
-- the report end date, keyed by (base account, commodity). Computed
-- from all of the pool's lot postings, whatever the query (see
-- journalAveragePoolTotals). Used to fill in the cost missing from
-- AVERAGE lots' costless subaccount names (see lotsUnder).
poolavgmap :: M.Map (AccountName, CommoditySymbol) Amount
poolavgmap = M.map (\(units, costtot) -> styleAmounts styles $ avgcost nullamt{aquantity=units} costtot)
(journalAveragePoolTotals j mend)
-- The per-row lookups below (lotsOf, rgainsOf, flowsOf and the
-- *Under forms) used to scan a whole per-lot map for every displayed
-- row, making the report roughly O(rows × lots) (#2779). Instead,
-- each map is indexed by account up front, in two groupings:
--
-- "under": a key's data appears under its account and every ancestor,
-- answering "at or under this account" queries directly.
--
-- "own": a key's data appears under its owning row account - the
-- deepest candidate row account at or above it, if any - answering
-- "in this row's own scope" queries. This is what makes overlapping
-- rows disjoint, eg when lots are held in both an account and its
-- subaccount (each of which then gets its own row).
--
-- Each group keeps the map's ascending (account, commodity) key
-- order, as the full scans produced.
underIx :: M.Map (AccountName, CommoditySymbol) v -> M.Map AccountName [(CommoditySymbol, v)]
underIx m = groupIx [(anc, (c, v)) | ((sub, c), v) <- M.toAscList m
, anc <- sub : parentAccountNames sub]
ownIx :: M.Map (AccountName, CommoditySymbol) v -> M.Map AccountName [(CommoditySymbol, v)]
ownIx m = groupIx [(owner, (c, v)) | ((sub, c), v) <- M.toAscList m
, Just owner <- [ownerOf sub]]
-- Group an ascending association list by account, each group keeping
-- the input order (fromListWith prepends, hence the reverse).
groupIx :: [(AccountName, a)] -> M.Map AccountName [a]
groupIx = M.fromListWith (++) . reverse . map (fmap (:[]))
-- A lot subaccount's owning row account: the deepest candidate row
-- account at or above it, if any.
ownerOf :: AccountName -> Maybe AccountName
ownerOf sub = find (`S.member` candaccset) (sub : parentAccountNames sub)
candaccset = S.fromList candaccts
ownFlowIx = ownIx flowmap
ownRgainIx = ownIx rgainmap
underFlowIx = underIx flowmap
underRgainIx = underIx rgainmap
allUnderRgainIx = underIx allrgainmap
-- Narrow an indexed group to one held commodity, if specified.
inComm :: Maybe CommoditySymbol -> [(CommoditySymbol, v)] -> [v]
inComm mc kvs = [v | (c, v) <- kvs, maybe True (== c) mc]
-- The cashflows of the lots in a row account's own scope.
flowsOf :: AccountName -> Maybe CommoditySymbol -> [(Day, Amount)]
flowsOf acct mc = concat $ inComm mc $ M.findWithDefault [] acct ownFlowIx
-- The realised gains of the lots at or under an account, optionally of one held commodity.
rgainsUnder :: AccountName -> Maybe CommoditySymbol -> [Amount]
rgainsUnder acct mc = inComm mc $ M.findWithDefault [] acct underRgainIx
-- The realised gains of the lots in a row account's own scope.
rgainsOf :: AccountName -> Maybe CommoditySymbol -> [Amount]
rgainsOf acct mc = inComm mc $ M.findWithDefault [] acct ownRgainIx
-- A lot subaccount's cost basis, parsed from its name
-- (which by construction contains the acquisition date and unit cost).
-- The cost gets its commodity's display style, including display
-- precision (lot names can have more precision, eg from inferred
-- per-unit costs), so derived amounts (Unit cost, Cost) are displayed
-- with the standard display precision.
lotBasis :: AccountName -> Maybe CostBasis
lotBasis acct = do
name <- lotSubaccountName acct
cb <- either (const Nothing) Just $ parseLotName parseAmt name
Just cb{cbCost = styleAmounts styles <$> cbCost cb}
where parseAmt = either (const Nothing) Just . parseamount
-- Amounts are displayed normalised to their commodity's display
-- precision by default; hroRounding can choose another rounding strategy.
styles = journalCommodityStylesWith rounding j
priceoracle = fromMaybe (journalPriceOracle (infer_prices_ ropts) j) mpriceoracle
-- The valuation strategy requested with -V/-X/--value, if any.
-- It selects the valuation date and/or the valuation commodity;
-- --value=then is rejected above.
mvalue = value_ ropts
(valuationdate, mtargetcomm) = case mvalue of
Nothing -> (reportdate, Nothing)
Just (AtEnd mc) -> (reportdate, mc)
Just (AtNow mc) -> (_rsDay rspec, mc)
Just (AtDate d mc) -> (d, mc)
Just (AtThen mc) -> (reportdate, mc) -- not supported, rejected above
-- The valuation target commodity for a lot: the commodity requested
-- with -V/-X/--value if any, otherwise the lot's own cost commodity
-- when known, otherwise none (the price oracle picks a default).
lotValuationComm :: Maybe CostBasis -> Maybe CommoditySymbol
lotValuationComm mcb = case mvalue of
Nothing -> acommodity <$> (cbCost =<< mcb)
Just _ -> mtargetcomm
-- Value one lot at the valuation date: Just (unit price, total value)
-- if it has a market price to its target commodity.
lotValuation :: (Amount, Maybe CostBasis) -> Maybe (Amount, Amount)
lotValuation (a, mcb) = do
(pcomm, rate) <- priceoracle (valuationdate, acommodity a, lotValuationComm mcb)
let mkamt n = styleAmounts styles $ amountSetFullPrecisionUpTo Nothing
nullamt{acommodity=pcomm, aquantity=n}
Just (mkamt rate, mkamt (rate * aquantity a))
-- Value some lots at the valuation date: Just (their distinct unit
-- prices, their total value per value commodity) if every lot has a
-- market price, otherwise Nothing. Each lot is valued separately in
-- its own target commodity, so values (and their sums, like the
-- totals row) don't depend on how lots are grouped into display rows
-- (by --depth, --pivot, tree mode etc).
lotsValuation :: [(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount])
lotsValuation lots = do
pvs <- mapM lotValuation lots
Just (nubSortOn (\a -> (acommodity a, aquantity a)) $ map fst pvs
,sumAmounts $ map snd pvs)
-- The market value of the lots at or under an account whose value is
-- known (see mvalueExcluding), per value commodity.
mvalueUnder :: AccountName -> Maybe [Amount]
mvalueUnder acct = mvalueExcluding (unpricedCommodities lots) lots
where lots = lotsUnder acct
-- How to convert cost amounts (Cost, Unit/Avg cost, RGain, and the
-- cost side of UGain) for display when -V/-X/--value is in effect:
-- convert to the requested commodity, or to the given fallback
-- commodity (the row's or portfolio's value commodity), at the
-- valuation date. Costs already in the target commodity, or with no
-- target or no market price, are left unchanged.
costValuerTo :: Maybe CommoditySymbol -> Amount -> Amount
costValuerTo mfallback = case mvalue of
Nothing -> id
Just _ -> case mtargetcomm <|> mfallback of
Nothing -> id
-- styleAmounts is reapplied after conversion, since
-- amountValueAtDate leaves full precision displayed
Just tc -> \a -> if acommodity a == tc then a
else styleAmounts styles $
amountValueAtDate priceoracle styles (Just tc) valuationdate a
rowCostValuer :: PeriodicReportRow DisplayName MixedAmount -> Amount -> Amount
rowCostValuer r = costValuerTo $ singleCommodity $ mvalueUnder (prrFullName r)
xirrOf = holdingsXirr reportdate
-- The total value of those lots which have a market price, per value
-- commodity.
pricedValue :: [(Amount, Maybe CostBasis)] -> [Amount]
pricedValue lots = sumAmounts [v | Just (_, v) <- map lotValuation lots]
-- The total value of all the priced holdings, including any lines
-- hidden by change: or balance: terms. Weight is relative to this, so
-- those terms hide lines without changing the others' weights, and
-- unpriced holdings (which get no Weight) don't prevent the others'.
wholevalue :: [Amount]
wholevalue = pricedValue [l | ((sub, _), l) <- M.toList alllotbases, isJust $ ownerOf sub]
-- A value's percentage of the priced portfolio's value (wholevalue),
-- when both are single amounts in the same commodity.
weightPct :: [Amount] -> Maybe Quantity
weightPct val = do
[t] <- Just wholevalue
[v] <- Just val
guard $ acommodity v == acommodity t && aquantity t /= 0
Just $ 100 * aquantity v / aquantity t
-- The commodity display styles, plus a default style for the "%"
-- commodity if none is declared or inferred: one decimal digit,
-- and the % sign on the right with no space.
pctstyles = M.union styles $ M.singleton "%" $
amountstyle{ascommodityside=R, asprecision=Precision 1, asrounding=HardRounding}
-- The unrealised gains implied by value and cost amounts: value minus
-- cost per commodity, when they cover exactly the same (nonempty) set
-- of commodities; otherwise Nothing.
gainAmounts :: [Amount] -> [Amount] -> Maybe [Amount]
gainAmounts vals costs = do
guard $ not (null vs) && map acommodity vs == map acommodity cs
Just $ zipWith gain1 vs cs
where
vs = sumAmounts vals
cs = sumAmounts costs
gain1 v c = styleAmounts styles $ amountSetFullPrecisionUpTo Nothing
nullamt{acommodity=acommodity v, aquantity=aquantity v - aquantity c}
-- The percent gain, when the gains and the costs are single amounts
-- in the same commodity and the cost is nonzero. Relative to the cost's
-- magnitude, so a short position's gain (its cost being negative) keeps
-- its sign.
gainPct :: [Amount] -> [Amount] -> Maybe Quantity
gainPct gains costs = do
[g] <- Just gains
[c] <- Just $ sumAmounts costs
guard $ acommodity g == acommodity c && aquantity c /= 0
Just $ 100 * aquantity g / abs (aquantity c)
-- A row's units of lot-tracked commodities: the sum of the lots in
-- its own scope, one amount per commodity. (Not the row's report
-- balance: a depth-clipped or pivoted row could also aggregate
-- same-commodity balances from non-lot-tracked accounts, which would
-- make Units inconsistent with the lot-derived Cost and gain columns.)
rowUnitAmounts :: PeriodicReportRow DisplayName MixedAmount -> [Amount]
rowUnitAmounts r =
filter (not . amountLooksZero) $ sumAmounts $
map fst $ lotsOf $ prrFullName r
-- The nonempty lots as (units, cost basis), keyed like lotmap.
-- A lot's cost basis comes from its subaccount name, parsed once
-- here; when the name has no cost part (AVERAGE lots' names omit it,
-- staying stable across re-averaging), the pool's current average
-- cost is filled in instead.
alllotbases :: M.Map (AccountName, CommoditySymbol) (Amount, Maybe CostBasis)
alllotbases = M.mapWithKey mklot $ M.filter (not . amountLooksZero) lotmap
mklot (sub, _) a = (a, addPoolAvg sub a <$> lotBasis sub)
where
addPoolAvg sub' a' cb@CostBasis{cbCost=Nothing} =
cb{cbCost = M.lookup (lotBaseAccount sub', acommodity a') poolavgmap}
addPoolAvg _ _ cb = cb
lotbases = matchingLots alllotbases
underLotIx = underIx lotbases
ownLotIx = ownIx lotbases
allUnderLotIx = underIx alllotbases
allOwnLotIx = ownIx alllotbases
-- The query's change: and balance: terms. In this report they test each
-- displayed line: one commodity in one row account (see lineMatches).
-- The lots, realised gains and cashflows of the other lines are left out
-- (by matchingLots), so that the totals and tree mode's headings follow
-- the lines shown (but Weight stays relative to all the holdings; see
-- wholevalue). Row ownership is decided from all lots.
rowq = _rsRowQuery rspec
matchingLots :: M.Map (AccountName, CommoditySymbol) v -> M.Map (AccountName, CommoditySymbol) v
matchingLots
| isJust mkeeplot || not (queryIsNull rowq) = M.filterWithKey (\k _ -> keeplot k)
| otherwise = id
keeplot :: (AccountName, CommoditySymbol) -> Bool
keeplot = case mkeeplot of
Just keep -> keep
Nothing | queryIsNull rowq -> const True
| otherwise -> \(sub, c) -> maybe False (\o -> (o, c) `S.member` matchinglines) $ ownerOf sub
matchinglines = S.fromList
[(o, c) | (o, c) <- nubSort [(o, c) | (sub, c) <- M.keys lotmap, Just o <- [ownerOf sub]], lineMatches o c]
-- Each lot subaccount's change in units during the report period (all of
-- its units, if the report has no start date), with its cost basis; the
-- unchanged ones are left out.
lotchanges :: M.Map (AccountName, CommoditySymbol) (Amount, Maybe CostBasis)
lotchanges = M.mapWithKey mklot $ M.filter (not . amountLooksZero) $ M.fromListWith (+)
[(k, amountStripCost a) | (k, (d, a)) <- lotpostings, inperiod d]
ownLotChangeIx = ownIx lotchanges
-- Does a row account's line for this commodity match the change: and
-- balance: terms ? A line has two balances, its units and their market
-- value (if all are priced), and likewise two changes: its change in
-- units during the report period, and that valued (at the valuation
-- date, as in the balance reports). A term with no commodity symbol tests
-- the units; one with a symbol tests whichever of the two amounts is in
-- that commodity, so eg balance:'>$1000' tests the value, and doesn't
-- match an unpriced line. With -B/--cost, the cost is tested instead of
-- the value, as displayed in Total cost (the known costs; and with
-- -V/-X, converted like the row's costs).
lineMatches :: AccountName -> CommoditySymbol -> Bool
lineMatches acct c = go rowq
where
(balunits, balvalue) = unitsAndValue allOwnLotIx
(chgunits, chgvalue) = unitsAndValue ownLotChangeIx
unitsAndValue ix = (mixed $ map fst lots, if atcost then cost else mktvalue)
where
lots = [l | (c', l) <- M.findWithDefault [] acct ix, c' == c]
mktvalue = maybe nullmixedamt (mixed . snd) $ lotsValuation lots
cost = mixed [costvaluer $ multiplyAmount (aquantity a) cb | (a, mcb) <- lots, Just cb <- [cbCost =<< mcb]]
-- like rowCostValuer, but from all lots, since this decides which are kept
costvaluer = costValuerTo $ case lotsValuation $ map snd $ M.findWithDefault [] acct allUnderLotIx of
Just (_, [v]) -> Just $ acommodity v
_ -> Nothing
go (And qs) = all go qs
go (Not t) = not $ go t
go (Change ord n mc) = Amt ord n mc `matchesMixedAmount` pick mc chgunits chgvalue
go (Balance ord n mc) = Amt ord n mc `matchesMixedAmount` pick mc balunits balvalue
go _ = True
pick Nothing units _ = units
pick _ units val = maPlus units val
-- The lots held at or under the given account, excluding empty ones.
lotsUnder :: AccountName -> [(Amount, Maybe CostBasis)]
lotsUnder acct = map snd $ M.findWithDefault [] acct underLotIx
-- The lots in a row account's own scope, excluding empty ones.
lotsOf :: AccountName -> [(Amount, Maybe CostBasis)]
lotsOf acct = map snd $ M.findWithDefault [] acct ownLotIx
-- Report rows come from a single-period, end-balances multiBalanceReport:
-- on the lot-detailed journal with --lots (rows are lot subaccounts),
-- on the collapsed journal otherwise (rows are the base accounts).
-- Non-holding accounts are filtered out.
-- Cost conversion and valuation (-B/-V/--value) are disabled:
-- holdings does its own valuation, and units should stay units.
-- Nor does it apply the change:/balance: terms; they are tested here (see rowq).
-- Its query has no start date, since holdings are cumulative (a start date
-- after the last posting would otherwise leave an empty report span).
mbr = multiBalanceReport rspec' j'
where
rspec' = rspec{_rsRowQuery = Any
,_rsQuery = And [filterQuery (not . queryIsDateOrDate2) q, Date $ DateSpan Nothing (Exact <$> mend)]
,_rsReportOpts=ropts{balanceaccum_=Historical, interval_=NoInterval
,conversionop_=Just NoConversionOp, value_=Nothing
,sort_amount_=False}} -- -S sorts by value/cost below, not by units
j' = if showlots then j else journalCollapseLotDetail j
-- Candidate rows: those with lots at or beneath them; with -E/--empty,
-- also those with realised gains at or beneath them (fully disposed
-- accounts/lots, normally hidden).
candidates = filter isholdingrow $ prRows mbr
where
isholdingrow r = not (null (M.findWithDefault [] acct allUnderLotIx))
|| (empty_ ropts && any (not . amountLooksZero . snd) (M.findWithDefault [] acct allUnderRgainIx))
where acct = prrFullName r
candaccts = map prrFullName candidates
-- Rows to display: the candidates, except those with nothing in
-- their own scope (eg a base account row whose lots all appear in
-- displayed lot subaccount rows). A row holding lots directly is
-- kept even when a deeper row also displays; it shows just its own
-- lots (see ownIx).
rows = filter keeprow candidates
where
keeprow r = not (null (lotsOf acct))
|| (empty_ ropts && not (null $ rgainOnlyCommodities acct))
where acct = prrFullName r
-- The commodities with nonzero realised gains in this row account's own
-- scope but no units held there (eg fully sold off).
rgainOnlyCommodities :: AccountName -> [CommoditySymbol]
rgainOnlyCommodities acct =
nubSort [ c | (c, g) <- M.findWithDefault [] acct ownRgainIx, not $ amountLooksZero g
, c `notElem` map fst (M.findWithDefault [] acct allOwnLotIx) ]
-- The topmost displayed rows: those not contained in another displayed
-- row. Totals are computed from these, to avoid double counting.
toprows = [ r | r <- rows
, not $ any (`S.member` rowaccset) (parentAccountNames $ prrFullName r) ]
where rowaccset = S.fromList $ map prrFullName rows
-- With -B/--cost, -S sorts and the change:/balance: terms test cost instead of value.
atcost = conversionop_ ropts == Just ToCost
-- The displayed table lines: each report row's holdings, one line per
-- commodity, with the report row kept for rendering the account cell
-- (repeated on each of its lines). They are in account name order, or
-- with -S, each line is sorted by its own amounts (see
-- holdingsSortKey), ties keeping the account name order. Tree mode
-- groups these into account sections, keeping this order within each.
rowlines :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]
rowlines
| sort_amount_ ropts = sortOn (\(_, h) -> holdingsSortKey atcost (hValue h) (hCost h)) namelines
| otherwise = namelines
where namelines = [(r, h) | r <- rows, h <- rowHoldings r]
-- One display line per report line.
displaylines :: [HoldingsLine]
displaylines =
[ HoldingsPosition
{ hlIndent = prrIndent r
, hlAccount = prrFullName r
, hlDisplay = prrDisplayName r
, hlIsLot = isJust $ lotSubaccountName $ prrFullName r
, hlHolding = h }
| (r, h) <- rowlines ]
-- The cost column's heading matches what's shown: "Avg cost" on rows
-- aggregating multiple lots (the default) or when the lots shown all
-- belong to AVERAGE/AVERAGEALL pools (whose per-lot rows show the
-- pool's average cost); "Unit cost" when each lot shows its own cost;
-- "Unit/Avg cost" when both kinds of lot are shown.
-- TRANSLATORS: the holdings table's cost column heading, translated where it is displayed.
unitcostheading :: T.Text
unitcostheading
| not showlots || allavg = I18n.i18n "Avg cost"
| anyavg = I18n.i18n "Unit/Avg cost"
| otherwise = I18n.i18n "Unit cost"
where
avgs = [ fst (resolveReductionMethodForAccount j (lotBaseAccount sub) c)
`elem` [AVERAGE, AVERAGEALL]
| (sub, c) <- M.keys lotmap ]
allavg = not (null avgs) && and avgs
anyavg = or avgs
-- Sum amounts per commodity, keeping an empty list empty
-- (unlike amounts . mixed, which would make it a single zero).
sumAmounts :: [Amount] -> [Amount]
sumAmounts [] = []
sumAmounts as = amounts $ mixed as
-- A report row's holdings, one per commodity, in the same order as its
-- unit amounts. With -E/--empty, these are followed by a zero-units
-- holding for each commodity no longer held at or under the row's
-- account but with realised gains, keeping those visible (eg a
-- commodity fully sold off); without -E such rows are hidden (their
-- gains still count in the totals row).
rowHoldings :: PeriodicReportRow DisplayName MixedAmount -> [Holding]
rowHoldings r = map rec $ heldamts ++ rgainonlyamts
where
acct = prrFullName r
heldamts = rowUnitAmounts r
rgainonlyamts
| not $ empty_ ropts = []
| otherwise = [nullamt{acommodity=c} | c <- rgainOnlyCommodities acct]
rec qa = Holding
{ hAccount = acct
, hCommodity = c
, hDate = mdate
, hAge = diffDays reportdate <$> mdate
, hUnits = styleAmounts styles qa
, hUnitCost = mucost
, hCost = sumAmounts ccosts
, hPrice = prices
, hValue = vals
, hWeight = weightPct vals
, hUgain = gains
, hUgainPct = gainPct gains ccosts
, hRgain = sumAmounts $ map (rowCostValuer r) $ rgainsOf acct (Just c)
, hXirr = mxirr
, hFlows = flowsOf acct (Just c)
}
where
c = acommodity qa
clots = filter ((==c) . acommodity . fst) $ lotsOf acct
dates = nubSort [cbDate =<< mcb | (_, mcb) <- clots]
mdate = case dates of
[Just dt] -> Just dt
_ -> Nothing
ccosts
-- a line with no units held (shown for its realised gain) costs zero, in the gain's commodity
| null clots = [g{aquantity = 0} | g <- take 1 $ rgainsOf acct (Just c)]
| otherwise = [rowCostValuer r $ multiplyAmount (aquantity a) cb | (a, mcb) <- clots, Just cb <- [cbCost =<< mcb]]
mucost = case (clots, ccosts) of
([(_, mcb)], _) -> rowCostValuer r <$> (cbCost =<< mcb)
(_, _:_) | [totcost] <- amounts (mixed ccosts)
, not $ amountLooksZero qa
-> Just $ avgcost qa totcost
_ -> Nothing
-- The line's lots to value; a zero-units (rgain-only) line
-- values a synthetic zero lot, so a market price and a zero
-- value can still be shown.
vlots = if null clots then [(qa, Nothing)] else clots
(prices, vals) = fromMaybe ([], []) $ lotsValuation vlots
gains = fromMaybe [] $ gainAmounts vals ccosts
mxirr = do
[v] <- Just vals
xirrOf (flowsOf acct (Just c)) v
-- The grand totals, summed over the topmost displayed rows; the
-- RGain and XIRR components cover all the lots within the query and
-- end date, whatever rows are displayed (#2769; see HoldingsTotals).
-- The value, gains and cashflows leave out the holdings whose value is
-- unknown, and those of the given commodities (see htUnpriced).
totalsExcluding :: [CommoditySymbol] -> HoldingsTotals
totalsExcluding excl0 = HoldingsTotals
{ htUnits = case totunits of [u] -> Just u; _ -> Nothing
, htAvgCost = case (totunits, sumAmounts totcosts) of
([u], [c]) -> Just $ avgcost u c
_ -> Nothing
, htCost = amounts $ mixed totcosts
, htPrice = singlePrice toplots
, htValue = mvalue'
, htWeight = weightPct $ pricedValue toplots
, htUgain = mgains
, htUgainPct = gainPct (fromMaybe [] mgains) valuedcosts
, htRgain = case map (costValuerTo mvaluecomm) $ M.elems rgainmap of
[] -> []
rs -> amounts $ mixed rs
, htXirr = do
[tv] <- mvalue'
xirrOf flows tv
, htFlows = flows
, htValuedCost = amounts $ mixed valuedcosts
, htUnpriced = excl
}
where
toplots = concatMap (lotsUnder . prrFullName) toprows
excl = nubSort $ excl0 ++ unpricedCommodities toplots
mvalue' = mvalueExcluding excl toplots
mvaluecomm = singleCommodity mvalue'
totunits = filter (not . amountLooksZero) $ sumAmounts $ map fst toplots
-- each lot's cost, with its units
lotcosts = [ (a, rowCostValuer r $ multiplyAmount (aquantity a) c)
| r <- toprows, (a, mcb) <- lotsUnder (prrFullName r), Just c <- [cbCost =<< mcb] ]
totcosts = map snd lotcosts
valuedcosts = [k | (a, k) <- lotcosts, acommodity a `notElem` excl]
mgains = mvalue' >>= \v -> gainAmounts v valuedcosts
flows = concat [fs | ((_, c), fs) <- M.toList flowmap, c `notElem` excl]
-- The totals of the lots at or under one account, computed like the
-- grand totals row: an account heading row's figures. Like those,
-- RGain and XIRR cover all the subtree's lots within the query and
-- end date, including fully disposed ones with no row (#2769), and
-- the value, gains and cashflows leave out the holdings whose value is
-- unknown, and those of the given commodities. Weight is relative to
-- the whole portfolio's value.
accountTotalsExcluding :: [CommoditySymbol] -> AccountName -> HoldingsTotals
accountTotalsExcluding excl0 acct = HoldingsTotals
{ htUnits = case units of [u] -> Just u; _ -> Nothing
, htAvgCost = case (units, sumAmounts costs) of
([u], [c]) -> Just $ avgcost u c
_ -> Nothing
, htCost = sumAmounts costs
, htPrice = singlePrice lots
, htValue = msubvalue
, htWeight = weightPct $ pricedValue lots
, htUgain = mgains
, htUgainPct = gainPct (fromMaybe [] mgains) valuedcosts
, htRgain = sumAmounts $ map (costValuerTo msubvaluecomm) $ rgainsUnder acct Nothing
, htXirr = do
[v] <- msubvalue
xirrOf flows v
, htFlows = flows
, htValuedCost = sumAmounts valuedcosts
, htUnpriced = excl
}
where
lots = lotsUnder acct
excl = nubSort $ excl0 ++ unpricedCommodities lots
units = filter (not . amountLooksZero) $ sumAmounts $ map fst lots
-- each lot's cost, with its units
lotcosts = [ (a, costValuerTo msubvaluecomm $ multiplyAmount (aquantity a) c)
| (a, mcb) <- lots, Just c <- [cbCost =<< mcb] ]
costs = map snd lotcosts
valuedcosts = [k | (a, k) <- lotcosts, acommodity a `notElem` excl]
msubvalue = mvalueExcluding excl lots
msubvaluecomm = singleCommodity msubvalue
mgains = msubvalue >>= \subvalue -> gainAmounts subvalue valuedcosts
flows = concat [fs | (c, fs) <- M.findWithDefault [] acct underFlowIx, c `notElem` excl]
-- The commodities of these lots which have a lot with no market price,
-- so whose holdings' value is unknown.
unpricedCommodities :: [(Amount, Maybe CostBasis)] -> [CommoditySymbol]
unpricedCommodities lots = nubSort [acommodity a | l@(a, _) <- lots, isNothing $ lotValuation l]
-- The market value of these lots, per value commodity, leaving out
-- those of the given commodities (eg the unpriced ones); Nothing if
-- some of the others can't be valued.
mvalueExcluding :: [CommoditySymbol] -> [(Amount, Maybe CostBasis)] -> Maybe [Amount]
mvalueExcluding excl lots = snd <$> lotsValuation (filter ((`notElem` excl) . acommodity . fst) lots)
-- The commodity of a value, when it is a single amount.
singleCommodity :: Maybe [Amount] -> Maybe CommoditySymbol
singleCommodity mv = case mv of
Just [v] -> Just $ acommodity v
_ -> Nothing
-- The unit market price of some lots, when they are all of one commodity
-- and have the same price.
singlePrice :: [(Amount, Maybe CostBasis)] -> Maybe Amount
singlePrice lots = do
[_] <- Just $ nubSort $ map (acommodity . fst) lots
([p], _) <- lotsValuation lots
Just p
-- An average cost: total cost / total units, shown like other amounts
-- in the cost commodity's display precision - but with at least 2
-- decimal digits when the division is inexact and the display
-- precision is less, so eg an average of $56.666... is not shown as
-- the misleading $57.
avgcost qtya costa = amountSetPrecision (Precision p) avg
where
avg = divideAmountAndUpdatePrecision (aquantity qtya) costa
p = clamp pstyle (max 2 pstyle) pdiv
clamp lo hi = max lo . min hi
pdiv = case asprecision (astyle avg) of Precision n -> n; _ -> defaultMaxDisplayPrecision
pstyle = case asprecision (astyle costa) of Precision n -> n; _ -> 2
-- | The commodities whose holdings some totals leave out of their value, gains and XIRR,
-- having no market price, when they show those of other holdings. (When they show none,
-- those are simply blank.)
totalsLeftOut :: HoldingsTotals -> [CommoditySymbol]
totalsLeftOut tot = case htValue tot of
Just (_:_) -> htUnpriced tot
_ -> []
-- | A note saying which commodities' holdings the totals' value, gains and XIRR
-- leave out, having no market price (see 'htUnpriced'), if there are any.
holdingsUnpricedNote :: I18n.Translations -> [CommoditySymbol] -> Maybe T.Text
holdingsUnpricedNote _ [] = Nothing
holdingsUnpricedNote trs cs = Just $
-- TRANSLATORS: a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".
I18n.trf trs "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"
[("commodities", T.intercalate ", " $ map quoteCommoditySymbolIfNeeded cs)]
-- | How many closed positions (an account's commodity, fully disposed, with
-- a realised gain) a holdings report of this spec and journal leaves out of its
-- rows, for lack of -E/--empty. The totals' RGain and XIRR still include them.
holdingsClosedHidden :: HoldingsReportOpts -> ReportSpec -> Journal -> Int
holdingsClosedHidden hropts rspec j
| empty_ ropts = 0
| otherwise = length [() | (_, h) <- hrRows rpt, aquantity (hUnits h) == 0]
where
ropts = _rsReportOpts rspec
rpt = holdingsReport hropts{hroLots = False} rspec{_rsReportOpts = ropts{empty_ = True, sort_amount_ = False}} j
-- | A note saying how many closed positions are not shown, though the totals'
-- RGain and XIRR include them (see 'holdingsClosedHidden'), if there are any.
holdingsClosedNote :: I18n.Translations -> Int -> Maybe T.Text
holdingsClosedNote _ 0 = Nothing
holdingsClosedNote trs n = Just $
-- TRANSLATORS: a note below the holdings table; {n} is the number of closed (fully disposed) positions.
I18n.trn trs n "RGain and XIRR totals include {n} closed position, not shown" "RGain and XIRR totals include {n} closed positions, not shown"
-- | A report spec with these start and end dates in place of its query's dates
-- (Nothing for the end date keeps the query's end date).
holdingsSpecWithDates :: ReportSpec -> Maybe EFDay -> Maybe EFDay -> ReportSpec
holdingsSpecWithDates rspec mb me =
rspec{_rsQuery = And [ filterQuery (not . queryIsDateOrDate2) $ _rsQuery rspec
, Date $ DateSpan mb (me <|> (Exact <$> queryEndDate False (_rsQuery rspec)))]}
-- | Holdings reports at the end of each of the report spec's periods (it should have a report interval),
-- like the single-date report computed at each period's end. Their gain columns cover the time since acquisition
-- (Historical), each period (PerPeriod), or the time since the first period's start (Cumulative).
-- List/tree mode and lots don't matter here (only the reports' totals are meant to be shown),
-- so these are flat and without lots.
holdingsPeriodReports :: HoldingsReportOpts -> BalanceAccumulation -> ReportSpec -> Journal -> [(DateSpan, HoldingsReport)]
holdingsPeriodReports hropts accum rspec j =
[ (spn, holdingsReport hropts{hroLots = False} (rspecFor mb e) j)
| spn@(DateSpan mb (Just e)) <- periodspans ]
where
-- each period's report: as of its end, with gains since acquisition, or
-- during the period, or since the first period's start
rspecFor mb e = (holdingsSpecWithDates rspec mstart (Just e)){_rsReportOpts = (_rsReportOpts rspec){accountlistmode_ = ALFlat}}
where mstart = case accum of
Historical -> Nothing
PerPeriod -> mb
Cumulative -> mfirststart
mfirststart = case periodspans of
DateSpan mb _ : _ -> mb
[] -> Nothing
-- The periods: as usual (with no end date, ending with the journal's last
-- postings), but since values change with market prices, with no end date
-- they always extend to today, and the period containing today ends today,
-- like the single-date report. (Periods after it, from future-dated
-- postings, are kept.)
periodspans
| isJust (queryEndDate False $ _rsQuery rspec) = defspans
| reachestoday defspans = map clip defspans
| otherwise = map clip $ spansOf rspec{_rsQuery = And [_rsQuery rspec, Date $ DateSpan Nothing (Just $ Exact tomorrow)]}
where
spansOf = maybeDayPartitionToDateSpans . snd . reportSpanBothDates j
defspans = spansOf rspec
tomorrow = addDays 1 $ _rsDay rspec
reachestoday = any (\(DateSpan _ me) -> maybe False ((>= tomorrow) . fromEFDay) me)
clip spn@(DateSpan mb (Just e))
| fromEFDay e > tomorrow && maybe True ((< tomorrow) . fromEFDay) mb = DateSpan mb (Just $ Exact tomorrow)
| otherwise = spn
clip spn = spn
-- | The default title of some holdings reports at period ends (see 'holdingsPeriodReports'),
-- saying their interval, which dates they cover and what their gain columns cover.
holdingsPeriodsTitle :: I18n.Translations -> Interval -> BalanceAccumulation -> [(DateSpan, HoldingsReport)] -> T.Text
holdingsPeriodsTitle trs ivl accum rpts = case (map (hrDate . snd) rpts, accum) of
([], _) -> ivltitle
-- TRANSLATORS: the title of the holdings report with a report interval; {holdings} is eg "Monthly holdings", {dates} a date range like 2026-01-31..2026-06-30.
(ds, Historical) -> trf "{holdings}, {dates}" [("holdings", ivltitle), ("dates", showdates ds)]
-- TRANSLATORS: the title of the holdings report with a report interval and --change; {holdings} is eg "Monthly holdings", {dates} a date range like 2026-01-31..2026-06-30.
(ds, PerPeriod) -> trf "{holdings}, {dates}, gains in each period" [("holdings", ivltitle), ("dates", showdates ds)]
-- TRANSLATORS: the title of the holdings report with a report interval and --cumulative; {holdings} is eg "Monthly holdings", {dates} a date range like 2026-01-31..2026-06-30, {start} the report start date.
(ds, Cumulative) -> trf "{holdings}, {dates}, gains since {start}" [("holdings", ivltitle), ("dates", showdates ds), ("start", maybe "" (showDate . fromEFDay) mfirststart)]
where
trf = I18n.trf trs
ivltitle = I18n.tr trs $ holdingsIntervalTitle $ titleInterval ivl
showdates ds = showDate (minimum ds) <> ".." <> showDate (maximum ds)
mfirststart = case rpts of
(DateSpan mb _, _) : _ -> mb
[] -> Nothing
-- | The start of the holdings report's title with a report interval.
holdingsIntervalTitle :: Interval -> T.Text
holdingsIntervalTitle = \case
-- TRANSLATORS: the start of the holdings report's title, with its reporting interval. Each is a
-- whole phrase, so put the words in the order and form your language needs.
Days 1 -> I18n.i18n "Daily holdings"
Weeks 1 -> I18n.i18n "Weekly holdings"
Weeks 2 -> I18n.i18n "Biweekly holdings"
Months 1 -> I18n.i18n "Monthly holdings"
Months 2 -> I18n.i18n "Bimonthly holdings"
Months 3 -> I18n.i18n "Quarterly holdings"
Months 6 -> I18n.i18n "Half-yearly holdings"
Years 1 -> I18n.i18n "Yearly holdings"
Years 2 -> I18n.i18n "Biennial holdings"
_ -> I18n.i18n "Periodic holdings"
-- | Show the holdings report: the assets held in lot-tracked accounts
-- as of the report end date, one row per account (or per lot, with --lots).
--
-- This command receives the journal with lot detail (lot subaccounts and
-- synthetic postings) uncollapsed, regardless of --lots
-- (see maybePrepareLotDetail); holdingsReport aggregates lots itself.
holdings :: CliOpts -> Journal -> IO ()
holdings opts@CliOpts{rawopts_=rawopts, reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}} j = do
warnIfLargeMultiPeriodReport rspec j
if (case value_ ropts of Just (AtThen _) -> True; _ -> False)
then error' "holdings: --value=then is not supported"
else rounding `seq` -- validate the --round value before any output
if | chartRequested opts && periodic ->
writeChart opts (Just $ (<>"\n") $ htmlAsLazyText $ (titledTableHtml ptitle phtmltable <> htmlnote (("* " <>) <$> pnote))) $ holdingsReportsAsChart ropts paccum ptitle periodrpts
| chartRequested opts ->
writeChart opts (Just $ (<>"\n") $ htmlAsLazyText $ (titledTableHtml title htmltable <> foldMap (htmlnote . Just) notes)) $ holdingsReportAsChart ropts title rpt
| periodic -> writeOutputLazyText opts $ case outputFormatFromOpts opts of
"txt" -> ptxtoutput
"csv" -> printCSV pcsvoutput
"tsv" -> printTSV pcsvoutput
"html" -> (<>"\n") $ htmlAsLazyText $ (titledTableHtml ptitle phtmltable <> htmlnote (("* " <>) <$> pnote))
"fods" -> printFods IO.localeEncoding $ M.singleton (tr "Holdings") ((1,0), pfodstable)
"json" -> (<>"\n") $ toJsonText $ map (uncurry periodTotalsJson) ptotals
fmt -> error' $ unsupportedOutputFormatError fmt
| otherwise -> writeOutputLazyText opts $ case outputFormatFromOpts opts of
"txt" -> txtoutput
"csv" -> printCSV csvoutput
"tsv" -> printTSV csvoutput
"html" -> (<>"\n") $ htmlAsLazyText $ (titledTableHtml title htmltable <> foldMap (htmlnote . Just) notes)
"fods" -> printFods IO.localeEncoding $ M.singleton (tr "Holdings") ((1,0), fodstable)
"json" -> (<>"\n") $ toJsonText $ map holdingJson holdingrecords
fmt -> error' $ unsupportedOutputFormatError fmt
where
-- Amounts are displayed normalised to their commodity's display
-- precision by default; --round can choose another rounding strategy.
rounding = fromMaybe HardRounding $ roundFromRawOpts rawopts
tr = I18n.tr (translations_ ropts)
trf = I18n.trf (translations_ ropts)
rpt = holdingsReport hropts rptspec j
hropts = HoldingsReportOpts{hroLots = boolopt "lots" rawopts, hroRounding = rounding, hroPriceOracle = Just priceoracle}
rptspec = if maccum == Just Historical then holdingsSpecWithDates rspec Nothing Nothing else rspec
-- --change, --cumulative or --historical/-H, if specified: which period the
-- gain columns cover. In the single-date report, a start date gives the gains
-- during the report period (--change, or the same, --cumulative), unless
-- --historical asks for the gains since acquisition. With a report interval,
-- the default is --historical.
maccum = balanceAccumulationOverride rawopts
-- one price oracle for all the reports (eg one per period)
priceoracle = journalPriceOracle (infer_prices_ ropts) j
paccum = fromMaybe Historical maccum
rowlines = hrRows rpt
reportdate = hrDate rpt
-- With a report interval, the holdings at the end of each period (their totals, in a row per period).
periodic = interval_ ropts /= NoInterval
periodrpts = holdingsPeriodReports
HoldingsReportOpts{hroLots = False, hroRounding = rounding, hroPriceOracle = Just priceoracle} paccum rspec j
ptotals = [(hrDate r, (hrStyles r, hrTotals r)) | (_, r) <- periodrpts]
ptitle = effectiveTitle ropts $ holdingsPeriodsTitle (translations_ ropts) (interval_ ropts) paccum periodrpts
-- The Units, Avg cost and Unit price columns are shown only when some period has a single commodity
-- (they are blank otherwise); Weight is always 100%, and Date and Age don't apply.
showunits = any (isJust . htUnits . snd . snd) ptotals
pcolheadings = [h | (h, shown) <- zip allpcolheadings pcolshown, shown]
allpcolheadings = [tr "Units", tr "Avg cost", tr "Unit price", tr "Total cost", tr "Total value", tr "UGain", tr "UGain%", tr "RGain", tr "XIRR"]
pcolshown = replicate 3 showunits ++ replicate 6 True
-- a period's cells: those of the totals row's cells which make sense over time, and its unit price
periodcells c (styles, tot) = [ps | (ps, shown) <- zip (take 2 cells ++ [price] ++ drop 2 cells) pcolshown, shown]
where
cells = [ps | (i, ps) <- zip [0 :: Int ..] (totalsCellParts c styles tot), i `elem` [2, 3, 5, 6, 8, 9, 10, 11]]
price = maybe [] ((:[]) . showAmountB noCostFmt) (htPrice tot)
-- for the html and fods tables: whether each shown column is an amount, and its class
pcolinfo = [ci | (ci, shown) <- zip [(True,"units"),(True,"unitcost"),(True,"unitprice"),(True,"totalcost"),(True,"totalvalue"),(True,"ugain"),(False,"ugainpct"),(True,"rgain"),(False,"xirr")] pcolshown, shown]
ptxtoutput =
(case ptitle of
"" -> ""
t -> TL.fromStrict t <> "\n\n")
<>
if null ptotals
then TL.fromStrict (tr "(no holdings)") <> "\n"
else renderTable def{tableBorders=False} (textCell TopLeft) (textCell TopRight) (Cell TopRight . pure) (Table
(Group NoLine [Header $ pdate d st | (d, st) <- ptotals])
(Group NoLine $ map Header pcolheadings)
[map joinParts $ periodcells (color_ ropts) st | (_, st) <- ptotals])
<> txtnote (("* " <>) <$> pnote)
-- A period's date, starred if its totals leave out unpriced holdings,
-- which the note below the table names.
pdate d (_, tot) = showDate d <> if null (totalsLeftOut tot) then "" else "*"
pnote = holdingsUnpricedNote (translations_ ropts) $ nubSort $ concatMap (totalsLeftOut . snd . snd) ptotals
pcsvoutput :: CSV
pcsvoutput = ["date","units","avgcost","unitprice","totalcost","totalvalue","ugain","ugainpct","rgain","xirr","unpriced"] : map (uncurry periodTotalsCsv) ptotals
-- spreadsheet-shaped tables for the html and fods output, like the text table
pspreadsheetWith :: forall content. (T.Text -> content) -> (Bool -> [T.Text] -> content) -> [[Ods.Cell Ods.NumLines content]]
pspreadsheetWith plain parts =
addHeaderBorders [plain <$> (headerCell t){Ods.cellClass = Ods.Class cls} | (t, cls) <- zip (tr "Date" : pcolheadings) ("date" : map snd pcolinfo)]
: [ (Ods.defaultCell (plain $ pdate d st)){Ods.cellType = Ods.TypeString, Ods.cellClass = Ods.Class "date"}
: [ (Ods.defaultCell (parts isamount ps)){Ods.cellType = Ods.TypeMixedAmount, Ods.cellClass = Ods.Class cls}
| ((isamount, cls), ps) <- zip pcolinfo (textParts $ periodcells False st) ]
| (d, st) <- ptotals ]
phtmltable = pspreadsheetWith toHtml htmlParts
pfodstable = pspreadsheetWith id (\_ -> T.intercalate ", " . filter (not . T.null))
-- The default title can be customised or suppressed with --title.
-- TRANSLATORS: the holdings report's title; {date} is the report date, {period} the report period (eg 2026-11, or 2026-11-01..2026-11-14) if it has a start date.
title = effectiveTitle ropts $ case hrGainsPeriod rpt of
Nothing -> trf "Holdings on {date}" [("date", showDate reportdate)]
Just spn -> trf "Holdings on {date}, gains in {period}" [("date", showDate reportdate), ("period", showDateSpan spn)]
txtoutput =
(case title of
"" -> ""
t -> TL.fromStrict t <> "\n\n")
<>
if null rowlines
then TL.fromStrict (tr "(no holdings)") <> "\n"
else renderTable
def{tableBorders=False}
(textCell TopLeft)
(textCell TopRight)
(Cell TopRight . pure)
tbl
<> foldMap (txtnote . Just) notes
-- Notes about the totals, when there are totals (a totals row, or
-- tree mode's headings): that they leave out unpriced holdings, if
-- any, and that their RGain and XIRR include closed positions which
-- are not shown, if any.
notes
| no_total_ ropts && accountlistmode_ ropts /= ALTree = []
| otherwise = catMaybes
[ holdingsUnpricedNote (translations_ ropts) $ totalsLeftOut $ hrTotals rpt
-- TRANSLATORS: follows the holdings report's closed positions note, naming the flag that shows them.
, (<> " " <> tr "(see -E)") <$> holdingsClosedNote (translations_ ropts) (holdingsClosedHidden hropts rptspec j)
]
-- A note below a text table, after a blank line.
txtnote = maybe "" (\n -> "\n" <> TL.fromStrict n <> "\n")
-- A note below an html table.
htmlnote :: Maybe T.Text -> Html
htmlnote = maybe mempty (H.p . toHtml)
tbl = maybe id addtotalrow (map joinParts <$> mtotalrowparts (color_ ropts)) $ Table
(Group NoLine $ map (Header . lineacct) displaylines)
(Group NoLine $ map Header colheadings)
(map (map joinParts . linecells (color_ ropts)) displaylines)
where
addtotalrow totalrow tbl' = concatTables SingleLine tbl' $
Table (Group NoLine [Header ""]) (Header []) [totalrow]
-- TRANSLATORS: the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".
colheadings = [tr "Date", tr "Age", tr "Units", tr (hrUnitCostHeading rpt), tr "Unit price", tr "Total cost", tr "Total value", tr "Weight", tr "UGain", tr "UGain%", tr "RGain", tr "XIRR"]
displaylines = hrLines rpt
-- A display line's account cell: indented display names in tree
-- mode, full (possibly dropped) account names otherwise.
lineacct :: HoldingsLine -> T.Text
lineacct l
| accountlistmode_ ropts == ALTree && not (full_names_ ropts) =
T.replicate (hlIndent l * 2) " " <> hlDisplay l
| otherwise = accountNameDrop (drop_ ropts) (hlAccount l)
-- A display line's data cells, each as a list of parts,
-- with gains and losses coloured if the flag is true (see gainColour).
linecells :: Bool -> HoldingsLine -> [[WideBuilder]]
linecells c HoldingsHeading{hlTotals} = totalsCellParts c (hrStyles rpt) hlTotals
linecells c HoldingsPosition{hlHolding} = holdingCellParts c hlHolding
-- A text table cell from its parts, comma-separated.
joinParts :: [WideBuilder] -> WideBuilder
joinParts = mconcat . intersperse (wbFromText ", ")
-- Cells' parts as plain text, for the html and fods tables.
textParts :: [[WideBuilder]] -> [[T.Text]]
textParts = map (map wbToText)
-- Colour a gain (or the like, eg an XIRR) green if positive and a loss red, if the flag is true.
-- Colouring a WideBuilder keeps its width, so text tables stay aligned.
gainColour :: Bool -> Quantity -> WideBuilder -> WideBuilder
gainColour c q
| c && q > 0 = colorB Dull Green
| c && q < 0 = colorB Dull Red
| otherwise = id
showpct = showPercentWith (hrStyles rpt)
-- Show an XIRR percentage, like showpct: eg 12.3%.
showxirr :: Double -> T.Text
showxirr = showpct . realToFrac
-- A holding's cells, each as a list of parts: possibly several in Cost
-- and RGain (when cost commodities are mixed), at most one elsewhere.
-- Units show a commodity symbol even when zero (for rgain-only rows).
holdingCellParts :: Bool -> Holding -> [[WideBuilder]]
holdingCellParts c h =
[ [wbFromText $ maybe "" showDate (hDate h)]
, [wbFromText $ maybe "" showage (hAge h)]
, [showamtz (hUnits h)]
, [maybe mempty showamt (hUnitCost h)]
, map showamt $ hPrice h
, map showamtz $ hCost h
, map showamtz $ hValue h
, [wbFromText $ maybe "" showpct (hWeight h)]
, map (gainamt showamtz) $ hUgain h
, [maybe mempty (\p -> gainColour c p $ wbFromText $ showpct p) (hUgainPct h)]
, map (gainamt showamt) $ hRgain h
, [maybe mempty (\x -> gainColour c (realToFrac x) $ wbFromText $ showxirr x) (hXirr h)]
]
where
showamt = showAmountB noCostFmt
showamtz = showAmountB noCostFmt{displayZeroCommodity=True}
gainamt sh a = gainColour c (aquantity a) (sh a)
-- A totals row's cells (the grand total, or an account heading row
-- in tree mode), each as a list of parts like holdingCellParts.
totalsCellParts :: Bool -> M.Map CommoditySymbol AmountStyle -> HoldingsTotals -> [[WideBuilder]]
totalsCellParts c styles tot =
[ []
, []
, maybe [] ((:[]) . showamt) (htUnits tot)
, maybe [] ((:[]) . showamt) (htAvgCost tot)
, []
, map showamt (htCost tot)
, maybe [] (map showamt) (htValue tot)
, [wbFromText $ maybe "" pct (htWeight tot)]
, maybe [] (map (gainamt showamtz)) (htUgain tot)
, [maybe mempty (\p -> gainColour c p $ wbFromText $ pct p) (htUgainPct tot)]
, map (gainamt showamt) (htRgain tot)
, [maybe mempty (\x -> gainColour c (realToFrac x) $ wbFromText $ pct $ realToFrac x) (htXirr tot)]
]
where
pct = showPercentWith styles
showamt = showAmountB noCostFmt
showamtz = showAmountB noCostFmt{displayZeroCommodity=True}
gainamt sh a = gainColour c (aquantity a) (sh a)
-- The grand totals row as cell parts (coloured if the flag is true), unless --no-total is in effect.
mtotalrowparts :: Bool -> Maybe [[WideBuilder]]
mtotalrowparts c
| no_total_ ropts = Nothing
| otherwise = Just $ totalsCellParts c (hrStyles rpt) $ hrTotals rpt
-- Spreadsheet-shaped tables for the html and fods output: like the
-- text table, but with single-line cells, an Account column heading,
-- and a Total: row heading. Parameterised on how to convert plain
-- text, and a cell's list of (possibly amount) parts, to content.
spreadsheetWith :: forall content. (T.Text -> content) -> (Bool -> [T.Text] -> content)
-> [[Ods.Cell Ods.NumLines content]]
spreadsheetWith plain parts =
addHeaderBorders (zipWith hcell colclasses (tr "Account" : colheadings))
: [ zipWith3 bodycell [0..] (lineclasses l)
(plain (acctcell l) : zipWith parts amountcols (textParts $ linecells False l))
| l <- displaylines ]
++ maybe [] (\tot -> addTotalBorders
[zipWith3 totalcell [0..] colclasses
(plain (tr "Total:") : zipWith parts amountcols (textParts tot)) :: [Ods.Cell () content]])
(mtotalrowparts False)
where
-- per-column css classes, so the html cells can be styled
colclasses = ["account","date","age","units","unitcost","unitprice","totalcost","totalvalue","weight","ugain","ugainpct","rgain","xirr"]
-- which of the other columns' cell parts are amounts
amountcols = [False, False, True, True, True, True, True, False, True, False, True, False]
hcell cls t = plain <$> (headerCell t){Ods.cellClass = Ods.Class cls}
-- account heading rows get an extra class, so html can style them
lineclasses HoldingsHeading{} = "account acctheading" : drop 1 colclasses
lineclasses HoldingsPosition{} = colclasses
-- body cells are right-aligned, except the first two columns
-- (Account and Date); headings are unaffected
bodycell :: Ods.Lines border => Int -> T.Text -> content' -> Ods.Cell border content'
bodycell i cls t = (Ods.defaultCell t)
{Ods.cellType = if i < 2 then Ods.TypeString else Ods.TypeMixedAmount
,Ods.cellClass = Ods.Class cls}
totalcell i cls = bodycell i (cls <> " coltotal")
-- indent tree-mode account names with no-break spaces
acctcell l = T.replicate (hlIndent l * 2) "\160" <> hlDisplay l
-- Each commodity amount gets its own span with an "amount" class,
-- so eg wrapping within amounts can be prevented with css.
htmltable :: [[Ods.Cell Ods.NumLines Html]]
htmltable = spreadsheetWith toHtml htmlParts
htmlParts isamount parts =
mconcat $ intersperse (toHtml (", "::T.Text)) $
map (\p -> if isamount then (H.span ! A.class_ "amount") (toHtml p) else toHtml p) $
filter (not . T.null) parts
fodstable :: [[Ods.Cell Ods.NumLines T.Text]]
fodstable = spreadsheetWith id (\_ -> T.intercalate ", " . filter (not . T.null))
-- Machine-readable records for the csv/tsv/json output, one per
-- displayed table line. No totals records.
holdingrecords :: [Holding]
holdingrecords = map snd rowlines
csvoutput :: CSV
csvoutput =
["account","commodity","date","age","units","unitcost","unitprice","totalcost","totalvalue","weight","ugain","ugainpct","rgain","xirr"]
: map holdingCsv holdingrecords