hledger-2.0: embeddedfiles/hledger.1
.\"t
.TH "HLEDGER" "1" "December 2026" "hledger-2.0 " "hledger User Manuals"
.SH NAME
hledger \- a robust, friendly plain text accounting app (command line
version).
.SH SYNOPSIS
\f[CR]hledger\f[R]
.PD 0
.P
.PD
or
.PD 0
.P
.PD
\f[CR]hledger COMMAND [OPTS] [ARGS]\f[R]
.SH DESCRIPTION
hledger is a robust, user\-friendly, cross\-platform set of programs for
tracking money, time, or any other commodity, using double\-entry
accounting and a simple, editable file format.
hledger is inspired by and largely compatible with ledger(1), and
largely interconvertible with beancount(1).
.PP
This manual is for hledger\(aqs command line interface, version 2.0.
It also describes the common options, file formats and concepts used by
all hledger programs.
It might accidentally teach you some bookkeeping/accounting as well!
You don\(aqt need to know everything in here to use hledger
productively, but when you have a question about functionality, this doc
should answer it.
It is detailed, so do skip ahead or skim when needed.
You can read it on hledger.org, or as an info manual or man page on your
system.
You can also open a built\-in copy, at a point of interest, by running
.PD 0
.P
.PD
\f[CR]hledger help [TOPIC]\f[R].
.PP
The main function of the hledger CLI is to read plain text files
describing financial transactions, crunch the numbers, and print a
useful report or chart on the terminal (or save it as HTML, CSV, JSON,
SQL or SVG).
Many reports are available, as subcommands.
hledger will also detect other \f[CR]hledger\-*\f[R] executables as
extra subcommands.
.PP
hledger usually reads from (and appends to) a journal file specified by
the \f[CR]LEDGER_FILE\f[R] environment variable (defaulting to
\f[CR]$HOME/.hledger.journal\f[R]); or you can specify files with
\f[CR]\-f\f[R] options.
It can also read timeclock files, timedot files, or any CSV/SSV/TSV file
with a date field.
.PP
Here is a small journal file, describing some starting balances and two
transactions:
.IP
.EX
2025\-01\-01 * opening balances
assets:bank:checking $1000 = $1000
assets:cash $100 = $100
liabilities:creditcard $\-50 = $\-50
equity:opening/closing balances
2025\-01\-10 * gift received
income:gifts $\-20
assets:cash $20
2025\-01\-12 farmers market
assets:cash $\-13
expenses:food $13
.EE
.PP
Transactions are dated movements of money (etc.)
between two or more \f[I]accounts\f[R]: bank accounts, your wallet,
revenue/expense categories, people, etc.
You can choose any account names you wish, using \f[CR]:\f[R] to
indicate subaccounts.
There must be at least two spaces between account name and amount.
Positive amounts are inflow to that account (\f[I]debit\f[R]), negatives
are outflow from it (\f[I]credit\f[R]).
(Some reports show revenue, liability and equity account balances as
negative numbers as a result; this is normal.)
.PP
Some details from this example: the first entry records your real\-world
balances on a starting date, with the equity account absorbing the
difference (its amount is inferred); the \f[CR]= AMOUNT\f[R] parts are
optional balance assertions, for extra error checking; the \f[CR]*\f[R]
after a date is an optional status mark, meaning \(dqcleared\(dq; and
the currency symbols are optional, but a good habit.
.PP
hledger\(cqs add command can help you add transactions, or you can
install other data entry UIs like hledger\-web or hledger\-iadd.
For more extensive/efficient changes, use a text editor: Emacs +
ledger\-mode, VIM + vim\-ledger, or VS Code + hledger\-vscode are some
good choices (see https://hledger.org/editors.html).
.PP
To get started, run \f[CR]hledger add\f[R] and follow the prompts, or
save some entries like the above in \f[CR]$HOME/.hledger.journal\f[R],
then try commands like:
.IP
.EX
$ hledger print \-x
$ hledger aregister assets
$ hledger balance
$ hledger balancesheet
$ hledger incomestatement
$ hledger incomestatement \-M \-\-chart
.EE
.PP
Run \f[CR]hledger\f[R] to list the commands.
.PP
In this manual, we\(aqll cover all of hledger\(aqs functionality in
detail.
For a more gentle step by step introduction, see hledger by example, or
for a faster intro, the 5 minute quick start.
.PP
For tips on configuring a default journal file, reconciling with your
bank, closing a file at end of year, or migrating between hledger 1 and
2, see PART 6: COMMON TASKS.
.SH PART 1: USER INTERFACE
.SH Input
hledger reads one or more data files, each time you run it.
You can specify a file with \f[CR]\-f\f[R], like so
.IP
.EX
$ hledger \-f FILE [\-f FILE2 ...] print
.EE
.PP
Files are most often in hledger\(aqs journal format, with the
\f[CR].journal\f[R] file extension (\f[CR].hledger\f[R] or \f[CR].j\f[R]
also work); these files describe transactions, like an accounting
general journal.
.PP
When no file is specified, hledger looks for \f[CR].hledger.journal\f[R]
in your home directory.
.PP
But most people prefer to keep financial files in a dedicated folder,
perhaps with version control.
Also, starting a new journal file each year is common (it\(aqs not
required, but helps keep things fast and organised).
So we usually configure a different journal file, by setting the
\f[CR]LEDGER_FILE\f[R] environment variable, to something like
\f[CR]\(ti/finance/2023.journal\f[R].
For more about how to do that on your system, see Common tasks > Setting
LEDGER_FILE.
.SS Text encoding
hledger expects non\-ascii input to be decodable with the system
locale\(aqs text encoding.
(For CSV/SSV/TSV files, this can be overridden by the
\f[CR]encoding\f[R] CSV rule.)
.PP
So, trying to read non\-ascii files which have the wrong text encoding,
or when no system locale is configured, will fail.
To fix this, configure your system locale appropriately, and/or convert
the files to your system\(aqs text encoding (using \f[CR]iconv\f[R] on
unix, or powershell or notepad on Windows).
See Install: Text encoding for more tips.
.PP
hledger\(aqs output will use the system locale\(aqs encoding.
.PP
hledger\(aqs docs and example files mostly use UTF\-8 encoding.
.SS Data formats
Usually the data file is in hledger\(aqs journal format, but it can be
in any of the supported file formats, which currently are:
.PP
.TS
tab(@);
lw(13.5n) lw(33.0n) lw(23.5n).
T{
Reader:
T}@T{
Reads:
T}@T{
Automatically used for files with extensions:
T}
_
T{
\f[CR]journal\f[R]
T}@T{
hledger journal files and some Ledger journals, for transactions
T}@T{
\f[CR].journal\f[R] \f[CR].j\f[R] \f[CR].hledger\f[R] \f[CR].ledger\f[R]
T}
T{
\f[CR]timeclock\f[R]
T}@T{
timeclock files, for precise time logging
T}@T{
\f[CR].timeclock\f[R]
T}
T{
\f[CR]timedot\f[R]
T}@T{
timedot files, for approximate time logging
T}@T{
\f[CR].timedot\f[R]
T}
T{
\f[CR]csv\f[R]
T}@T{
Comma\- or other delimiter\-separated values, for data import
T}@T{
\f[CR].csv\f[R]
T}
T{
\f[CR]ssv\f[R]
T}@T{
Semicolon separated values
T}@T{
\f[CR].ssv\f[R]
T}
T{
\f[CR]tsv\f[R]
T}@T{
Tab separated values
T}@T{
\f[CR].tsv\f[R]
T}
T{
\f[CR]rules\f[R]
T}@T{
CSV/SSV/TSV/other separated values, alternate way
T}@T{
\f[CR].rules\f[R]
T}
.TE
.PP
These formats are described in more detail below.
.PP
hledger detects the format automatically based on the file extensions
shown above.
If it can\(aqt recognise the file extension, it assumes
\f[CR]journal\f[R] format.
So for non\-journal files, it\(aqs important to use a recognised file
extension, so as to either read successfully or to show relevant error
messages.
.PP
You can also force a specific reader/format by prefixing the file path
with the format and a colon.
Eg, to read a .dat file containing tab separated values:
.IP
.EX
$ hledger \-f tsv:/some/file.dat stats
.EE
.SS Standard input
The file name \f[CR]\-\f[R] means standard input:
.IP
.EX
$ cat FILE | hledger \-f\- print
.EE
.PP
If reading non\-journal data in this way, you\(aqll need to write the
format as a prefix, like \f[CR]timeclock:\f[R] here:
.IP
.EX
$ echo \(aqi 2009/13/1 08:00:00\(aq | hledger print \-f timeclock:\-
.EE
.SS Multiple files
You can specify multiple \f[CR]\-f\f[R] options, to read multiple files
as one big journal.
When doing this, note that certain features (described below) will be
affected:
.IP \(bu 2
Balance assertions will not see the effect of transactions in previous
files.
(Usually this doesn\(aqt matter as each file will set the corresponding
opening balances.)
.IP \(bu 2
Some directives will not affect previous or subsequent files.
.PP
If needed, you can work around these by using a single parent file which
includes the others (this works with CSV files too), or concatenating
the files into one, eg:
\f[CR]cat a.journal b.journal | hledger \-f\- CMD\f[R].
.SS Strict mode
hledger checks input files for valid data.
By default, the most important errors are detected, while still
accepting easy journal files without a lot of declarations:
.IP \(bu 2
Are the input files parseable, with valid syntax ?
.IP \(bu 2
Are all transactions balanced ?
.IP \(bu 2
Do all balance assertions pass ?
.PP
With the \f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R] flag, additional checks
are performed:
.IP \(bu 2
Are all accounts posted to, declared with an \f[CR]account\f[R]
directive ?
(Account error checking)
.IP \(bu 2
Are all commodities declared with a \f[CR]commodity\f[R] directive ?
(Commodity error checking)
.IP \(bu 2
Are all commodity conversions declared explicitly ?
.PP
You can use the check command to run individual checks \- the ones
listed above and some more.
.SH Commands
hledger provides various subcommands for getting things done.
Most of these commands do not change the journal file; they just read it
and output a report.
A few commands assist with adding data and file management.
Some commands to start with:
.IP \(bu 2
\f[CR]hledger add\f[R] \- add transactions, with interactive prompts
.IP \(bu 2
\f[CR]hledger print\f[R] \- show journal entries
.IP \(bu 2
\f[CR]hledger aregister assets:checking\f[R] (\f[CR]areg\f[R]) \- show
one account\(aqs transactions and running balance
.IP \(bu 2
\f[CR]hledger balancesheet\f[R] (\f[CR]bs\f[R]) \- show assets,
liabilities and net worth
.IP \(bu 2
\f[CR]hledger incomestatement\f[R] (\f[CR]is\f[R]) \- show revenues and
expenses
.PP
To show a summary of commands, run \f[CR]hledger\f[R] with no arguments.
See also PART 2: COMMANDS below.
.PP
To use a particular command, run
\f[CR]hledger CMD [CMDOPTS] [CMDARGS]\f[R],
.IP \(bu 2
CMD is the full command name, or its standard abbreviation shown in the
commands list, or any unambiguous prefix of the name.
.IP \(bu 2
CMDOPTS are command\-specific options, if any.
Command\-specific options must be written after the command name.
Eg: \f[CR]hledger print \-x\f[R].
.IP \(bu 2
CMDARGS are additional arguments to the command, if any.
Most hledger commands accept arguments representing a query, to limit
the data in some way.
Eg: \f[CR]hledger reg assets:checking\f[R].
.PP
To list a command\(aqs options, arguments, and documentation in the
terminal, run \f[CR]hledger CMD \-h\f[R].
Eg: \f[CR]hledger bal \-h\f[R].
.SS Add\-on commands
In addition to the built\-in commands, you can install \f[I]add\-on
commands\f[R], which will also appear in hledger\(aqs commands list.
Some of these can be installed as separate packages; others can be found
in hledger\(aqs bin/ directory, documented at
https://hledger.org/scripts.html.
.PP
Add\-on commands are programs or scripts in your shell\(aqs PATH, whose
name starts with \(dqhledger\-\(dq and ends with no extension or a
recognised extension (\(dq.bat\(dq, \(dq.com\(dq, \(dq.exe\(dq,
\(dq.hs\(dq, \(dq.js\(dq, \(dq.lhs\(dq, \(dq.lua\(dq, \(dq.php\(dq,
\(dq.pl\(dq, \(dq.py\(dq, \(dq.rb\(dq, \(dq.rkt\(dq, or \(dq.sh\(dq),
and (on unix and mac) which has executable permission for the current
user.
.PP
You can run add\-on commands directly: \f[CR]hledger\-ui \-\-watch\f[R].
.PP
Or you can run them with hledger, like built\-in commands:
\f[CR]hledger ui \-\-watch\f[R].
In this case hledger\(aqs config file will be used, so you can set
custom options for the addon there.
(Before hledger 1.50, an \f[CR]\-\-\f[R] argument was needed before
addon options, but not any more.)
.PP
Arguments written after the command name are passed on to the add\-on
unchanged, except for the options specific to the \f[CR]hledger\f[R] CLI
(\f[CR]\-\-conf\f[R], \f[CR]\-\-no\-conf\f[R], \f[CR]\-n\f[R]), which
hledger consumes.
To send one of those to the add\-on instead, write it after a
\f[CR]\-\-\f[R] argument: \f[CR]hledger ui \-\- \-n\f[R].
hledger consumes only that first \f[CR]\-\-\f[R]; later ones are passed
on like any other argument.
.SH Options
Run \f[CR]hledger \-h\f[R] to see general command line help.
Options can be written either before or after the command name.
These options are specific to the \f[CR]hledger\f[R] CLI:
.IP
.EX
Flags:
\-\-conf=CONFFILE Use extra options defined in this config file. If
not specified, searches upward and in XDG config
dir for hledger.conf (or .hledger.conf in $HOME).
\-n \-\-no\-conf ignore any config file
.EE
.PP
And the following general options are common to most hledger commands:
.IP
.EX
General input flags:
\-f \-\-file=[FMT:]FILE Use this as the journal file (\- means stdin). If
not specified, $LEDGER_FILE or \(ti/.hledger.journal
will be used. If specified more than once, the
files will be read in order. Each file\(aqs format
(journal, csv, timeclock, timedot, rules..) is
inferred from the file extension or a FMT: prefix.
Some commands (add, import) write to the (first)
file, and expect it to be in journal format.
\-\-rules=RULESFILE Use rules defined in this rules file for
converting subsequent CSV/SSV/TSV files. If not
specified, uses FILE.csv.rules for each FILE.csv.
\-\-alias=A=B|/RGX/=RPL transform account names from A to B, or by
replacing regular expression matches
\-\-auto generate extra postings by applying auto posting
rules (\(dq=\(dq) to all transactions
\-\-forecast[=PERIOD] Generate extra transactions from periodic rules
(\(dq\(ti\(dq), from after the latest ordinary transaction
until 6 months from now. Or, during the specified
PERIOD (the equals is required). Auto posting rules
will also be applied to these transactions. In
hledger\-ui, also make future\-dated transactions
visible at startup.
\-\-ignore\-assertions don\(aqt check balance assertions by default
\-\-ignore\-lots don\(aqt track lots: skip lot checks, inferred cost
bases and gain postings
\-I shortcut for \-\-ignore\-assertions \-\-ignore\-lots
\-\-txn\-tolerance=... how much imbalance to allow in transactions:
\(aqentry\(aq: \- the entry\(aqs precision (default)
\(aqdisplay\(aq: \- display precision (legacy)
\-\-infer\-costs infer costs from conversion equity postings
\-\-infer\-equity infer conversion equity postings from costs
\-\-infer\-imbalance add postings showing tolerated imbalances
\-\-infer\-market\-prices infer market prices from costs
\-\-pivot=TAGNAME use a different field or tag as account names
\-s \-\-strict do extra error checks (and override \-I)
General output flags (affecting some commands):
\-b \-\-begin=DATE include postings/transactions on/after this date
\-e \-\-end=DATE include postings/transactions before this date
(with a report interval, will be adjusted to
following subperiod end)
\-D \-\-daily set report interval: 1 day
\-W \-\-weekly set report interval: 1 week
\-M \-\-monthly set report interval: 1 month
\-Q \-\-quarterly set report interval: 1 quarter
\-Y \-\-yearly set report interval: 1 year
\-p \-\-period=PERIODEXP set begin date, end date, and/or report interval,
with more flexibility
\-\-today=DATE override today\(aqs date (affects relative dates)
\-\-date2 match/use secondary dates instead (deprecated)
\-U \-\-unmarked include only unmarked postings/transactions
\-P \-\-pending include only pending postings/transactions
\-C \-\-cleared include only cleared postings/transactions
(\-U/\-P/\-C can be combined)
\-R \-\-real include only non\-virtual postings
\-E \-\-empty Show zero items, which are normally hidden.
In hledger\-ui & hledger\-web, do the opposite.
\-\-depth=DEPTHEXP if a number (or \-NUM): show only top NUM levels
of accounts. If REGEXP=NUM, only apply limiting to
accounts matching the regular expression.
\-B \-\-cost convert amounts to their cost basis ({}), or else
their cost/sale amount (\(at/\(at\(at)
\-V \-\-market valuation mode: show amounts converted to market
value at period end(s) in their default valuation
commodity. Short for \-\-value=end.
\-X \-\-exchange=COMM valuation mode: show amounts converted to market
value at period end(s) in the specified commodity.
Short for \-\-value=end,COMM.
\-\-value=WHEN[,COMM] valuation mode: show amounts converted to market
value on the specified date(s) in their default
valuation commodity or a specified commodity. WHEN
can be:
\(aqthen\(aq: value on transaction dates
\(aqend\(aq: value at period end(s)
\(aqnow\(aq: value today
YYYY\-MM\-DD: value on given date
\(aqcost\(aq: cost basis, or else transacted cost
(same as \-B)
\(aqtransacted\(aq: transacted cost/sale amount (\(at/\(at\(at)
only
COMM may be written in double quotes; \(aq\(dq\(dq\(aq or an
empty COMM means the no\-symbol commodity.
\-\-lots show lot subaccounts and other lot details
\-c \-\-commodity\-style=S Override a commodity\(aqs display style.
Eg: \-c \(aq.\(aq or \-c \(aq1.000,00 EUR\(aq
\-\-pretty[=YN] Use box\-drawing characters in text output? The
optional \(aqy\(aq/\(aqyes\(aq or \(aqn\(aq/\(aqno\(aq arg requires =.
\-\-title=T set or customise a report title
\-\-subreport\-titles=TS customise subreport headings in compound reports
(|\-separated)
\-\-period\-titles=OPT customise headings in periodic reports:
\(aqcompact\(aq: readable period names when possible
\(aqdates\(aq: exact dates/date ranges always
General help flags:
\-? show the hledger quick reference
\-h \-\-help show this command\(aqs usage help
\-\-info show this command\(aqs manual with info
\-\-man show this command\(aqs manual with man
\-\-webman show this command\(aqs manual on the web
\-\-examples show examples for this command
\-\-version show version information
\-\-test[=PATTERN] run built\-in tests (those matching PATTERN) and
exit
\-\-write\-lang=LANG write LANG\(aqs PO file to the config directory, for
editing translations, and exit
\-\-debug=[1\-9] show this much debug output (default: 1)
\-\-pager=YN use a pager when needed ? y/yes (default) or n/no
\-\-color=YNA \-\-colour use ANSI color ? y/yes, n/no, or auto (default)
\-\-lang=LANG select the user interface language:
en (default), de, es, fr, ga, haw, it, ja, pt\-BR,
ru, uk, zh, or auto
.EE
.PP
Usually hledger accepts any unambiguous flag prefix, eg you can write
\f[CR]\-\-dry\f[R] instead of \f[CR]\-\-dry\-run\f[R].
.PP
You can combine short flags which don\(aqt take arguments, eg you can
write \f[CR]\-MAST\f[R] instead of \f[CR]\-M \-A \-S \-T\f[R].
Flags requiring an argument can\(aqt be combined in this way
(\f[CR]\-If FILE\f[R] won\(aqt work).
.PP
If the same option appears more than once in a command line, usually the
last (right\-most) wins.
Similarly, if mutually exclusive flags are used together, the
right\-most wins.
(When flags are mutually exclusive, they\(aqll usually have a group
prefix in \-\-help.)
.PP
With most commands, arguments are interpreted as a hledger query which
filters the data.
Some queries can be expressed either with options or with arguments.
.SS Config files
You can configure default command line options and arguments
conveniently in a hledger config file.
Config file options will be inserted near the start of your command
line, so you can override them with command line options.
.PP
You can specify a config file with the \f[CR]\-\-conf\f[R] option.
Otherwise, hledger will search for a default config file, in this order:
.IP \(bu 2
\f[CR]hledger.conf\f[R] in the current directory or above
.IP \(bu 2
\f[CR].hledger.conf\f[R] in your home directory
.IP \(bu 2
\f[CR]hledger.conf\f[R] in your XDG config
(\f[CR]\(ti/.config/hledger/hledger.conf\f[R]).
.PP
Only one config file is used.
Here\(aqs a small example:
.IP
.EX
\f[I]# General options, used with all hledger commands that support them.\f[R]
\-\-pretty
\f[I]# Command\-specific options.\f[R]
\f[B][print]\f[R]
\-\-explicit \-\-infer\-costs
.EE
.PP
And here is a commented starter config file:
https://github.com/hledgerorg/hledger/blob/main/hledger.conf.sample
.PP
You can put not only options, but also arguments in a config file.
.PP
You can ignore all config files by adding the
\f[CR]\-n\f[R]/\f[CR]\-\-no\-conf\f[R] flag to the command line.
This is recommended when using hledger in scripts.
When both \f[CR]\-\-conf\f[R] and \f[CR]\-\-no\-conf\f[R] options are
used, the right\-most wins.
.PP
Note, hledger 1 also reads config files, but some things written for
hledger 2 make it stop with an error: indented lines (including the
continuation lines of a multi\-line command alias), a \f[CR]#\f[R]
inside quotes, quotes around only part of an argument, and options in a
\f[CR][COMMAND]\f[R] section which that command doesn\(aqt have in
hledger 1.
(hledger 1 ignores single\-line command aliases, and unknown options in
the general section.)
In this situation, you can run hledger 1 with \f[CR]\-n\f[R], or give it
a separate config file with \f[CR]\-\-conf\f[R].
.SS Command aliases
In a config file you can also define command aliases: your own custom
commands, which expand to a longer command line (similar to git\(aqs
aliases).
(Since 1.99.4.)
Eg:
.IP
.EX
\f[B][alias]\f[R]
p = print
p1 = transactions
rev10 = balance type\f[B]:\f[R]R \-2 \-X\f[B]$\f[R] \-p \(aqevery 10 years from 2000\(aq
.EE
.PP
With this in your config file, you\(aqll see a \f[CR]rev10\f[R] command
in the \f[CR]hledger help commands\f[R] list, and
\f[CR]hledger rev10\f[R] will run the balance command above.
Options or arguments written at the command line will be added at the
end, usually overriding those in the alias; eg
\f[CR]hledger rev10 \-X €\f[R] will convert to \f[CR]€\f[R] instead of
\f[CR]$\f[R].
Command aliases can also be used in \f[CR]run\f[R] command scripts and
at the \f[CR]repl\f[R] prompt.
.PP
Each line in an \f[CR][alias]\f[R] section should look like
\f[CR]NAME = COMMAND [ARGS..]\f[R].
A command line can be continued on following lines by indenting them
more than the \f[CR]NAME\f[R]; the indented lines are joined to the
command line.
Blank lines and comment lines within it are ignored, so you can space it
out or comment out individual lines.
Eg:
.IP
.EX
\f[B][alias]\f[R]
rev10 = balance
type\f[B]:\f[R]R
\-2
\-X\f[B]$\f[R]
\-p \(aqevery 10 years from 2000\(aq
\f[I]# \-\-drop 1\f[R]
.EE
.PP
(hledger 1 can\(aqt read these continuation lines; see Config files.)
.PP
Command aliases override addon commands with the same name, but they
can\(aqt override builtin command names or abbreviations like
\f[CR]balance\f[R] or \f[CR]bal\f[R].
If the same alias name is defined more than once, the last definition
wins.
.PP
An alias\(aqs command can be a hledger builtin command, addon command,
or another alias.
If there\(aqs a \f[CR][COMMAND]\f[R] options section for an alias\(aqs
resolved builtin command, that will also be applied.
.PP
Or if an alias\(aqs command line begins with \f[CR]!\f[R], the rest is
run as a shell command (with any extra command line arguments appended).
Eg:
.IP
.EX
\f[B][alias]\f[R]
git\-commit = \f[B]!\f[R] git commit \-p
jj\-commit = \f[B]!\f[R] jj commit \-i
.EE
.PP
For safety, shell command aliases run only if defined in a trusted
config file: one you gave explicitly with \f[CR]\-\-conf\f[R], or your
user config file (\f[CR]\(ti/.hledger.conf\f[R] or the XDG
\f[CR]hledger.conf\f[R]).
Shell commands in a nearby automatically\-found \f[CR]hledger.conf\f[R],
in the current directory or a parent directory, will not run \- this
prevents a config file from an untrusted downloaded or shared directory
from running arbitrary shell commands.
.SS Config file troubleshooting
A default config file (one which hledger finds and uses automatically,
without a \f[CR]\-\-conf\f[R] option) is convenient, but it can surprise
you, eg by quietly changing report output, or breaking scripts which use
hledger.
Some tips:
.IP "1." 3
Be mindful about what you put in your config file; consider the effect
on all your reports.
.IP "2." 3
If a hledger command isn\(aqt doing what you expect, try it again with
\f[CR]\-n\f[R], to see if a config file is to blame.
.IP "3." 3
Run \f[CR]hledger setup\f[R] to list the currently active config file.
(\f[CR]setup\f[R] is not affected by config files.)
.IP "4." 3
Add \f[CR]\-\-debug\f[R] or \f[CR]\-\-debug=8\f[R] to any command to see
config/command line debug output.
.IP "5." 3
In scripts, and in examples you share with others, add \f[CR]\-n\f[R] so
that a config file can\(aqt change the result.
.IP "6." 3
When you download hledger data from elsewhere, watch out for directories
containing a \f[CR]hledger.conf\f[R] file.
.IP "7." 3
If hledger reports an error in a config file which should be fine, you
might be running an older hledger version.
(Since 1.99.6, config file errors show the hledger version; with older
versions, check which hledger executables are in your PATH.)
.IP "8." 3
A config file with errors doesn\(aqt stop help flags like
\f[CR]\-\-help\f[R] or \f[CR]\-\-version\f[R] from working, unless
they\(aqre used with a command alias defined in that file, in which case
the error is reported.
.SH Environment
These environment variables affect hledger:
.PP
\f[B]HLEDGER_FASTPATH\f[R] hledger parses simple journal entries with a
special fast\-path parser, when possible.
Setting this to \f[CR]off\f[R] disables the fast path, so that all
entries are parsed by the general parser, which could be useful to rule
out a parser bug.
Setting it to \f[CR]check\f[R] parses each entry with both parsers, and
reports an error if they disagree.
(\f[CR]\-\-debug=1\f[R] shows how much of a journal was parsed by the
fast path.)
.PP
\f[B]HLEDGER_LESS\f[R] If \f[CR]less\f[R] is your pager, this variable
specifies the \f[CR]less\f[R] options hledger should use.
(Otherwise, \f[CR]LESS\f[R] + custom options are used.)
.PP
\f[B]LEDGER_FILE\f[R] The default journal file, to be used when no
\f[CR]\-f/\-\-file\f[R] option is provided.
For example, it could be \f[CR]\(ti/finance/main.journal\f[R].
This can also be a glob pattern, eg \f[CR]./2???.journal\f[R].
(If the glob matches multiple files, only the alphanumerically first one
is used.)
If LEDGER_FILE points to a non\-existent file, an error will be raised.
If the value is the empty string, it is ignored.
.PP
If LEDGER_FILE is not set and \f[CR]\-f\f[R] is not provided, the
default journal file is \f[CR]$HOME/.hledger.journal\f[R] (or if a home
directory can\(aqt be detected, \f[CR]./.hledger.journal\f[R]).
.PP
See also Common tasks > Setting LEDGER_FILE.
.PP
\f[B]NO_COLOR\f[R] If this environment variable exists (with any value,
including empty), hledger will not use ANSI color codes in terminal
output, unless overridden by an explicit \f[CR]\-\-color=y\f[R] or
\f[CR]\-\-colour=y\f[R] option.
.PP
\f[B]LANGUAGE\f[R], \f[B]LC_ALL\f[R], \f[B]LC_MESSAGES\f[R],
\f[B]LANG\f[R] When the \f[CR]\-\-lang=auto\f[R] option is used, these
select the language of report titles and headings, following the usual
gettext rules: the effective locale is \f[CR]LC_ALL\f[R], else
\f[CR]LC_MESSAGES\f[R], else \f[CR]LANG\f[R]; if that is \f[CR]C\f[R],
\f[CR]POSIX\f[R] or unset, English is used; otherwise the languages
listed in \f[CR]LANGUAGE\f[R] (colon\-separated) are tried first, then
the effective locale.
See Languages.
.SH PART 2: COMMANDS
.PP
Here are hledger\(aqs standard commands.
You can list these by running \f[CR]hledger help commands\f[R], or as a
more compact list by running \f[CR]hledger\f[R].
If you have installed more add\-on commands, they also will be listed.
.PP
In the following command docs, each command\(aqs specific options are
shown.
Most commands also support the general options described above, though
some of them might have no effect.
(Usually if there\(aqs a sensible way for a general option to affect a
command, it will.)
You can list all of a command\(aqs options by running
\f[CR]hledger CMD \-h\f[R].
.PP
\f[B]User interface commands\f[R]
.IP \(bu 2
help (h) \- show documentation and examples
.IP \(bu 2
repl \- run multiple commands from an interactive prompt
.IP \(bu 2
run \- run multiple commands from a file or command line
.IP \(bu 2
ui \- (if installed) run a terminal UI
.IP \(bu 2
web \- (if installed) run a web UI
.PP
\f[B]Data entry commands\f[R]
.IP \(bu 2
add \- add transactions using terminal prompts
.IP \(bu 2
get \- fetch transaction and price data for import
.IP \(bu 2
import \- add new transactions from other files, eg CSV files
.PP
\f[B]Report commands\f[R]
.IP \(bu 2
accounts (acc) \- account names
.IP \(bu 2
activity \- transaction or posting counts, as a bar chart
.IP \(bu 2
aregister (areg) \- an account\(aqs transactions & running balance
.IP \(bu 2
balance (bal) \- balance changes, end balances, gains, budgets & more
.IP \(bu 2
balancesheet (bs) \- assets, liabilities and net worth
.IP \(bu 2
balancesheetequity (bse) \- assets, liabilities and equity
.IP \(bu 2
cashflow (cf) \- changes in liquid assets
.IP \(bu 2
codes \- transaction codes
.IP \(bu 2
commodities (comm) \- commodity/currency symbols
.IP \(bu 2
descriptions (desc) \- transaction descriptions
.IP \(bu 2
files \- input files used
.IP \(bu 2
holdings \- investment holdings and performance
.IP \(bu 2
incomestatement (is) \- revenues and expenses
.IP \(bu 2
notes \- the note part of transaction descriptions
.IP \(bu 2
payees \- the payee part of transaction descriptions
.IP \(bu 2
prices \- market prices
.IP \(bu 2
print \- transaction entries, or a whole exported journal
.IP \(bu 2
register (reg) \- matched postings & running total, across accounts
.IP \(bu 2
roi \- return on investments
.IP \(bu 2
stats \- journal statistics
.IP \(bu 2
tags \- tag names
.IP \(bu 2
transactions (tx) \- transactions, in compact one\-line format
.PP
\f[B]Maintenance commands\f[R]
.IP \(bu 2
setup \- check your hledger installation
.IP \(bu 2
init \- create starter journal files
.IP \(bu 2
check \- check that your journal is valid
.IP \(bu 2
diff \- compare an account\(aqs transactions in two journals
.PP
\f[B]Data generation commands\f[R]
.IP \(bu 2
close \- generate transactions to zero/restore/assert balances
.IP \(bu 2
rewrite \- generate postings by rule, like print \-\-auto
.PP
Next, these commands are described in detail.
.PP
.SH User interface commands
.SS help
.PP
Show some part of hledger\(aqs documentation.
.IP
.EX
Flags:
\-i use info when showing the manual
\-m use man when showing the manual
\-p use less (or $PAGER) when showing the manual
\-w use a web browser when showing the manual
\-l just list the manual topics matching TOPIC
\-\-builtins with commands: show only builtin commands
\-\-addons with commands: show only addon commands
\-\-aliases with commands: show only command aliases
.EE
.PP
The part shown is selected by arguments:
.IP \(bu 2
\f[CR]quickref\f[R] (or no args): a quick reference / overview
.IP \(bu 2
\f[CR]commands\f[R]: all commands, including addons and aliases (or just
one category, with \-\-builtins/\-\-addons/\-\-aliases)
.IP \(bu 2
\f[CR]usage [CMD]\f[R]: command line options help (like \-h/\-\-help)
.IP \(bu 2
\f[CR]examples [CMD]\f[R]: command line examples
.IP \(bu 2
\f[CR]manual [TOPIC]\f[R]: view a topic in the manual, or list them all
.IP \(bu 2
\f[CR]TOPIC\f[R]: (like \f[CR]manual TOPIC\f[R])
.IP \(bu 2
\f[CR]home|install|relnotes|docs|support|sponsor\f[R]: browse
hledger.org pages
.PP
TOPIC is a section heading in the hledger, hledger\-ui or hledger\-web
manual, or part of one, matched case insensitively.
Enclose it in quotes if it contains spaces.
With no TOPIC (\f[CR]hledger help manual\f[R]), all manual topics are
listed, indented to show (most of) their hierarchy.
.PP
The manual will be shown in a default viewer (info, man, pager, web
browser), or you can choose with \-i/\-m/\-p/\-w.
.PP
The manual is built in to your hledger executable, so it can be useful
when offline, or when you prefer the terminal to a web browser, or when
the appropriate hledger manual or viewers are not installed properly on
your system.
.PP
By default it chooses the best viewer found in $PATH, trying in this
order: \f[CR]info\f[R], \f[CR]man\f[R], \f[CR]$PAGER\f[R],
\f[CR]less\f[R], \f[CR]more\f[R], stdout.
(If a TOPIC is specified, \f[CR]$PAGER\f[R] and \f[CR]more\f[R] are not
tried.)
You can force the use of info, man, or a pager with the \f[CR]\-i\f[R],
\f[CR]\-m\f[R], or \f[CR]\-p\f[R] flags.
If no viewer can be found, or if running non\-interactively, it just
prints the manual to stdout.
.PP
Examples:
.IP
.EX
$ hledger help # show the quick reference
$ hledger help \-h # show the help command\(aqs options
$ hledger help commands # list all commands
$ hledger help commands \-\-aliases # list just the command aliases
$ hledger help \(aqtime periods\(aq # show the \(dqTime periods\(dq section in the manual
$ hledger help keys # show the \(dqKEYS\(dq section in the hledger\-ui manual
$ hledger help \-l # list the manual\(aqs topics
$ hledger help \-l journal # list the manual topics matching \(dqjournal\(dq
$ hledger help examples add # show examples for the add command
.EE
.SS repl
Start an interactive prompt for running hledger commands.
Input files are reloaded only when they change, so commands run faster.
.IP
.EX
Flags:
\-\-no\-watch disable automatic reloading of changed input
files, config aliases and addon commands
.EE
.PP
\f[CR]hledger repl\f[R] starts a read\-eval\-print loop (REPL) where you
can enter commands interactively.
As with the \f[CR]run\f[R] command, each input file (or each input
file/input options combination) is parsed just once, so commands will
run more quickly than if you ran them individually at the command line.
.PP
The input file(s) specified for the \f[CR]repl\f[R] command will be used
throughout the session; but you can override this temporarily by
specifying new \f[CR]\-f\f[R] options for a command.
.PP
Before running a command, any input files which have changed on disk are
automatically reloaded (including CSV rules files).
Also command aliases are reloaded if the config file has changed, and
addon commands are re\-detected if PATH\(aqs contents have changed.
The \f[CR]\-\-no\-watch\f[R] flag disables all of this reloading, so as
to work with a stable snapshot of the data, or to avoid file/directory
polling on a slow network drive.
.PP
Any other general flags given to \f[CR]repl\f[R] \- input, reporting, or
display flags such as \f[CR]\-I\f[R], \f[CR]\-\-strict\f[R],
\f[CR]\-\-alias\f[R], \f[CR]\-b\f[R]/\f[CR]\-e\f[R],
\f[CR]\-\-depth\f[R], \f[CR]\-\-cost\f[R], \f[CR]\-\-value\f[R],
\f[CR]\-\-color\f[R] \- are also applied to every command you run.
A command can still override them by specifying its own flags.
.PP
The command syntax is the same as with \f[CR]run\f[R]:
.IP \(bu 2
enter one hledger command at a time, without the usual
\f[CR]hledger\f[R] first word
.IP \(bu 2
empty lines and comment text from \f[CR]#\f[R] to end of line are
ignored
.IP \(bu 2
enclose arguments in quotes if they contain spaces.
.PP
Use \f[CR]help\f[R] (or \f[CR]h\f[R]) to show the quick reference, or
\f[CR]help commands\f[R] to list commands.
Addons in PATH and command aliases defined in a config file can also be
used.
Generally \f[CR]repl\f[R] should feel much like using hledger at the
command line.
But \f[CR]repl\f[R] requires full command names or official
abbreviations (it does not recognise ad hoc abbreviations).
.PP
To run a single shell command, type \f[CR]! SHELLCMD\f[R] (eg
\f[CR]! ls\f[R] or \f[CR]! git status\f[R]).
.PP
While it is running, the REPL remembers your command history, and you
can navigate in the usual ways:
.IP \(bu 2
Keypad or Emacs navigation keys to edit the current command line
.IP \(bu 2
UP/DOWN or control\-P/control\-N to step back/forward through history
.IP \(bu 2
control\-R to search for a past command
.IP \(bu 2
TAB to complete file paths.
.PP
You can type control\-C to cancel a long\-running command (but only
once; typing it a second time will exit the REPL).
.PP
In most shells you can type control\-Z to temporarily exit to the shell
(and then \f[CR]fg\f[R] to return to the REPL).
.PP
To exit the REPL, use control\-D or \f[CR]q\f[R] or \f[CR]quit\f[R] or
\f[CR]exit\f[R].
.SS Examples
Start the REPL and enter some commands:
.IP
.EX
$ hledger repl
hledger 1.52
Enter hledger commands. To exit, enter \(aqquit\(aq or \(aqexit\(aq, or send EOF / control\-d.
2025> stats
Main file : .../2025.journal
\&...
2025> stats \-f 2024/2024.journal
Main file : .../2024.journal
\&...
2025> stats
Main file : .../2025.journal
\&...
.EE
.PP
or:
.IP
.EX
$ hledger repl \-f some.journal
hledger 1.52
Enter hledger commands. To exit, enter \(aqquit\(aq or \(aqexit\(aq, or send EOF / control\-d.
some> bs
\&...
some> print \-b \(aqlast week\(aq
\&...
some> bs \-f other.journal
\&...
.EE
.SS run
Run a sequence of hledger commands, provided as files or command line
arguments.
Input files are parsed just once, so the commands run faster.
.IP
.EX
Flags:
\-O \-\-output\-format=FMT select the output format. Supported formats:
html.
\-o \-\-output\-file=FILE write output to FILE. A file extension matching
one of the above formats selects that format.
\-\-view write output to FILE, or to view.FMT in hledger\(aqs
cache directory, and open it in the system\(aqs
default viewer for its format (eg a web browser for
html). The default format is html.
.EE
.PP
You can use \f[CR]run\f[R] in three ways:
.IP \(bu 2
\f[CR]hledger run \-\- CMD1 \-\- CMD2 \-\- CMD3\f[R] \- read commands
from the command line, separated by \f[CR]\-\-\f[R]
.IP \(bu 2
\f[CR]hledger run SCRIPTFILE1 SCRIPTFILE2\f[R] \- read commands from one
or more files
.IP \(bu 2
\f[CR]cat SCRIPTFILE1 | hledger run\f[R] \- read commands from standard
input.
.PP
\f[CR]run\f[R] first loads the input file(s) specified by
\f[CR]LEDGER_FILE\f[R] or by \f[CR]\-f\f[R] options, in the usual way.
Then it runs each command in turn, each using the same input data.
But if you want a particular command to use different input, you can
specify an \f[CR]\-f\f[R] option within that command.
This will override (not add to) the default input, just for that
command.
.PP
Any other general flags given to \f[CR]run\f[R] \- input, reporting, or
display flags such as \f[CR]\-I\f[R], \f[CR]\-\-strict\f[R],
\f[CR]\-\-alias\f[R], \f[CR]\-b\f[R]/\f[CR]\-e\f[R],
\f[CR]\-\-depth\f[R], \f[CR]\-\-cost\f[R], \f[CR]\-\-value\f[R],
\f[CR]\-\-color\f[R] \- are also applied to every command it runs.
A command can still override them by specifying its own flags.
.PP
Each input file (more precisely, each combination of input file and
input options) is parsed only once.
This means that commands will not see any changes made to these files,
until the next run.
But the commands will run more quickly than if run individually
(typically about twice as fast).
.PP
Command scripts, whether in a file or written on the command line, have
a simple syntax:
.IP \(bu 2
each line may contain a single hledger command and its arguments,
without the usual \f[CR]hledger\f[R] first word
.IP \(bu 2
empty lines are ignored
.IP \(bu 2
text from \f[CR]#\f[R] to end of line is a comment, and ignored
.IP \(bu 2
you can use single or double quotes to quote arguments when needed, as
on the command line
.IP \(bu 2
these extra commands are available: \f[CR]echo TEXT\f[R] prints some
text (interpreting the backslash escapes \f[CR]\(rsn\f[R],
\f[CR]\(rst\f[R], \f[CR]\(rsr\f[R], \f[CR]\(rs\(rs\f[R]), and
\f[CR]exit\f[R] or \f[CR]quit\f[R] ends the run.
.PP
On unix systems you can use \f[CR]#!/usr/bin/env hledger run\f[R] in the
first line of a command file to make it a runnable script.
If that gives an error, use \f[CR]#!/usr/bin/env \-S hledger run\f[R].
.PP
It\(aqs ok to use the \f[CR]run\f[R] command recursively within a
command script.
.PP
With \f[CR]\-O html\f[R], \f[CR]\-o FILE.html\f[R] or
\f[CR]\-\-view\f[R], \f[CR]run\f[R] collects the commands\(aq outputs
into one HTML page instead of printing them: a section for each command,
headed by its command line, which can be folded; and a heading for each
\f[CR]echo\f[R].
Commands which can produce HTML (the balance commands,
\f[CR]register\f[R], \f[CR]aregister\f[R], \f[CR]print\f[R],
\f[CR]holdings\f[R], \f[CR]activity\f[R]) do so, charts included;
others\(aq text output is shown as is.
\f[CR]\-\-view\f[R] then opens the page in your web browser (see Output
destination), which is a convenient way to see several reports, or
charts, at once:
.IP
.EX
$ hledger run \-\-view \-\- echo Overview \-\- is \-M \-\-chart \-\- bs \-Q \-\-chart \-\- reg expenses \-p thismonth
.EE
.PP
Command aliases defined in a config file can also be used in command
scripts.
.PP
You may find some differences in behaviour between \f[CR]run\f[R]
command lines and normal hledger command lines.
\f[CR]run\f[R] is a little stricter; eg it requires full command names
or official abbreviations (as seen in the commands list), and command
options must be written after the command name.
.SS Examples
Run commands from the command line:
.IP
.EX
hledger \-f some.journal run \-\- balance assets \-\-depth 2 \-\- balance liabilities \-f /some/other.journal \-\-depth 3 \-\-transpose \-\- stats
.EE
.PP
This would load \f[CR]some.journal\f[R], run
\f[CR]balance assets \-\-depth 2\f[R] on it, then run
\f[CR]balance liabilities \-\-depth 3 \-\-transpose\f[R] on
\f[CR]/some/other.journal\f[R], and finally run \f[CR]stats\f[R] on
\f[CR]some.journal\f[R]
.PP
Run commands from standard input:
.IP
.EX
(echo \(dqfiles\(dq; echo \(dqstats\(dq) | hledger \-f some.journal run
.EE
.PP
Run commands as a script:
.IP
.EX
$ cat report
#!/usr/bin/env \-S hledger run \-f some.journal
echo \(dqList of accounts in some.journal\(dq
accounts
echo \(dqAssets of some.journal\(dq
balance assets \-\-depth 2
echo \(dqLiabilities from /some/other.journal\(dq
balance liabilities \-f /some/other.journal \-\-depth 3 \-\-transpose
echo \(dqCommands from another.script, applied to another.journal\(dq
run \-f another.journal another.script
.EE
.IP
.EX
$ chmod +x report
$ ./report
List of accounts in some.journal
\&...
.EE
.SS ui
Runs hledger\-ui, a terminal UI (if installed).
.SS web
Runs hledger\-web, a web UI (if installed).
.SH Data entry commands
.SS add
Add new transactions to a journal file, with interactive prompting.
.IP
.EX
Flags:
\-\-no\-new\-accounts don\(aqt allow creating new accounts
\-\-layout=hledger1|COL how should posting amounts be aligned ?
hledger1 \- right\-align amounts, as in hledger 1
COL \- align decimal marks at column COL
(default: 53)
.EE
.PP
Many hledger users edit their journals directly with a text editor, or
generate them from CSV.
For more interactive data entry, there is the \f[CR]add\f[R] command,
which prompts interactively on the console for new transactions, and
appends them to the main journal file (which should be in journal
format).
Existing transactions are not changed.
This is one of the few hledger commands that writes to the journal file
(see also \f[CR]import\f[R]).
.PP
To use it, just run \f[CR]hledger add\f[R] and follow the prompts.
You can add as many transactions as you like; when you are finished,
enter \f[CR].\f[R] or press control\-d or control\-c to exit.
.PP
Features:
.IP \(bu 2
add tries to provide useful defaults, using the most similar (by
description) and nearest\-dated transaction (filtered by the query, if
any) as a template.
.IP \(bu 2
You can also set the initial defaults with command line arguments.
.IP \(bu 2
Readline\-style edit keys can be used during data entry.
.IP \(bu 2
The tab key will auto\-complete whenever possible \- accounts,
payees/descriptions, dates (\f[CR]yesterday\f[R], \f[CR]today\f[R],
\f[CR]tomorrow\f[R]).
If the input area is empty, it will insert the default value.
.IP \(bu 2
A parenthesised transaction code may be entered following a date.
.IP \(bu 2
Comments and tags may be entered following a description or amount.
.IP \(bu 2
If you make a mistake, enter \f[CR]<\f[R] at any prompt to go one step
backward.
.IP \(bu 2
Before saving a transaction, add checks that the journal will still be
readable with it added, as the next read with the same options will
check it (eg balance assertions must pass, lots must be valid, and with
\f[CR]\-\-strict\f[R], the strict checks must pass).
If not, it shows the error and goes one step backward, so you can
correct the entry.
(With a large journal this check may take a moment; it runs while you
are deciding whether to save.)
.IP \(bu 2
Input prompts are displayed in a different colour when the terminal
supports it.
.PP
Notes:
.IP \(bu 2
If you enter a number with no commodity symbol, and you have declared a
default commodity with a \f[CR]D\f[R] directive, you might expect
\f[CR]add\f[R] to add this symbol for you.
It does not do this; we assume that if you are using a \f[CR]D\f[R]
directive you prefer not to see the commodity symbol repeated on amounts
in the journal.
.IP \(bu 2
\f[CR]add\f[R] creates entries in journal format; it won\(aqt work with
timeclock or timedot files.
.IP \(bu 2
There is a known issue on Windows if this hledger version is built from
stackage: the prompts will show ANSI junk instead of colours (#2410).
You can avoid this by using official hledger release binaries or by
building it with haskeline >=0.8.4; or by running \f[CR]add\f[R] with
\f[CR]\-\-color=no\f[R], perhaps configured in your config file.
.PP
Examples:
.IP \(bu 2
Record new transactions, saving to the default journal file:
.RS 2
.PP
\f[CR]hledger add\f[R]
.RE
.IP \(bu 2
Add transactions to 2024.journal, but also load 2023.journal for
completions:
.RS 2
.PP
\f[CR]hledger add \-\-file 2024.journal \-\-file 2023.journal\f[R]
.RE
.IP \(bu 2
Provide answers for the first four prompts:
.RS 2
.PP
\f[CR]hledger add today \(aqbest buy\(aq expenses:supplies \(aq$20\(aq\f[R]
.RE
.PP
There is a detailed tutorial at https://hledger.org/add.html.
.SS add and balance assertions
You can add a balance assertion by writing \f[CR]AMOUNT = BALANCE\f[R]
when asked for an amount.
Eg \f[CR]100 = 500\f[R].
.PP
Also, each time you enter a new amount, hledger re\-checks all balance
assertions in the journal and rejects the new amount if it would make
any of them fail.
You can run \f[CR]add\f[R] with \f[CR]\-I\f[R] or
\f[CR]\-\-ignore\-assertions\f[R] to disable balance assertion checking.
.SS add and balance assignments
\f[B]Adding a new balance assignment\f[R]
.PD 0
.P
.PD
When entering a posting amount, you can write a
\f[CR]= BALANCEAMOUNT\f[R] balance assignment (or \f[CR]==\f[R],
\f[CR]=*\f[R], \f[CR]==*\f[R]) instead.
The posting amount required to produce this balance will be calculated
automatically.
\f[I](Since 1.51)\f[R]
.PP
\f[B]Adding a posting dated before an existing balance assignment\f[R]
.PD 0
.P
.PD
\f[CR]add\f[R] won\(aqt let you add a posting dated earlier than an
existing balance assignment in that account.
(Because it calculates balance assignments only once at startup,
converting them to assertions, so adding the new amount causes an
assertion failure.)
To work around this, run \f[CR]add\f[R] with balance assertions ignored:
\f[CR]hledger add \-I\f[R].
.SS get
Fetch new transactions and market prices for the journal, by running
\f[CR]getdata\f[R] and \f[CR]getprices\f[R] helper scripts.
New prices are merged into prices files automatically; new transaction
data is just saved, for later conversion & import by \f[CR]import\f[R].
.IP
.EX
Flags:
\-\-transactions fetch transactions only
\-\-prices fetch prices only
\-\-dry\-run just print the commands that would be run
.EE
.PP
By default, this command fetches both transactions and prices.
.SS Phase 1: transactions data
.IP "1." 3
Creates a \f[CR]data/\f[R] directory next to the main journal file, if
it does not exist.
.IP "2." 3
If the \f[CR]data/getdata\f[R] helper script exists, runs it in the data
directory, so it can save downloaded files (CSV/TSV/JSON/OFX/etc.)
there.
.SS Phase 2: prices
.IP "1." 3
Creates a \f[CR]prices/\f[R] directory next to the main journal file, if
it does not exist.
.IP "2." 3
If the \f[CR]prices/getprices\f[R] helper script exists, hledger first
guesses the journal\(aqs base currency (the commodity most used as the
target in P price directives; or if there are no P directives, the
commodity most used in postings; or if there are no postings,
\(dqUSD\(dq).
Then for each other commodity in the journal, it fetches daily market
prices in the base currency, from that commodity\(aqs earliest
transaction until today, by running
\f[CR]getprices BASECUR COMM START END\f[R].
Each commodity\(aqs prices are merged into
\f[CR]prices/<COMM>.prices\f[R], preserving existing prices.
.PP
Commands being run, and files being updated, are logged to stderr.
With \f[CR]\-\-dry\-run\f[R], you can preview the commands without
running them.
.SS Merging new prices
Complete historical price data can be hard to get, so the prices phase
is careful to preserve older prices.
If prices files already exist, the newly fetched prices will be merged
as follows:
.IP \(bu 2
Prices files will be updated only if they contain nothing but P
directives (or blank lines).
.IP \(bu 2
New prices for dates already seen are discarded.
(So if you want to replace old prices, you must delete them before
running \f[CR]get\f[R].)
.IP \(bu 2
If no new prices remain to be added, the prices file is left as\-is.
.IP \(bu 2
Otherwise, the old prices plus the new prices are saved to the file,
ordered by: date, from commodity, to commodity.
Each price keeps the number format it was written with.
.SS get\(aqs helper scripts
Data downloading varies for everyone, and needs to be easily
customisable, so it is done via helper scripts:
.SS getdata
If you want \f[CR]get\f[R] to download transaction data for you, make
your own \f[CR]getdata\f[R] shell script (or executable program), and
install it in the \f[CR]data\f[R] directory next to your main journal
file.
.PP
It should download zero or more transaction data files into its current
directory.
Anything it prints (on stdout or stderr) is shown on stderr, as progress
output.
These are typically bank/brokerage CSV/TSV/SSV files, but could be
anything that your hledger rules files can read.
The hledger repo\(aqs getdata is a stub you can start from, with
commented examples.
.SS getprices
If you want \f[CR]get\f[R] to download historical market prices (useful
for currency conversions, and value or gains reports), install a
\f[CR]getprices\f[R] script in the \f[CR]prices\f[R] directory next to
your main journal file.
.PP
You can start with the hledger repo\(aqs getprices, customising it if
needed.
This script uses pricehist, so you will need to install that python tool
also (eg with \f[CR]uv tool install pricehist\f[R]).
Some price providers limit the commodity pairs, history, or number of
requests available for free; you can get better data by paying them and
setting up their API keys as environment variables.
.PP
Or, you can make your own \f[CR]getprices\f[R] script.
It should accept 3\-4 arguments:
.IP \(bu 2
ISO code for the base currency
.IP \(bu 2
ISO code for the commodity to be priced
.IP \(bu 2
ISO start date
.IP \(bu 2
optional ISO end date (default: today)
.SS import
Import new transactions from one or more data files to the main journal.
Or with no arguments, import from the rules files in \f[CR]rules/\f[R].
.IP
.EX
Flags:
\-g \-\-get fetch new data first by running the get command
\-\-catchup just mark all transactions as already imported
\-\-dry\-run just show the transactions to be imported
\-\-layout=hledger1|COL how should posting amounts be aligned ?
hledger1 \- right\-align amounts, as in hledger 1
COL \- align decimal marks at column COL
(default: 53)
.EE
.PP
This command detects new transactions in one or more data files
specified as arguments, and appends them to the main journal.
.PP
You can import from any input file format hledger supports, but
CSV/SSV/TSV files, downloaded from financial institutions, are the most
common import source.
.PP
The import destination is the default journal file, or another specified
in the usual way with \f[CR]$LEDGER_FILE\f[R] or
\f[CR]\-f/\-\-file\f[R].
It should be in journal format.
.PP
Before writing anything, \f[CR]import\f[R] checks that the journal will
still be readable with the new transactions added, as the next read with
the same options will check it (eg balance assertions must pass, lots
must be valid, and with \f[CR]\-\-strict\f[R], the strict checks must
pass).
If not, it shows the error and imports nothing (and updates no
\f[CR].latest\f[R] files).
A dry run does this check too.
.PP
Examples:
.IP
.EX
$ hledger import bank1\-checking.csv bank1\-savings.csv
.EE
.IP
.EX
$ hledger import *.csv
.EE
.SS Default import sources
If \f[CR]import\f[R] is run with no file arguments, it looks in the
journal\(aqs \f[CR]rules/\f[R] directory (next to the main journal file)
and imports from every \f[CR].rules\f[R] file found there, in
alphabetical order.
Files whose name begins with \f[CR].\f[R] or \f[CR]_\f[R] are skipped:
the \f[CR]_\f[R] prefix is for rules files that are either disabled, or
shared/common rules \f[CR]include\f[R]d by other rules files and not
meant to be read directly.
.PP
So a typical setup might be:
.IP
.EX
\(ti/finance/2026.journal
\(ti/finance/rules/bank1\-checking.rules
\(ti/finance/rules/bank1\-savings.rules
\(ti/finance/rules/_common.rules # included by others, not read directly
\(ti/finance/rules/_brokerage.rules # disabled
.EE
.PP
and \f[CR]hledger import\f[R] reads \f[CR]bank1\-checking.rules\f[R]
then \f[CR]bank1\-savings.rules\f[R].
.PP
If the \f[CR]rules/\f[R] directory does not exist or contains no usable
\f[CR].rules\f[R] files, import reports an error.
.SS Fetching new data first
With \f[CR]\-g/\-\-get\f[R], \f[CR]import\f[R] runs the \f[CR]get\f[R]
command first, which runs your \f[CR]data/getdata\f[R] and
\f[CR]prices/getprices\f[R] scripts (if any) to download new transaction
and price data.
The import then proceeds normally, with the new transaction data (if
any) readable by your rules files\(aq \f[CR]source\f[R] rules.
.SS Import dry run
It\(aqs useful to preview the import by running first with
\f[CR]\-\-dry\-run\f[R], to sanity check the range of dates being
imported, and to check the effect of your conversion rules if converting
from CSV.
Eg:
.IP
.EX
$ hledger import bank.csv \-\-dry\-run
.EE
.PP
A dry run archives no data files and updates no \f[CR].latest\f[R]
files.
With \f[CR]\-g\f[R], the \f[CR]get\f[R] command does a dry run too.
But \f[CR]source\f[R] rules\(aq data cleaning and data generating
commands do run, since their output is needed for the preview; so these
should be safe to repeat.
.PP
The dry run output is valid journal format, so hledger can re\-parse it.
If the output is large, you could show just the uncategorised
transactions like so:
.IP
.EX
$ hledger import \-\-dry\-run bank.csv | hledger \-f\- \-I print unknown
.EE
.PP
You could also run this repeatedly to see the effect of edits to your
conversion rules:
.IP
.EX
$ watchexec \-\- \(dqhledger import \-\-dry\-run bank.csv | hledger \-f\- \-I print unknown\(dq
.EE
.PP
Once the conversion and dates look good enough to import to your
journal, perhaps with some manual fixups to follow, you would do the
actual import:
.IP
.EX
$ hledger import bank.csv
.EE
.SS Overlap detection
Reading CSV files is built in to hledger, and not specific to
\f[CR]import\f[R]; so you could also import by doing
\f[CR]hledger \-f bank.csv print >>$LEDGER_FILE\f[R].
.PP
But \f[CR]import\f[R] is easier and provides some advantages.
The main one is that it avoids re\-importing transactions it has seen on
previous runs.
This means you don\(aqt have to worry about overlapping data in
successive downloads of your bank CSV; just download and
\f[CR]import\f[R] as often as you like, and only the new transactions
will be imported each time.
.PP
We don\(aqt call this \(dqdeduplication\(dq, as it\(aqs generally not
possible to reliably detect duplicates in bank CSV.
Instead, \f[CR]import\f[R] remembers the latest date processed
previously in each CSV file (saving it in a hidden file), and skips any
records prior to that date.
This works well for most real\-world CSV, where:
.IP "1." 3
the data file name is stable (does not change) across imports
.IP "2." 3
the item dates are stable across imports
.IP "3." 3
the order of same\-date items is stable across imports
.IP "4." 3
the newest items have the newest dates
.PP
(Occasional violations of 2\-4 are often harmless; you can reduce the
chance of disruption by downloading and importing more often.)
.PP
Overlap detection is automatic, and shouldn\(aqt require much attention
from you, except perhaps at first import (see below).
But here\(aqs how it works:
.IP \(bu 2
For each \f[CR]FILE\f[R] being imported from:
.RS 2
.IP "1." 3
hledger reads a file named \f[CR].latest.FILE\f[R] file in the same
directory, if any.
This file contains the latest record date previously imported from FILE,
in YYYY\-MM\-DD format.
If multiple records with that date were imported, the date is repeated
on N lines.
.IP "2." 3
hledger reads records from FILE.
If a latest date was found in step 1, any records before that date, and
the first N records on that date, are skipped.
.RE
.IP \(bu 2
After a successful import from all FILEs, without error and without
\f[CR]\-\-dry\-run\f[R], hledger updates each FILE\(aqs
\f[CR].latest.FILE\f[R] for next time.
.PP
If this goes wrong, it\(aqs relatively easy to repair:
.IP \(bu 2
You\(aqll notice it before import when you preview with
\f[CR]import \-\-dry\-run\f[R].
.IP \(bu 2
Or after import when you try to reconcile your hledger account balances
with your bank.
.IP \(bu 2
\f[CR]hledger print \-f FILE.csv\f[R] will show all recently downloaded
transactions.
Compare these with your journal.
Copy/paste if needed.
.IP \(bu 2
Update your conversion rules and print again, if needed.
.IP \(bu 2
You can manually update or remove the .latest file, or use
\f[CR]import \-\-catchup FILE\f[R].
.IP \(bu 2
Download and import more often, eg twice a week, at least while you are
learning.
It\(aqs easier to review and troubleshoot when there are fewer
transactions.
.SS First import
The first time you import from a file, when no corresponding .latest
file has been created yet, all of the records will be imported.
.PP
But perhaps you have been entering the data manually, so you know that
all of these transactions are already recorded in the journal.
In this case you can run \f[CR]hledger import \-\-catchup\f[R] once.
This will create a .latest file containing the latest CSV record date,
so that none of those records will be re\-imported.
.PP
Or, if you know that some but not all of the transactions are in the
journal, you can create the .latest file yourself.
Eg, let\(aqs say you previously recorded foobank transactions up to
2024\-10\-31 in the journal.
Then in the directory where you\(aqll be saving \f[CR]foobank.csv\f[R],
you would create a \f[CR].latest.foobank.csv\f[R] file containing
.IP
.EX
2024\-10\-31
.EE
.PP
Or if you had three foobank transactions recorded with that date, you
would repeat the date that many times:
.IP
.EX
2024\-10\-31
2024\-10\-31
2024\-10\-31
.EE
.PP
Then \f[CR]hledger import foobank.csv [\-\-dry\-run]\f[R] will import
only the newer records.
.SS Importing balance assignments
Journal entries added by import will have all posting amounts made
explicit (like \f[CR]print \-x\f[R]).
.PP
This means that any balance assignments in the imported entries would
need to be evaluated.
But this generally isn\(aqt possible, as the main file\(aqs account
balances are not visible during import.
So try to avoid generating balance assignments with your CSV rules, or
importing from a journal that contains balance assignments.
(Balance assignments are best avoided anyway.)
.PP
But if you must use them, eg because your CSV includes only balances:
you can import with \f[CR]print\f[R], which leaves implicit amounts
implicit.
(\f[CR]print\f[R] can also do overlap detection like import, with the
\f[CR]\-\-new\f[R] flag):
.IP
.EX
$ hledger print \-\-new \-f bank.csv >> $LEDGER_FILE
.EE
.PP
(If you think \f[CR]import\f[R] should preserve implicit balances,
please test that and send a pull request.)
.SS Import and commodity styles
Amounts in entries added by import will be formatted according to the
journal\(aqs canonical commodity styles, as declared by
\f[CR]commodity\f[R] directives or inferred from the journal\(aqs
amounts.
.PP
Related: CSV > Amount decimal places.
.SS Import archiving
When importing from a CSV rules file
(\f[CR]hledger import bank.rules\f[R]), you can use the archive rule to
enable automatic archiving of the data file.
.PP
After a successful import, the data file specified by \f[CR]source\f[R]
will be moved (or data generated by a command will be saved) to an
archive directory.
This can be useful for troubleshooting, detecting variations in your
banks\(aq CSV data, regenerating entries with improved rules, etc.
.PP
The archive directory is \f[CR]data/archive/\f[R], next to the main
journal file, auto\-created.
The archive file name will be similar to the rules file, with a date
added: the original data file\(aqs modification date, or today\(aqs date
if the data was command\-generated.
.PP
The \f[CR]archive\f[R] rule also causes \f[CR]import\f[R] to handle
\f[CR]source\f[R] glob patterns differently: when there are multiple
matched files, it will pick the oldest, not the newest.
.SS Import special cases
.SS Multiple journals in the same directory
You might want to keep each journal you are importing to in its own
directory.
That way, each will have its own \f[CR]rules/\f[R], \f[CR]data/\f[R],
and \f[CR]data/archive/\f[R] directories (if those are used).
.PP
Otherwise, imports to the same\-directory journals will potentially use
the same \f[CR]rules/\f[R], \f[CR]data/\f[R] and
\f[CR]data/archive/\f[R] directories (depending on commands and rules
configuration).
This is not necessarily a problem; it might even be desirable in some
cases.
But see below:
.SS Import configurations to avoid
A few unusual workflows which you should generally avoid:
.IP \(bu 2
Don\(aqt import from one input file to different journals.
The imports\(aq overlap detection would overwrite the same
\f[CR].latest.FILE\f[R] state file.
(In effect, the journals would compete for the new records.)
.IP \(bu 2
Don\(aqt import from multiple data files on the same day, reusing the
same rules file for all, with \f[CR]archive\f[R] enabled.
The archived file names in \f[CR]data/archive/\f[R] would clash, causing
some archives to be overwritten.
.IP \(bu 2
Don\(aqt do argument\-less \f[CR]hledger import\f[R] to more than one
journal in the same directory.
That would read from the same files in \f[CR]rules/\f[R], potentially
disrupting both overlap detection and archiving.
.SS Deduplication
Here are two kinds of \(dqdeduplication\(dq which \f[CR]import\f[R] does
not handle (and should not, because these can happen legitimately in
financial data):
.IP \(bu 2
Two or more of the new CSV records are identical, and generate identical
new journal entries.
.IP \(bu 2
A new CSV record generates a journal entry identical to one(s) already
in the journal.
.SS Varying file name
If you have a download whose file name varies, you could rename it to a
fixed name after each download.
Or you could use a CSV \f[CR]source\f[R] rule with a suitable glob
pattern, and import from the .rules file.
.SS Multiple versions
Say you download \f[CR]bank.csv\f[R], import it, but forget to delete it
from your downloads folder.
The next time you download it, your web browser will save it as (eg)
\f[CR]bank (2).csv\f[R].
The source rule\(aqs glob patterns are for just this situation: instead
of specifying \f[CR]source bank.csv\f[R], specify
\f[CR]source bank*.csv\f[R].
Then \f[CR]hledger \-f bank.rules CMD\f[R] or
\f[CR]hledger import bank.rules\f[R] will automatically pick the newest
matched file (\f[CR]bank (2).csv\f[R]).
.PP
Alternately, what if you download, but forget to import or delete, then
download again ?
Now each of \f[CR]bank.csv\f[R] and \f[CR]bank (2).csv\f[R] might
contain data that\(aqs not in the other, and not in your journal.
In this case, it\(aqs best to import each of them in turn, oldest first
(otherwise, overlap detection could cause new records to be skipped).
Enabling import archiving ensures this.
Then \f[CR]hledger import bank.rules; hledger import bank.rules\f[R]
will import and archive first \f[CR]bank.csv\f[R], then
\f[CR]bank (2).csv\f[R].
.PP
.PP
.PP
.PP
.SH Report commands
.SS accounts
(acc)
.PP
List the account names used or declared in the journal.
.IP
.EX
Flags:
\-u \-\-used list accounts used
\-d \-\-declared list accounts declared
\-\-undeclared list accounts used but not declared
\-\-unused list accounts declared but not used
\-\-find list the first account matched by the first
argument (a case\-insensitive infix regexp)
\-\-directives show as account directives, for use in journals
\-\-locations also show where accounts were declared, or first
used
\-\-types also show account types when known
\-\-show\-aliases also show account aliases declared with alias:
tags
\-l \-\-flat list/tree mode: show accounts as a flat list
(default)
\-t \-\-tree list/tree mode: show accounts as a tree
\-\-drop=N flat mode: omit N leading account name parts
.EE
.PP
This command lists account names \- all of them by default, or just the
ones which have been used in transactions (\f[CR]\-u/\-\-used\f[R]), or
declared with \f[CR]account\f[R] directives
(\f[CR]\-d/\-\-declared\f[R]), or used but not declared
(\f[CR]\-\-undeclared\f[R]), or declared but not used
(\f[CR]\-\-unused\f[R]), or just the first one matched by a pattern
(\f[CR]\-\-find\f[R], returning a non\-zero exit code if it fails).
.PP
You can add query arguments to select a subset of transactions or
accounts.
Note that transaction\-specific query terms like \f[CR]date:\f[R] will
exclude declared\-but\-unused accounts, which don\(aqt have that field.
.PP
With \f[CR]\-\-directives\f[R], it shows valid account directives which
could be pasted into a journal file, including any account aliases as
\f[CR]alias:\f[R] tags.
This is useful together with \f[CR]\-\-undeclared\f[R] when updating
your account declarations to satisfy \f[CR]hledger check accounts\f[R].
.PP
With \f[CR]\-\-locations\f[R], it also shows the file and line number of
each account\(aqs declaration, if any, and the account\(aqs overall
declaration order; these may be useful when troubleshooting account
display order.
For an undeclared account, it shows where the account was first used
(posted to), if anywhere.
.PP
With \f[CR]\-\-types\f[R], it also shows each account\(aqs type, if
it\(aqs known.
(See Declaring accounts > Account types.)
.PP
With \f[CR]\-\-show\-aliases\f[R], it also shows each account\(aqs
aliases, declared with \f[CR]alias:\f[R] tags.
(Aliases from \f[CR]alias\f[R] directives or \f[CR]\-\-alias\f[R]
options are not shown.)
Also, account names in the query will match aliases too, so eg
\f[CR]hledger accounts \-\-show\-aliases chk\f[R] shows the account(s)
with an alias containing \f[CR]chk\f[R].
.PP
It shows a flat list by default.
With \f[CR]\-\-tree\f[R], it uses indentation to show the account
hierarchy.
In flat mode you can add \f[CR]\-\-drop N\f[R] to omit the first few
account name components.
Account names can be depth\-clipped with \f[CR]depth:N\f[R] or
\f[CR]\-\-depth N\f[R] or \f[CR]\-N\f[R].
.PP
Examples:
.IP
.EX
$ hledger accounts
assets:bank:checking
assets:bank:saving
assets:cash
expenses:food
expenses:supplies
income:gifts
income:salary
liabilities:debts
.EE
.IP
.EX
$ hledger accounts \-\-undeclared \-\-directives >> $LEDGER_FILE
$ hledger check accounts
.EE
.SS activity
Show a bar chart of transaction counts per week, or other report
interval.
.IP
.EX
Flags:
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, svg, html, csv, tsv, json.
\-o \-\-output\-file=FILE write output to FILE. A file extension matching
one of the above formats selects that format.
\-\-view write output to FILE, or to view.FMT in hledger\(aqs
cache directory, and open it in the system\(aqs
default viewer for its format (eg a web browser for
html). The default format is html.
\-w \-\-width=N with \-\-chart: draw the chart N characters wide
(default: the terminal width)
\-\-txns count transactions, showing just the total
(default)
\-\-postings count postings, showing each account\(aqs count
\-S \-\-sort\-amount with \-\-postings, sort accounts by posting count,
largest first
\-T \-\-total show the total count, below the chart
\-A \-\-average show the average count per period, below the
chart (and as a line in SVG charts)
.EE
.PP
The activity command shows how many transactions there are in each week
(or with a report interval, each day, month, quarter etc.), as a bar
chart.
Each transaction is one character, unless there are too many to fit,
when the bars are scaled down.
With query arguments, it counts only the transactions which have at
least one matched posting.
.PP
Or with \f[CR]\-\-postings\f[R], it shows how many postings there are in
each period, with each account\(aqs postings stacked in its own colour.
With query arguments, it counts only the matched postings.
This is a shortcut for \f[CR]balance \-\-count \-\-chart\f[R], with a
weekly interval by default, so it can show charts in all the same ways:
eg with \f[CR]\-1\f[R] or other depth limit to show less detail,
\f[CR]\-0\f[R] to show just the total count, without the accounts\(aq
detail, \f[CR]\-S\f[R]/\f[CR]\-\-sort\-amount\f[R] to show the accounts
with most postings first.
(Transaction counts show just the total, since a transaction\(aqs
postings can be in several accounts.)
.PP
\f[CR]\-\-txns\f[R] selects transaction counts explicitly; if both
\f[CR]\-\-txns\f[R] and \f[CR]\-\-postings\f[R] are given, the last one
wins.
.PP
Both kinds of chart can be shown in the usual ways, eg with
\f[CR]\-w\f[R]/\f[CR]\-\-width\f[R] to set the width,
\f[CR]\-T\f[R]/\f[CR]\-\-total\f[R] and
\f[CR]\-A\f[R]/\f[CR]\-\-average\f[R] to show the total count and the
average count per period below the chart (in graphical charts, the
average is also drawn as a dashed line), or \f[CR]\-o FILE.svg\f[R] (or
\f[CR]\-O svg\f[R]) for a graphical chart.
.PP
Examples:
.IP
.EX
$ hledger activity \-M \-T \-A \-w 40
Transaction counts in 2008:
Jan 1 █
Feb 0
Mar 0
Apr 0
May 0
Jun 3 ███
Jul 0
Aug 0
Sep 0
Oct 0
Nov 0
Dec 1 █
Total 5, Average 0.4
.EE
.IP
.EX
$ hledger activity \-M \-\-postings \-1 \-w 40
Posting counts in 2008:
▓ assets █ expenses ░ income
▒ liabilities
Jan 2 ▓░
Feb 0
Mar 0
Apr 0
May 0
Jun 7 ▓▓▓▓██░
Jul 0
Aug 0
Sep 0
Oct 0
Nov 0
Dec 2 ▓▒
.EE
.SS aregister
(areg)
.PP
Show the transactions and running balances in one account, with one
entry per transaction.
.IP
.EX
Flags:
\-\-txn\-dates filter strictly by transaction date, not posting
date. Warning: this can show a wrong running
balance.
\-\-no\-elide don\(aqt show only 2 commodities per amount
\-\-cumulative accumulation mode: show running total from report
start date
\-H \-\-historical accumulation mode: show historical running
total/balance (includes postings before report
start date) (default)
\-A \-\-average show running average of transaction amounts
instead of balance (implies \-\-empty and, unless \-H
is used, \-\-cumulative)
\-r \-\-related show the other accounts in each transaction
(default)
\-\-matched show the matched accounts (this account or its
subaccounts) instead
\-\-invert display all amounts with reversed sign
\-\-drop=N omit N leading account name parts
\-\-heading=YN show heading row above table: yes (default) or no
\-w \-\-width=N set output width (default: terminal width). \-wN,M
sets description width as well.
\-\-align\-all guarantee alignment across all lines (slower)
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, html, csv, tsv, json, svg.
\-o \-\-output\-file=FILE write output to FILE. A file extension matching
one of the above formats selects that format.
\-\-view write output to FILE, or to view.FMT in hledger\(aqs
cache directory, and open it in the system\(aqs
default viewer for its format (eg a web browser for
html). The default format is html.
\-\-chart[=net,SCALE] show a chart: instead of the table (txt), above
it (html), or as data (csv, tsv, json). net: also
draw the net total (a line, or marks in text
charts). SCALE: the amount that fills the chart (eg
1000 or 1000 USD; one per commodity), for
comparable charts.
.EE
.PP
\f[CR]aregister\f[R] shows the overall transactions affecting a
particular account (and any subaccounts).
Each report line represents one transaction in this account.
Transactions before the report start date are included in the running
balance (\f[CR]\-\-historical\f[R] mode is the default).
You can suppress this behaviour using the \f[CR]\-\-cumulative\f[R]
option.
.PP
This is a more \(dqreal world\(dq, bank\-like view than the
\f[CR]register\f[R] command (which shows individual postings, possibly
from multiple accounts, not necessarily in historical mode).
As a quick rule of thumb:
.IP \(bu 2
\f[CR]aregister\f[R] is best when reconciling real\-world
asset/liability accounts
.IP \(bu 2
\f[CR]register\f[R] is best when reviewing individual revenues/expenses.
.PP
Note this command\(aqs non\-standard, and required, first argument; it
specifies the account whose register will be shown.
You can write the account\(aqs name, or (to save typing) a
case\-insensitive infix regular expression matching the name, which
selects the alphabetically first matched account.
(For example, if you have \f[CR]assets:personal checking\f[R] and
\f[CR]assets:business checking\f[R], \f[CR]hledger areg checking\f[R]
would select \f[CR]assets:business checking\f[R].)
.PP
Transactions involving subaccounts of this account will also be shown.
\f[CR]aregister\f[R] ignores depth limits, so its final total will
always match a historical balance report with similar arguments.
.PP
Any additional arguments are standard query arguments, which will limit
the transactions shown.
Note some queries will disturb the running balance, causing it to be
different from the account\(aqs real\-world running balance.
.PP
An example: this shows the transactions and historical running balance
during july, in the first account whose name contains \(dqchecking\(dq:
.IP
.EX
$ hledger areg checking date:jul
.EE
.PP
Each \f[CR]aregister\f[R] line item shows:
.IP \(bu 2
the transaction\(aqs date (or the relevant posting\(aqs date if
different, see below)
.IP \(bu 2
the names of all the other account(s) involved in this transaction
(probably abbreviated)
.IP \(bu 2
the total change to this account\(aqs balance from this transaction
.IP \(bu 2
the account\(aqs historical running balance after this transaction.
.PP
The account column normally shows the other accounts in each transaction
(this is also selectable with \f[CR]\-r/\-\-related\f[R]).
With \f[CR]\-\-matched\f[R], it shows the matched accounts instead: this
account, or the subaccounts of it that were posted to.
This is useful when the account has subaccounts, eg:
.IP
.EX
$ hledger areg expenses \-\-matched
.EE
.PP
shows which expense categories each transaction touched.
Any additional query arguments also narrow the matched accounts shown.
The amounts and running balance are the same in both modes.
.PP
Transactions making a net change of zero are not shown by default; add
the \f[CR]\-E/\-\-empty\f[R] flag to show them.
.PP
The \f[CR]\-A/\-\-average\f[R] flag shows the running average change per
transaction, instead of the running balance, so the last number shown is
the average for the whole report period.
It implies \f[CR]\-\-empty\f[R], since zero\-change transactions also
affect the average.
Unlike aregister\(aqs other reports, it is not historical by default;
add \f[CR]\-H\f[R] to include the transactions before the report start
date in the average.
Like \f[CR]register \-A\f[R], it works best with a single commodity.
.PP
For performance reasons, column widths are chosen based on the first
1000 lines; this means unusually wide values in later lines can cause
visual discontinuities as column widths are adjusted.
If you want to ensure perfect alignment, at the cost of more time and
memory, use the \f[CR]\-\-align\-all\f[R] flag.
.PP
By default, \f[CR]aregister\f[R] shows a heading above the data.
However, when reporting in a language different from English, it is
easier to omit this heading and prepend your own one.
For this purpose, use the \f[CR]\-\-heading=no\f[R] option.
.PP
This command also supports the output destination and output format
options.
The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],
\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]fods\f[R] and \f[CR]json\f[R].
.PP
With \f[CR]\-\-chart\f[R], or with \f[CR]svg\f[R] output
(\f[CR]\-o FILE.svg\f[R]), it shows a chart of the account\(aqs balance
(or running total or average) over time instead.
A text chart has a row per transaction (for a row per period instead,
use a balance report with a report interval and \f[CR]\-H\f[R]).
An SVG chart draws the balance as a line on a time scale.
With \f[CR]\-\-chart \-O csv\f[R] (or tsv or json) it shows the
chart\(aqs data.
See also Balance charts.
.SS aregister and posting dates
aregister always shows one entry (and one date and amount) per
transaction.
(With a single commodity, this means line = one transaction.
But multi\-commodity amounts will be shown with one line per commodity.)
But sometimes transactions have postings with different dates.
Also, not all of a transaction\(aqs postings may be within the report
period.
To resolve this, aregister shows the earliest of the transaction\(aqs
date and posting dates that is in\-period, and the sum of the in\-period
postings.
In other words it will show a combined line item with just the earliest
date, and the running balance will (temporarily, until the
transaction\(aqs last posting) be inaccurate.
Use \f[CR]register \-H\f[R] if you need to see the individual postings.
.PP
There is also a \f[CR]\-\-txn\-dates\f[R] flag, which filters strictly
by transaction date, ignoring posting dates.
This too can cause an inaccurate running balance.
.SS balance
(bal)
.PP
Show accounts with some kind of summed numeric data: balance changes per
period, end balances on period end dates, simple capital gains, budget
goal performance, etc.
.IP
.EX
Flags:
\-\-sum calculation mode: show sum of posting amounts
(default)
\-\-valuechange calculation mode: show total change of value
of period\-end historical balances (caused by
deposits, withdrawals, market price
fluctuations)
\-\-gain calculation mode: show capital gain/loss
(historical balance value minus cost basis, or
transacted cost where there is none)
\-\-budget[=DESCPAT] calculation mode: show sum of posting amounts
together with budget goals defined by periodic
transactions. With a DESCPAT argument (must be
separated by = not space),
use only periodic transactions with matching
description
(case insensitive substring match).
\-\-count calculation mode: show the count of postings
\-\-change accumulation mode: accumulate amounts from
column start to column end (in multicolumn
reports, default)
\-\-cumulative accumulation mode: accumulate amounts from
report start (specified by e.g. \-b/\-\-begin) to
column end
\-H \-\-historical accumulation mode: accumulate amounts from
journal start to column end (includes postings
before report start date)
\-l \-\-flat list/tree mode: show accounts as a flat list
(default). Amounts exclude subaccount amounts,
except where the account is depth\-clipped.
\-t \-\-tree list/tree mode: show accounts as a tree.
Amounts include subaccount amounts.
\-\-drop=N in list mode, omit N leading account name
parts
\-\-declared include non\-parent declared accounts (best
used with \-E)
\-A \-\-average show a row average column (in multicolumn
reports)
\-T \-\-row\-total show a row total column (in multicolumn
reports)
\-\-summary\-only display only row summaries (e.g. row total,
average) (in multicolumn reports)
\-N \-\-no\-total omit the final total row
\-\-no\-elide in tree mode, don\(aqt squash boring parent
accounts; in list mode, also show parent
accounts (usually zero, hidden without \-E)
\-\-full\-names in tree mode, show full account names instead
of indented leaf names
\-\-format=FORMATSTR use this custom line format (in simple
reports)
\-S \-\-sort\-amount sort by amount instead of account code/name
(in flat mode). With multiple columns, sorts by
the row total, or by row average if that is
displayed.
\-% \-\-percent express values in percentage of each column\(aqs
total
\-r \-\-related show the other accounts transacted with,
instead
\-\-invert display all amounts with reversed sign
\-\-transpose switch rows and columns (use vertical time
axis); repeat to cancel
\-\-layout=ARG how to lay out multi\-commodity amounts and the
overall table:
\(aqwide[,W]\(aq: commodities on same line, up to W
wide
\(aqtall\(aq : commodities on separate lines
\(aqbare\(aq : commodity symbols in a separate
column
\(aqtidy\(aq : each data field in its own column
\-\-base\-url=URLPREFIX in html output, generate links to hledger\-web,
with this prefix. (Usually the base url shown by
hledger\-web; can also be relative.)
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, html, csv, tsv, json, fods, svg.
\-o \-\-output\-file=FILE write output to FILE. A file extension
matching one of the above formats selects that
format.
\-\-view write output to FILE, or to view.FMT in
hledger\(aqs cache directory, and open it in the
system\(aqs default viewer for its format (eg a web
browser for html). The default format is html.
\-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),
above it (html), or as data (csv, tsv, json).
KIND: grouped (a bar per account type, side by
side). net: also draw the net total (a line, or
marks in text charts). SCALE: the amount that
fills the chart (eg 1000 or 1000 USD; one per
commodity), for comparable charts.
\-w \-\-width=N with \-\-chart: draw the chart N characters wide
(default: the terminal width)
.EE
.PP
\f[CR]balance\f[R] is one of hledger\(aqs oldest and most versatile
commands, for listing account balances, balance changes, values, value
changes and more, during one time period or many.
Generally it shows a table, with rows representing accounts, and columns
representing periods.
.PP
Note there are some variants of the \f[CR]balance\f[R] command with
convenient defaults, which are simpler to use: \f[CR]balancesheet\f[R],
\f[CR]balancesheetequity\f[R], \f[CR]cashflow\f[R] and
\f[CR]incomestatement\f[R].
When you need more control, then use \f[CR]balance\f[R].
.SS balance features
Here\(aqs a quick overview of the \f[CR]balance\f[R] command\(aqs
features, followed by more detailed descriptions and examples.
Many of these work with the other balance\-like commands as well
(\f[CR]bs\f[R], \f[CR]cf\f[R], \f[CR]is\f[R]..).
.PP
\f[CR]balance\f[R] can show..
.IP \(bu 2
accounts as a list (\f[CR]\-l\f[R]) or a tree (\f[CR]\-t\f[R])
.IP \(bu 2
optionally depth\-limited (\f[CR]\-[1\-9]\f[R])
.IP \(bu 2
sorted by declaration order and name, or by amount
.PP
\&..and their..
.IP \(bu 2
balance changes (the default)
.IP \(bu 2
or actual and planned balance changes (\f[CR]\-\-budget\f[R])
.IP \(bu 2
or value of balance changes (\f[CR]\-V\f[R])
.IP \(bu 2
or change of balance values (\f[CR]\-\-valuechange\f[R])
.IP \(bu 2
or capital gain/loss (\f[CR]\-\-gain\f[R])
.IP \(bu 2
or balance changes from sibling postings
(\f[CR]\-\-related\f[R]/\f[CR]\-r\f[R])
.IP \(bu 2
or postings count (\f[CR]\-\-count\f[R])
.PP
\&..in..
.IP \(bu 2
one time period (the whole journal period by default)
.IP \(bu 2
or multiple periods (\f[CR]\-D\f[R], \f[CR]\-W\f[R], \f[CR]\-M\f[R],
\f[CR]\-Q\f[R], \f[CR]\-Y\f[R], \f[CR]\-p INTERVAL\f[R])
.PP
\&..either..
.IP \(bu 2
per period (the default)
.IP \(bu 2
or accumulated since report start date (\f[CR]\-\-cumulative\f[R])
.IP \(bu 2
or accumulated since account creation (\f[CR]\-\-historical/\-H\f[R])
.PP
\&..possibly converted to..
.IP \(bu 2
cost
(\f[CR]\-\-value=cost[,COMM]\f[R]/\f[CR]\-\-cost\f[R]/\f[CR]\-B\f[R])
.IP \(bu 2
or market value, as of transaction dates
(\f[CR]\-\-value=then[,COMM]\f[R])
.IP \(bu 2
or at period ends (\f[CR]\-\-value=end[,COMM]\f[R])
.IP \(bu 2
or now (\f[CR]\-\-value=now\f[R])
.IP \(bu 2
or at some other date (\f[CR]\-\-value=YYYY\-MM\-DD\f[R])
.PP
\&..with..
.IP \(bu 2
totals (\f[CR]\-T\f[R]), averages (\f[CR]\-A\f[R]), percentages
(\f[CR]\-%\f[R]), inverted sign (\f[CR]\-\-invert\f[R])
.IP \(bu 2
rows and columns swapped (\f[CR]\-\-transpose\f[R])
.IP \(bu 2
another field used as account name (\f[CR]\-\-pivot\f[R])
.IP \(bu 2
custom\-formatted line items (single\-period reports only)
(\f[CR]\-\-format\f[R])
.IP \(bu 2
commodities displayed on the same line or multiple lines
(\f[CR]\-\-layout\f[R])
.IP \(bu 2
a chart instead of a table (\f[CR]\-\-chart\f[R])
.PP
This command supports the output destination and output format options,
with output formats \f[CR]txt\f[R], \f[CR]csv\f[R], \f[CR]tsv\f[R],
\f[CR]json\f[R], \f[CR]html\f[R], \f[CR]fods\f[R], and \f[CR]svg\f[R].
In \f[CR]txt\f[R] output in a colour\-supporting terminal, negative
amounts are shown in red.
.SS Simple balance report
With no arguments, \f[CR]balance\f[R] shows a list of all accounts and
their change of balance \- ie, the sum of posting amounts, both inflows
and outflows \- during the entire period of the journal.
(\(dqSimple\(dq here means just one column of numbers, covering a single
period.
You can also have multi\-period reports, described later.)
.PP
For real\-world accounts, these numbers will normally be their end
balance at the end of the journal period; more on this below.
.PP
Accounts are sorted by declaration order if any, and then alphabetically
by account name.
For instance (using examples/sample.journal):
.IP
.EX
$ hledger \-f examples/sample.journal bal
$1 assets:bank:saving
$\-2 assets:cash
$1 expenses:food
$1 expenses:supplies
$\-1 income:gifts
$\-1 income:salary
$1 liabilities:debts
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
Accounts with a zero balance (and no non\-zero subaccounts, in tree mode
\- see below) are hidden by default.
Use \f[CR]\-E/\-\-empty\f[R] to show them (revealing
\f[CR]assets:bank:checking\f[R] here):
.IP
.EX
$ hledger \-f examples/sample.journal bal \-E
0 assets:bank:checking
$1 assets:bank:saving
$\-2 assets:cash
$1 expenses:food
$1 expenses:supplies
$\-1 income:gifts
$\-1 income:salary
$1 liabilities:debts
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
The total of the amounts displayed is shown as the last line, unless
\f[CR]\-N\f[R]/\f[CR]\-\-no\-total\f[R] is used.
.SS Balance report line format
For single\-period balance reports displayed in the terminal (only), you
can use \f[CR]\-\-format FMT\f[R] to customise the format and content of
each line.
Eg:
.IP
.EX
$ hledger \-f examples/sample.journal balance \-\-format \(dq%20(account) %12(total)\(dq
assets $\-1
bank:saving $1
cash $\-2
expenses $2
food $1
supplies $1
income $\-2
gifts $\-1
salary $\-1
liabilities:debts $1
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
The FMT format string specifies the formatting applied to each
account/balance pair.
It may contain any suitable text, with data fields interpolated like so:
.PP
\f[CR]%[MIN][.MAX](FIELDNAME)\f[R]
.IP \(bu 2
MIN pads with spaces to at least this width (optional)
.IP \(bu 2
MAX truncates at this width (optional)
.IP \(bu 2
FIELDNAME must be enclosed in parentheses, and can be one of:
.RS 2
.IP \(bu 2
\f[CR]depth_spacer\f[R] \- a number of spaces equal to the account\(aqs
depth, or if MIN is specified, MIN * depth spaces.
.IP \(bu 2
\f[CR]account\f[R] \- the account\(aqs name
.IP \(bu 2
\f[CR]total\f[R] \- the account\(aqs balance/posted total, right
justified
.RE
.PP
Also, FMT can begin with an optional prefix to control how
multi\-commodity amounts are rendered:
.IP \(bu 2
\f[CR]%_\f[R] \- render on multiple lines, bottom\-aligned (the default)
.IP \(bu 2
\f[CR]%\(ha\f[R] \- render on multiple lines, top\-aligned
.IP \(bu 2
\f[CR]%,\f[R] \- render on one line, comma\-separated
.PP
There are some quirks.
Eg in one\-line mode, \f[CR]%(depth_spacer)\f[R] has no effect, instead
\f[CR]%(account)\f[R] has indentation built in.
Experimentation may be needed to get pleasing results.
.PP
Some example formats:
.IP \(bu 2
\f[CR]%(total)\f[R] \- the account\(aqs total
.IP \(bu 2
\f[CR]%\-20.20(account)\f[R] \- the account\(aqs name, left justified,
padded to 20 characters and clipped at 20 characters
.IP \(bu 2
\f[CR]%,%\-50(account) %25(total)\f[R] \- account name padded to 50
characters, total padded to 20 characters, with multiple commodities
rendered on one line
.IP \(bu 2
\f[CR]%20(total) %2(depth_spacer)%\-(account)\f[R] \- the default
format for the single\-column balance report.
The total field keeps this 20\-character width as a minimum, but widens
automatically when displayed amounts need more room.
.SS Filtered balance report
You can show fewer accounts, a different time period, totals from
cleared transactions only, etc.
by using query arguments or options to limit the postings being matched.
Eg:
.IP
.EX
$ hledger \-f examples/sample.journal bal \-\-cleared assets date:200806
$\-2 assets:cash
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
$\-2
.EE
.SS List or tree mode
By default, or with \f[CR]\-l/\-\-flat\f[R], accounts are shown as a
flat list with their full names visible, as in the examples above.
.PP
With \f[CR]\-t/\-\-tree\f[R], the account hierarchy is shown, with
subaccounts\(aq \(dqleaf\(dq names indented below their parent:
.IP
.EX
$ hledger \-f examples/sample.journal balance
$\-1 assets
$1 bank:saving
$\-2 cash
$2 expenses
$1 food
$1 supplies
$\-2 income
$\-1 gifts
$\-1 salary
$1 liabilities:debts
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
Notes:
.IP \(bu 2
\(dqBoring\(dq accounts are combined with their subaccount for more
compact output, unless \f[CR]\-\-no\-elide\f[R] is used.
Boring accounts have no balance of their own and just one subaccount (eg
\f[CR]assets:bank\f[R] and \f[CR]liabilities\f[R] above).
.IP \(bu 2
All balances shown are \(dqinclusive\(dq, ie including the balances from
all subaccounts.
Note this means some repetition in the output, which requires
explanation when sharing reports with non\-plaintextaccounting\-users.
A tree mode report\(aqs final total is the sum of the top\-level
balances shown, not of all the balances shown.
.IP \(bu 2
Each group of sibling accounts (ie, under a common parent) is sorted
separately.
.PP
In list mode, \f[CR]\-\-no\-elide\f[R] shows parent accounts as well,
with their exclusive balances.
These are zero unless the parent has postings of its own, so
\f[CR]\-E/\-\-empty\f[R] is usually also needed to make them visible.
Together, these flags guarantee a complete table of all posted\-to
accounts and their parents, with full names:
.IP
.EX
$ hledger \-f examples/sample.journal balance \-\-no\-elide \-E
0 assets
0 assets:bank
0 assets:bank:checking
$1 assets:bank:saving
$\-2 assets:cash
0 expenses
$1 expenses:food
$1 expenses:supplies
0 income
$\-1 income:gifts
$\-1 income:salary
0 liabilities
$1 liabilities:debts
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
This can be useful eg when exporting to a spreadsheet which will look up
balances by account name.
.PP
In tree mode, \f[CR]\-\-full\-names\f[R] writes each account\(aqs full
name instead of indenting leaf names, while keeping tree mode\(aqs
inclusive balances.
So \f[CR]\-\-tree \-\-no\-elide \-\-full\-names \-E\f[R] shows the same
complete table as above, but with inclusive balances:
.IP
.EX
$ hledger \-f examples/sample.journal balance \-\-tree \-\-no\-elide \-\-full\-names \-E
$\-1 assets
$1 assets:bank
0 assets:bank:checking
$1 assets:bank:saving
$\-2 assets:cash
$2 expenses
$1 expenses:food
$1 expenses:supplies
$\-2 income
$\-1 income:gifts
$\-1 income:salary
$1 liabilities
$1 liabilities:debts
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
Note that in this variant, parent and subaccount balances overlap, so
(as in any tree mode report) the rows sum to more than the final total.
.SS Depth limiting
With a \f[CR]depth:NUM\f[R] query, or \f[CR]\-\-depth NUM\f[R] option,
or just \f[CR]\-NUM\f[R] (eg: \f[CR]\-3\f[R]) balance reports will show
accounts only to the specified depth, hiding the deeper subaccounts.
This can be useful for getting an overview without too much detail.
.PP
Account balances at the depth limit always include the balances from any
deeper subaccounts (even in list mode).
Eg, limiting to depth 1:
.IP
.EX
$ hledger \-f examples/sample.journal balance \-1
$\-1 assets
$2 expenses
$\-2 income
$1 liabilities
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.SS Dropping top\-level accounts
You can also hide one or more top\-level account name parts, using
\f[CR]\-\-drop NUM\f[R].
This can be useful for hiding repetitive top\-level account names:
.IP
.EX
$ hledger \-f examples/sample.journal bal expenses \-\-drop 1
$1 food
$1 supplies
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
$2
.EE
.PP
.SS Showing declared accounts
With \f[CR]\-\-declared\f[R], accounts which have been declared with an
account directive will be included in the balance report, even if they
have no transactions.
(Since they will have a zero balance, you will also need
\f[CR]\-E/\-\-empty\f[R] to see them.)
.PP
More precisely, \f[I]leaf\f[R] declared accounts (with no subaccounts)
will be included, since those are usually the more useful in reports.
.PP
The idea of this is to be able to see a useful \(dqcomplete\(dq balance
report, even when you don\(aqt have transactions in all of your declared
accounts yet.
.SS Sorting by amount
With \f[CR]\-S/\-\-sort\-amount\f[R], accounts with the largest (most
positive) balances are shown first.
Eg: \f[CR]hledger bal expenses \-MAS\f[R] shows your biggest averaged
monthly expenses first.
When more than one commodity is present, they will be sorted by the
alphabetically earliest commodity first, and then by subsequent
commodities (if an amount is missing a commodity, it is treated as 0).
.PP
Revenues and liability balances are typically negative, however, so
\f[CR]\-S\f[R] shows these in reverse order.
To work around this, you can add \f[CR]\-\-invert\f[R] to flip the
signs.
Or you could use one of the higher\-level balance reports
(\f[CR]bs\f[R], \f[CR]is\f[R]..), which flip the sign automatically (eg:
\f[CR]hledger is \-MAS\f[R]).
.PP
.SS Percentages
With \f[CR]\-%/\-\-percent\f[R], balance reports show each account\(aqs
value expressed as a percentage of the (column) total.
.PP
Note it is not useful to calculate percentages if the amounts in a
column have mixed signs.
In this case, make a separate report for each sign, eg:
.IP
.EX
$ hledger bal \-% amt:\(ga>0\(ga
$ hledger bal \-% amt:\(ga<0\(ga
.EE
.PP
Similarly, if the amounts in a column have mixed commodities, convert
them to one commodity with \f[CR]\-B\f[R], \f[CR]\-V\f[R],
\f[CR]\-X\f[R] or \f[CR]\-\-value\f[R], or make a separate report for
each commodity:
.IP
.EX
$ hledger bal \-% cur:\(rs\(rs$
$ hledger bal \-% cur:€
.EE
.SS Multi\-period balance report
With a report interval (set by the \f[CR]\-D/\-\-daily\f[R],
\f[CR]\-W/\-\-weekly\f[R], \f[CR]\-M/\-\-monthly\f[R],
\f[CR]\-Q/\-\-quarterly\f[R], \f[CR]\-Y/\-\-yearly\f[R], or
\f[CR]\-p/\-\-period\f[R] flag), \f[CR]balance\f[R] shows a tabular
report, with columns representing successive time periods (and a title):
.IP
.EX
$ hledger \-f examples/sample.journal bal \-\-quarterly income expenses \-E
Balance changes in 2008:
|| 2008q1 2008q2 2008q3 2008q4
===================++=================================
expenses:food || 0 $1 0 0
expenses:supplies || 0 $1 0 0
income:gifts || 0 $\-1 0 0
income:salary || $\-1 0 0 0
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| $\-1 $1 0 0
.EE
.PP
Notes:
.IP \(bu 2
The report\(aqs start/end dates will be expanded, if necessary, to fully
encompass the displayed subperiods (so that the first and last
subperiods have the same duration as the others).
.IP \(bu 2
Leading and trailing periods (columns) containing all zeroes are not
shown, unless \f[CR]\-E/\-\-empty\f[R] is used.
.IP \(bu 2
Accounts (rows) containing all zeroes are not shown, unless
\f[CR]\-E/\-\-empty\f[R] is used.
.IP \(bu 2
Amounts with many commodities are shown in abbreviated form, unless
\f[CR]\-\-no\-elide\f[R] is used.
.IP \(bu 2
Average and/or total columns can be added with the
\f[CR]\-A/\-\-average\f[R] and \f[CR]\-T/\-\-row\-total\f[R] flags.
.IP \(bu 2
The \f[CR]\-\-transpose\f[R] flag can be used to exchange rows and
columns.
Repeating it reverses its effect (an even number of
\f[CR]\-\-transpose\f[R] flags has no effect).
.IP \(bu 2
The \f[CR]\-\-pivot FIELD\f[R] option causes a different transaction
field to be used as \(dqaccount name\(dq.
See PIVOTING.
.IP \(bu 2
The \f[CR]\-\-summary\-only\f[R] flag (\f[CR]\-\-summary\f[R] also
works) hides all but the Total and Average columns (those should be
enabled with \f[CR]\-\-row\-total\f[R] and \f[CR]\-A/\-\-average\f[R]).
.PP
Multi\-period reports with many periods can be too wide for easy viewing
in the terminal.
Here are some ways to handle that:
.IP \(bu 2
Hide the totals row with \f[CR]\-N/\-\-no\-total\f[R]
.IP \(bu 2
Filter to a single currency with \f[CR]cur:\f[R]
.IP \(bu 2
Convert to a single currency with
\f[CR]\-V [\-\-infer\-market\-price]\f[R]
.IP \(bu 2
Use a more compact layout like \f[CR]\-\-layout=bare\f[R]
.IP \(bu 2
Maximize the terminal window
.IP \(bu 2
Reduce the terminal\(aqs font size
.IP \(bu 2
View with a pager like less, eg:
\f[CR]hledger bal \-D \-\-color=yes | less \-RS\f[R]
.IP \(bu 2
Output as CSV and use a CSV viewer like visidata
(\f[CR]hledger bal \-D \-O csv | vd \-f csv\f[R]), Emacs\(aq csv\-mode
(\f[CR]M\-x csv\-mode, C\-c C\-a\f[R]), or a spreadsheet
(\f[CR]hledger bal \-D \-o a.csv && open a.csv\f[R])
.IP \(bu 2
Output as HTML and view with a browser:
\f[CR]hledger bal \-D \-o a.html && open a.html\f[R]
.SS Balance change, end balance
It\(aqs important to be clear on the meaning of the numbers shown in
balance reports.
Here is some terminology we use:
.PP
A \f[B]\f[BI]balance change\f[B]\f[R] is the net amount added to, or
removed from, an account during some period.
.PP
An \f[B]\f[BI]end balance\f[B]\f[R] is the amount accumulated in an
account as of some date (and some time, but hledger doesn\(aqt store
that; assume end of day in your timezone).
It is the sum of previous balance changes.
.PP
We call it a \f[B]\f[BI]historical end balance\f[B]\f[R] if it includes
all balance changes since the account was created.
For a real world account, this means it will match the \(dqhistorical
record\(dq, eg the balances reported in your bank statements or bank web
UI.
(If they are correct!)
.PP
In general, balance changes are what you want to see when reviewing
revenues and expenses, and historical end balances are what you want to
see when reviewing or reconciling asset, liability and equity accounts.
.PP
\f[CR]balance\f[R] shows balance changes by default.
To see accurate historical end balances:
.IP "1." 3
Initialise account starting balances with an \(dqopening balances\(dq
transaction (a transfer from equity to the account), unless the journal
covers the account\(aqs full lifetime.
.IP "2." 3
Include all of of the account\(aqs prior postings in the report, by not
specifying a report start date, or by using the
\f[CR]\-H/\-\-historical\f[R] flag.
(\f[CR]\-H\f[R] causes report start date to be ignored when summing
postings.)
.SS Balance report modes
The balance command is quite flexible; here is the full detail on how to
control what it reports.
If the following seems complicated, don\(aqt worry \- this is for
advanced reporting, and it does take time and experimentation to get
familiar with all the report modes.
.PP
There are three important option groups:
.PP
\f[CR]hledger balance [CALCULATIONMODE] [ACCUMULATIONMODE] [VALUATIONMODE] ...\f[R]
.SS Calculation mode
The basic calculation to perform for each table cell.
It is one of:
.IP \(bu 2
\f[CR]\-\-sum\f[R] : sum the posting amounts (\f[B]default\f[R])
.IP \(bu 2
\f[CR]\-\-budget\f[R] : sum the amounts, but also show the budget goal
amount (for each account/period)
.IP \(bu 2
\f[CR]\-\-valuechange\f[R] : show the change in period\-end historical
balance values (caused by deposits, withdrawals, and/or market price
fluctuations)
.IP \(bu 2
\f[CR]\-\-gain\f[R] : show capital gain/loss for each account: the
current valued balance minus its cost.
For lot\-tracked commodities the cost is the cost basis of the units
still held, so this is the unrealised gain.
For other commodities it is the net of postings\(aq transacted costs
(acquisition costs minus disposal proceeds): where nothing has been sold
this too is the unrealised gain, but once disposals exist the figure
also includes the realised gain on the disposed units, so it is best
read as \(dqtotal gain since inception\(dq (to separate realised and
unrealised gains, track lots).
Compare \f[CR]\-\-valuechange\f[R], which shows how much the value moved
in a period, from price changes and from buying and selling.
See Unrealised gains for examples.
.IP \(bu 2
\f[CR]\-\-count\f[R] : show the count of postings
.SS Accumulation mode
How amounts should accumulate across a report\(aqs subperiods/columns.
Another way to say it: which time period\(aqs postings should contribute
to each cell\(aqs calculation.
It is one of:
.IP \(bu 2
\f[CR]\-\-change\f[R] : calculate with postings from column start to
column end, ie \(dqjust this column\(dq.
Typically used to see revenues/expenses.
(\f[B]default for balance, cashflow, incomestatement\f[R])
.IP \(bu 2
\f[CR]\-\-cumulative\f[R] : calculate with postings from report start to
column end, ie \(dqprevious columns plus this column\(dq.
Typically used to show changes accumulated since the report\(aqs start
date.
Not often used.
.IP \(bu 2
\f[CR]\-\-historical/\-H\f[R] : calculate with postings from journal
start to column end, ie \(dqall postings from before report start date
until this column\(aqs end\(dq.
Typically used to see historical end balances of
assets/liabilities/equity.
(\f[B]default for balancesheet, balancesheetequity\f[R])
.SS Valuation mode
Which kind of value or cost conversion should be applied, if any, before
displaying the report.
See Cost reporting and Value reporting for more about conversions.
.PP
A valuation (or cost) mode can be selected with the \-\-value option:
.IP \(bu 2
no conversion : don\(aqt convert to cost or value (\f[B]default\f[R])
.IP \(bu 2
\f[CR]\-\-value=cost[,COMM]\f[R] : convert amounts to cost (then
optionally to some other commodity)
.IP \(bu 2
\f[CR]\-\-value=then[,COMM]\f[R] : convert amounts to market value on
transaction dates
.IP \(bu 2
\f[CR]\-\-value=end[,COMM]\f[R] : convert amounts to market value on
period end date(s)
.PD 0
.P
.PD
(\f[B]default with \f[CB]\-\-valuechange\f[B], \f[CB]\-\-gain\f[B]\f[R])
.IP \(bu 2
\f[CR]\-\-value=now[,COMM]\f[R] : convert amounts to market value on
today\(aqs date
.IP \(bu 2
\f[CR]\-\-value=YYYY\-MM\-DD[,COMM]\f[R] : convert amounts to market
value on another date
.PP
or with the legacy \-B/\-V/\-X options, which are equivalent and easier
to type:
.IP \(bu 2
\f[CR]\-B\f[R]/\f[CR]\-\-cost\f[R] : like \-\-value=cost
.IP \(bu 2
\f[CR]\-V\f[R]/\f[CR]\-\-market\f[R] : like \-\-value=end
.IP \(bu 2
\f[CR]\-X COMM\f[R]/\f[CR]\-\-exchange COMM\f[R] : like
\-\-value=end,COMM
.PP
Note that \-\-value can also convert to cost, as a convenience; but
actually \-\-cost and \-\-value are independent options, and could be
used together.
.SS Combining balance report modes
Most combinations of these modes produce reasonable reports.
The following restrictions are applied:
.IP \(bu 2
\f[CR]\-\-valuechange\f[R] implies \f[CR]\-\-value=end\f[R]
.IP \(bu 2
\f[CR]\-\-valuechange\f[R] makes \f[CR]\-\-change\f[R] the default when
used with the \f[CR]balancesheet\f[R]/\f[CR]balancesheetequity\f[R]
commands
.IP \(bu 2
\f[CR]\-\-cumulative\f[R] or \f[CR]\-\-historical\f[R] disables
\f[CR]\-\-row\-total/\-T\f[R]
.PP
For reference, here is what the combinations of accumulation and
valuation show:
.PP
.TS
tab(@);
lw(7.9n) lw(16.4n) lw(16.9n) lw(15.1n) lw(13.7n).
T{
Valuation:> Accumulation:v
T}@T{
no valuation
T}@T{
\f[CR]\-\-value= then\f[R]
T}@T{
\f[CR]\-\-value= end\f[R]
T}@T{
\f[CR]\-\-value= YYYY\-MM\-DD /now\f[R]
T}
_
T{
\f[CR]\-\-change\f[R]
T}@T{
change in period
T}@T{
sum of posting\-date market values in period
T}@T{
period\-end value of change in period
T}@T{
DATE\-value of change in period
T}
T{
\f[CR]\-\-cumulative\f[R]
T}@T{
change from report start to period end
T}@T{
sum of posting\-date market values from report start to period end
T}@T{
period\-end value of change from report start to period end
T}@T{
DATE\-value of change from report start to period end
T}
T{
\f[CR]\-\-historical /\-H\f[R]
T}@T{
change from journal start to period end (historical end balance)
T}@T{
sum of posting\-date market values from journal start to period end
T}@T{
period\-end value of change from journal start to period end
T}@T{
DATE\-value of change from journal start to period end
T}
.TE
.SS Budget report
The \f[CR]balance \-\-budget\f[R] report is like a regular balance
report, but with two main differences:
.IP \(bu 2
Budget goals and performance percentages are also shown, in brackets
.IP \(bu 2
Accounts which don\(aqt have budget goals are hidden by default.
.PP
This is useful for comparing planned and actual income, expenses, time
usage, etc.
.PP
Periodic transaction rules are used to define budget goals.
For example, here\(aqs a periodic rule defining monthly goals for bus
travel and food expenses:
.IP
.EX
;; Budget
\(ti monthly
(expenses:bus) $30
(expenses:food) $400
.EE
.PP
After recording some actual expenses,
.IP
.EX
;; Two months worth of expenses
2017\-11\-01
income $\-1950
expenses:bus $35
expenses:food:groceries $310
expenses:food:dining $42
expenses:movies $38
assets:bank:checking
2017\-12\-01
income $\-2100
expenses:bus $53
expenses:food:groceries $380
expenses:food:dining $32
expenses:gifts $100
assets:bank:checking
.EE
.PP
we can see a budget report like this:
.IP
.EX
$ hledger bal \-M \-\-budget
Budget performance in 2017\-11\-01..2017\-12\-31:
|| Nov Dec
===============++============================================
<unbudgeted> || $\-425 $\-565
expenses || $425 [ 99% of $430] $565 [131% of $430]
expenses:bus || $35 [117% of $30] $53 [177% of $30]
expenses:food || $352 [ 88% of $400] $412 [103% of $400]
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 0 [ 0% of $430] 0 [ 0% of $430]
.EE
.PP
This is \(dqgoal\-based budgeting\(dq; you define goals for accounts and
periods, often recurring, and hledger shows performance relative to the
goals.
This contrasts with \(dqenvelope budgeting\(dq, which is more detailed
and strict \- useful when cash is tight, but also quite a bit more work.
https://plaintextaccounting.org/Budgeting has more on this topic.
.SS Using the budget report
Historically this report has been confusing and fragile.
hledger\(aqs version should be relatively robust and intuitive, but you
may still find surprises.
Here are more notes to help with learning and troubleshooting.
.IP \(bu 2
In the above example, \f[CR]expenses:bus\f[R] and
\f[CR]expenses:food\f[R] are shown because they have budget goals during
the report period.
.IP \(bu 2
Their parent \f[CR]expenses\f[R] is also shown, with budget goals
aggregated from the children.
.IP \(bu 2
The subaccounts \f[CR]expenses:food:groceries\f[R] and
\f[CR]expenses:food:dining\f[R] are not shown since they have no budget
goal of their own, but they contribute to \f[CR]expenses:food\f[R]\(aqs
actual amount.
.IP \(bu 2
Unbudgeted accounts \f[CR]expenses:movies\f[R] and
\f[CR]expenses:gifts\f[R] are also not shown, but they contribute to
\f[CR]expenses\f[R]\(aqs actual amount.
.IP \(bu 2
The other unbudgeted accounts \f[CR]income\f[R] and
\f[CR]assets:bank:checking\f[R] are grouped as \f[CR]<unbudgeted>\f[R].
.IP \(bu 2
\f[CR]\-\-depth\f[R] or \f[CR]depth:\f[R] can be used to limit report
depth in the usual way (but will not reveal unbudgeted subaccounts).
.IP \(bu 2
Amounts are always inclusive of subaccounts (even in
\f[CR]\-l/\-\-list\f[R] mode).
.IP \(bu 2
Numbers displayed in a \-\-budget report will not always agree with the
totals, because of hidden unbudgeted accounts; this is normal.
\f[CR]\-E/\-\-empty\f[R] can be used to reveal the hidden accounts.
.IP \(bu 2
In the periodic rules used for setting budget goals, unbalanced postings
are convenient.
.IP \(bu 2
You can filter budget reports with the usual queries, eg to focus on
particular accounts.
It\(aqs common to restrict them to just expenses.
(The \f[CR]<unbudgeted>\f[R] account is occasionally hard to exclude;
this is because of date surprises, discussed below.)
.IP \(bu 2
Only the account, account type, depth, date and commodity parts of the
query are applied to the budget goals; the other parts
(\f[CR]status:\f[R]/\f[CR]\-U\f[R]/\f[CR]\-P\f[R]/\f[CR]\-C\f[R],
\f[CR]code:\f[R], \f[CR]desc:\f[R], \f[CR]payee:\f[R], \f[CR]note:\f[R],
\f[CR]tag:\f[R], \f[CR]real:\f[R], \f[CR]amt:\f[R]) select actual
transactions and postings only.
So eg \f[CR]\-\-budget \-\-cleared\f[R] compares your cleared spending
against the full budget goals.
.IP \(bu 2
When you have multiple currencies, you may want to convert them to one
(\f[CR]\-X COMM \-\-infer\-market\-prices\f[R]) and/or show just one at
a time (\f[CR]cur:COMM\f[R]).
If you do need to show multiple currencies at once,
\f[CR]\-\-layout bare\f[R] can be helpful.
.IP \(bu 2
You can \(dqroll over\(dq amounts (actual and budgeted) to the next
period with \f[CR]\-\-cumulative\f[R].
.PP
See also: https://hledger.org/budgeting.html.
.SS Budget date surprises
With small data, or when starting out, some of the generated budget goal
transaction dates might fall outside the report periods.
Eg with the following journal and report, the first period appears to
have no \f[CR]expenses:food\f[R] budget.
(Also the \f[CR]<unbudgeted>\f[R] account should be excluded by the
\f[CR]expenses\f[R] query, but isn\(aqt.):
.IP
.EX
\(ti monthly in 2020
(expenses:food) $500
2020\-01\-15
expenses:food $400
assets:checking
.EE
.IP
.EX
$ hledger bal \-\-budget expenses
Budget performance in 2020\-01\-15:
|| 2020\-01\-15
===============++====================
<unbudgeted> || $400
expenses:food || 0 [ 0% of $500]
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| $400 [80% of $500]
.EE
.PP
In this case, the budget goal transactions are generated on first days
of of month (this can be seen with
\f[CR]hledger print \-\-forecast tag:generated expenses\f[R]).
Whereas the report period defaults to just the 15th day of january (this
can be seen from the report table\(aqs column headings).
.PP
To fix this kind of thing, be more explicit about the report period
(and/or the periodic rules\(aq dates).
In this case, adding \f[CR]\-b 2020\f[R] does the trick.
.SS Selecting budget goals
By default, the budget report uses all available periodic transaction
rules to generate goals.
This includes rules with a different report interval from your report.
Eg if you have daily, weekly and monthly periodic rules, all of these
will contribute to the goals in a monthly budget report.
.PP
You can select a subset of periodic rules by providing an argument to
the \f[CR]\-\-budget\f[R] flag.
\f[CR]\-\-budget=DESCPAT\f[R] will match all periodic rules whose
description contains DESCPAT, a case\-insensitive substring (not a
regular expression or query).
This means you can give your periodic rules descriptions (remember that
two spaces are needed between period expression and description), and
then select from multiple budgets defined in your journal.
.SS Budgeting vs forecasting
\f[CR]\-\-forecast\f[R] and \f[CR]\-\-budget\f[R] both use the periodic
transaction rules in the journal to generate temporary transactions for
reporting purposes.
However they are separate features \- though you can use both at the
same time if you want.
Here are some differences between them:
.PP
.TS
tab(@);
lw(38.2n) lw(31.8n).
T{
\-\-forecast
T}@T{
\-\-budget
T}
_
T{
is a general option; it enables forecasting with all reports
T}@T{
is a balance command option; it selects the balance report\(aqs budget
mode
T}
T{
generates visible transactions which appear in reports
T}@T{
generates invisible transactions which produce goal amounts
T}
T{
generates forecast transactions from after the last regular transaction,
to the end of the report period; or with an argument
\f[CR]\-\-forecast=PERIODEXPR\f[R] generates them throughout the
specified period, both optionally restricted by periods specified in the
periodic transaction rules
T}@T{
generates budget goal transactions throughout the report period,
optionally restricted by periods specified in the periodic transaction
rules
T}
T{
uses all periodic rules
T}@T{
uses all periodic rules; or with an argument
\f[CR]\-\-budget=DESCPAT\f[R] uses just the rules matched by DESCPAT
T}
.TE
.SS Balance report layout
The \f[CR]\-\-layout\f[R] option affects how \f[CR]balance\f[R] and the
other balance\-like commands show multi\-commodity amounts and commodity
symbols.
It can improve readability, for humans and/or machines (other software).
It has four possible values:
.IP \(bu 2
\f[CR]\-\-layout=wide[,WIDTH]\f[R]: commodities are shown on a single
line, optionally elided to WIDTH
.IP \(bu 2
\f[CR]\-\-layout=tall\f[R]: each commodity is shown on a separate line
.IP \(bu 2
\f[CR]\-\-layout=bare\f[R]: commodity symbols are in their own column,
amounts are bare numbers
.IP \(bu 2
\f[CR]\-\-layout=barewide\f[R]: commodities are shown on a single line,
all in separate columns, amounts are bare numbers
.IP \(bu 2
\f[CR]\-\-layout=tidy\f[R]: data is normalised to easily\-consumed
\(dqtidy\(dq form, with one row per data value.
(This one is currently supported only by the \f[CR]balance\f[R]
command.)
.PP
Here are the \f[CR]\-\-layout\f[R] modes supported by each output format
Only CSV output supports all of them:
.PP
.TS
tab(@);
l l l l l l.
T{
\-
T}@T{
txt
T}@T{
csv
T}@T{
html
T}@T{
json
T}@T{
sql
T}
_
T{
wide
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}
T{
tall
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}
T{
bare
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}
T{
barewide
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}
T{
tidy
T}@T{
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}
.TE
.PP
Choice of layouts for budget reports is more restricted:
.PP
.TS
tab(@);
l l l l l l.
T{
\-
T}@T{
txt
T}@T{
csv
T}@T{
html
T}@T{
json
T}@T{
sql
T}
_
T{
wide
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}
T{
tall
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}@T{
T}
T{
bare
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}
T{
barewide
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}
T{
tidy
T}@T{
T}@T{
T}@T{
T}@T{
T}@T{
T}
.TE
.PP
Examples:
.SS Wide layout
With many commodities, reports can be very wide:
.IP
.EX
$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=wide
Balance changes in 2012\-01\-01..2014\-12\-31:
|| 2012 2013 2014 Total
==================++====================================================================================================================================================================================================================
Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, \-98.12 USD, 10.00 VEA, 18.00 VHT \-11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, \-98.12 USD, 10.00 VEA, 18.00 VHT \-11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT
.EE
.PP
A width limit reduces the width, but some commodities will be hidden:
.IP
.EX
$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=wide,32
Balance changes in 2012\-01\-01..2014\-12\-31:
|| 2012 2013 2014 Total
==================++===========================================================================================================================
Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. \-11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more..
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. \-11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more..
.EE
.SS Tall layout
Each commodity gets a new line (may be different in each column), and
account names are repeated:
.IP
.EX
$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=tall
Balance changes in 2012\-01\-01..2014\-12\-31:
|| 2012 2013 2014 Total
==================++==================================================
Assets:US:ETrade || 10.00 ITOT 70.00 GLD \-11.00 ITOT 70.00 GLD
Assets:US:ETrade || 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT
Assets:US:ETrade || 12.00 VEA \-98.12 USD 14.00 VEA 5120.50 USD
Assets:US:ETrade || 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA
Assets:US:ETrade || 18.00 VHT 294.00 VHT
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 10.00 ITOT 70.00 GLD \-11.00 ITOT 70.00 GLD
|| 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT
|| 12.00 VEA \-98.12 USD 14.00 VEA 5120.50 USD
|| 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA
|| 18.00 VHT 294.00 VHT
.EE
.SS Bare layout
Commodity symbols are kept in one column, each commodity has its own
row, amounts are bare numbers, account names are repeated:
.IP
.EX
$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=bare
Balance changes in 2012\-01\-01..2014\-12\-31:
|| Commodity 2012 2013 2014 Total
==================++=============================================
Assets:US:ETrade || GLD 0 70.00 0 70.00
Assets:US:ETrade || ITOT 10.00 18.00 \-11.00 17.00
Assets:US:ETrade || USD 337.18 \-98.12 4881.44 5120.50
Assets:US:ETrade || VEA 12.00 10.00 14.00 36.00
Assets:US:ETrade || VHT 106.00 18.00 170.00 294.00
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| GLD 0 70.00 0 70.00
|| ITOT 10.00 18.00 \-11.00 17.00
|| USD 337.18 \-98.12 4881.44 5120.50
|| VEA 12.00 10.00 14.00 36.00
|| VHT 106.00 18.00 170.00 294.00
.EE
.PP
Bare layout also affects CSV output, which is useful for producing data
that is easier to consume, eg for making charts:
.IP
.EX
$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-O csv \-\-layout=bare
\(dqaccount\(dq,\(dqcommodity\(dq,\(dqbalance\(dq
\(dqAssets:US:ETrade\(dq,\(dqGLD\(dq,\(dq70.00\(dq
\(dqAssets:US:ETrade\(dq,\(dqITOT\(dq,\(dq17.00\(dq
\(dqAssets:US:ETrade\(dq,\(dqUSD\(dq,\(dq5120.50\(dq
\(dqAssets:US:ETrade\(dq,\(dqVEA\(dq,\(dq36.00\(dq
\(dqAssets:US:ETrade\(dq,\(dqVHT\(dq,\(dq294.00\(dq
\(dqTotal:\(dq,\(dqGLD\(dq,\(dq70.00\(dq
\(dqTotal:\(dq,\(dqITOT\(dq,\(dq17.00\(dq
\(dqTotal:\(dq,\(dqUSD\(dq,\(dq5120.50\(dq
\(dqTotal:\(dq,\(dqVEA\(dq,\(dq36.00\(dq
\(dqTotal:\(dq,\(dqVHT\(dq,\(dq294.00\(dq
.EE
.PP
Bare layout will sometimes display an extra row for the no\-symbol
commodity, because of zero amounts (hledger treats zeroes as
commodity\-less, usually).
This can break \f[CR]hledger\-bar\f[R] confusingly (workaround: add a
\f[CR]cur:\f[R] query to exclude the no\-symbol row).
.SS Barewide layout
Commodity symbols are spread in the table headers, each commodity has
its own column, all column groups share the same set of commodities even
if in one commodity column all values are zero.
For consistency you may think of layout \f[CR]bare\f[R] as
\f[CR]baretall\f[R].
.IP
.EX
$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=barewide
Balance changes in 2012\-01\-01..2014\-12\-31:
|| 2012 (GLD) 2012 (ITOT) 2012 (USD) 2012 (VEA) 2012 (VHT) 2013 (GLD) 2013 (ITOT) 2013 (USD) 2013 (VEA) 2013 (VHT) 2014 (GLD) 2014 (ITOT) 2014 (USD) 2014 (VEA) 2014 (VHT) Total (GLD) Total (ITOT) Total (USD) Total (VEA) Total (VHT)
==================++===================================================================================================================================================================================================================================================================
Assets:US:ETrade || 0 10.00 337.18 12.00 106.00 70.00 18.00 \-98.12 10.00 18.00 0 \-11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 0 10.00 337.18 12.00 106.00 70.00 18.00 \-98.12 10.00 18.00 0 \-11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00
.EE
.PP
Barewide layout is very useful for FODS and CSV output, since you can
easily use LibreOffice\(aqs \f[CR]VLOOKUP\f[R] function for accessing
numbers in a table with mixed commodities.
.SS Tidy layout
This produces normalised \(dqtidy data\(dq (see
https://cran.r\-project.org/web/packages/tidyr/vignettes/tidy\-data.html)
where every variable has its own column and each row represents a single
data point.
This is the easiest kind of data for other software to consume:
.IP
.EX
$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-Y \-O csv \-\-layout=tidy
\(dqaccount\(dq,\(dqperiod\(dq,\(dqstart_date\(dq,\(dqend_date\(dq,\(dqcommodity\(dq,\(dqvalue\(dq
\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqGLD\(dq,\(dq0\(dq
\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqITOT\(dq,\(dq10.00\(dq
\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqUSD\(dq,\(dq337.18\(dq
\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqVEA\(dq,\(dq12.00\(dq
\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqVHT\(dq,\(dq106.00\(dq
\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqGLD\(dq,\(dq70.00\(dq
\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqITOT\(dq,\(dq18.00\(dq
\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqUSD\(dq,\(dq\-98.12\(dq
\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqVEA\(dq,\(dq10.00\(dq
\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqVHT\(dq,\(dq18.00\(dq
\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqGLD\(dq,\(dq0\(dq
\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqITOT\(dq,\(dq\-11.00\(dq
\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqUSD\(dq,\(dq4881.44\(dq
\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqVEA\(dq,\(dq14.00\(dq
\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqVHT\(dq,\(dq170.00\(dq
.EE
.SS Balance report output
As noted in Output format, if you choose HTML output (by using
\f[CR]\-O html\f[R] or \f[CR]\-o somefile.html\f[R]), you can create a
\f[CR]hledger.css\f[R] file in the same directory to customise the
report\(aqs appearance.
.PP
The HTML and FODS output formats can generate hyperlinks to
\f[CR]hledger\-web\f[R] register views: an account name links to the
account\(aqs transactions, a period heading to the period\(aqs
transactions, and, in the default layout, a figure to the transactions
it is made of, in a register whose final balance is that figure (a
historical balance report asks the register for its historical mode).
The two can differ when a transaction\(aqs postings have dates of their
own, since the report counts such a posting in its own period while the
register shows its whole transaction.
Each link says where it leads in its title, which browsers show on
hover.
E.g.
if your \f[CR]hledger\-web\f[R] server is reachable at
\f[CR]http://localhost:5000\f[R] then you might run the
\f[CR]balance\f[R] command with the extra option
\f[CR]\-\-base\-url=http://localhost:5000\f[R].
You can also produce relative links, like
\f[CR]\-\-base\-url=\(dqsome/path\(dq\f[R] or
\f[CR]\-\-base\-url=\(dq\(dq\f[R].)
.SS Balance charts
With \f[CR]\-\-chart\f[R], \f[CR]balance\f[R] shows a chart of the
report instead of a table, choosing a useful kind of chart
automatically.
In the terminal, this is a bar chart drawn with text characters:
.IP
.EX
$ hledger \-f examples/bcexample.journal bal \-M expenses:food \-b 2013 \-e 2013\-04 cur:USD \-\-chart \-w 70
Balance changes in 2013Q1:
█ Expenses:Food:Groceries ▓ Expenses:Food:Restaurant
Jan 396.46 USD █████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
Feb 481.48 USD ████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
Mar 603.32 USD ██████████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
.EE
.IP \(bu 2
A multi\-period report of balance changes is charted as stacked bars per
period, showing the net total as the value (and with \f[CR]net\f[R], see
below, as a line mark, \f[CR]┃\f[R] in text).
.IP \(bu 2
A multi\-period report of end balances (\f[CR]\-\-cumulative\f[R],
\f[CR]\-H\f[R]) is charted the same way in text (and as lines in
graphical charts).
.IP \(bu 2
With \f[CR]\-\-chart=grouped\f[R], the accounts are stacked in a bar for
each account type (assets, liabilities, equity, revenues, expenses, then
any accounts of unknown type), side by side in each period, so that the
types can be compared.
Amounts keep their signs (eg liabilities are usually below zero), and
end balances are drawn as bars too.
In text charts, each period has a row for each type, and one for the
total.
Without a report interval, the whole report period is charted this way,
as one period.
.IP \(bu 2
A single\-period report is charted as one bar per account, with the
total below the chart (as a number only, since it belongs to no
account\(aqs bar, even with \f[CR]net\f[R]).
.PP
Negative amounts grow left from an axis, positive amounts right.
Each account has its own colour (when colour is enabled) and fill
character; fill characters repeat after four accounts.
The legend lists the accounts visible in the chart (an account too small
to fill a character cell is left out).
Accounts are coloured by their account type, with conventional colours:
assets blue, liabilities amber, equity violet, revenues green, expenses
red; several accounts of one type get different shades of its colour (up
to eight; beyond that, shades are shared).
(In terminals which advertise 24\-bit colour support, by setting
\f[CR]COLORTERM=truecolor\f[R], these are the same exact colours as in
SVG charts; otherwise they are the terminal\(aqs basic blue, yellow,
magenta, green and red, whose shades depend on its colour theme.)
Accounts of unknown type get distinct colours instead.
But when it shows just one account (in each panel), there is nothing to
tell apart, so the account has its type\(aqs colour, or if its type is
unknown, cyan, a colour no account type uses.
A chart showing just a total (eg with \f[CR]\-0\f[R], or of all
accounts\(aq transaction counts) is also cyan.
Colours and fill characters are chosen by account name, not by position,
so an account usually keeps its colour in other charts: with or without
\f[CR]\-S\f[R], or when you exclude other accounts to see more detail.
(Not always, since there are only a few colours: an account may get a
different one when some accounts are added or removed.)
The chart fills the terminal width, or the width set by
\f[CR]\-w\f[R]/\f[CR]\-\-width\f[R] (except for posting counts, with
\f[CR]\-\-count\f[R], which use at most one character per posting).
It is drawn with unicode block characters, or with ASCII characters if
the system\(aqs text encoding is not UTF\-8.
.PP
There is one chart panel per commodity.
You can reduce this by converting to one commodity (eg
\f[CR]\-X USD\f[R]) or selecting some (eg \f[CR]cur:USD\f[R]); hledger
suggests this when there are more than 8 panels.
In tree mode, each account\(aqs own amounts are stacked, excluding its
subaccounts\(aq, so that nothing is counted twice.
At most 8 accounts are shown per panel; the smallest are combined into
\(dqother\(dq series, one for each account type (so eg assets and
liabilities are never combined), and each type keeps at least its
largest account.
\(dqother\(dq series are grey, or when coloured by type, a greyed
version of their type\(aqs colour.
The total is omitted with \f[CR]\-N\f[R] or \f[CR]\-\-percent\f[R].
Charts draw it (as a line or marks) only with \f[CR]net\f[R], eg
\f[CR]\-\-chart=net\f[R] (or \f[CR]\-\-chart=grouped,net\f[R]).
\f[CR]net\f[R] draws the total where a bar combines several amounts; a
chart of one account, or with one bar per account, does not draw it.
(Text charts show it as a number either way.)
.PP
In a chart of balance changes per period,
\f[CR]\-T\f[R]/\f[CR]\-\-row\-total\f[R] and
\f[CR]\-A\f[R]/\f[CR]\-\-average\f[R] show the net total\(aqs total and
average per period on a line below the chart, eg
\f[CR]Total 11, Average 0.9\f[R]; and in graphical charts, the average
is also drawn as a dashed line across the chart, with an entry in the
legend.
In a chart of end balances (eg with \f[CR]\-H\f[R], or \f[CR]bs\f[R]),
\f[CR]\-A\f[R] shows the average of the net total\(aqs period\-end
balances in the same way (there is no total).
.PP
Each chart is scaled to fit its values.
To draw charts at a fixed scale instead, so that you can compare them
(eg this month\(aqs chart with last month\(aqs), add a SCALE amount:
\f[CR]\-\-chart=SCALE\f[R].
This is the amount that the chart spans; eg with
\f[CR]\-\-chart=5000\f[R], a bar of 5000 fills the chart.
If the chart also has negative values, they take the room they need and
positive values get the rest.
Bars that don\(aqt fit are clipped, with a mark at the edge
(\f[CR]▸\f[R] or \f[CR]◂\f[R] in text, a small triangle in SVG); lines
go off the edge.
A SCALE with a commodity symbol (eg
\f[CR]\-\-chart=\(aq5000 USD\(aq\f[R]) applies to that commodity\(aqs
panel, and one without, to the others.
SCALE can follow KIND and \f[CR]net\f[R], and several SCALEs can be
given, separated by commas (eg
\f[CR]\-\-chart=\(aqauto,5000 USD,4000 EUR\(aq\f[R]); so a SCALE
can\(aqt contain a comma: write it without digit group marks, or with
spaces or periods (eg \f[CR]10 000 EUR\f[R]).
A number like \f[CR]10.000\f[R] is read using that commodity\(aqs
decimal mark, as it is shown in the report: eg in a journal where EUR is
written with a decimal comma, \f[CR]10.000 EUR\f[R] is ten thousand.
For the same scale in text charts, use the same width too
(\f[CR]\-w\f[R]).
.PP
With SVG output (\f[CR]\-o FILE.svg\f[R] or \f[CR]\-O svg\f[R]),
\f[CR]balance\f[R] always shows a chart, as a graphical image.
Time runs along the x axis, and end balances are drawn as lines.
A single\-period report is drawn as vertical bars, one per account, with
the account names below (angled if needed) and values above the bars
(where they fit); or with more than 30 accounts, as horizontal bars.
The y axis shows the unit only on its top (or bottom) label.
In an HTML page, the chart shrinks to fit a narrower window.
.PP
With HTML output, \f[CR]\-\-chart\f[R] shows the chart (as SVG), with
the report\(aqs table collapsed below it (click Report details to show
it).
.PP
With \f[CR]\-O csv\f[R], \f[CR]\-O tsv\f[R] or \f[CR]\-O json\f[R],
\f[CR]\-\-chart\f[R] shows the chart\(aqs data, eg to inspect it or
chart it with other tools.
.PP
The compound balance commands (\f[CR]balancesheet\f[R],
\f[CR]balancesheetequity\f[R], \f[CR]cashflow\f[R],
\f[CR]incomestatement\f[R]) can show charts in the same ways.
They chart their sections\(aq accounts, with the net total (as a number
in text charts, and with \f[CR]net\f[R], as a mark in text charts or a
line in SVG charts), in one of two layouts:
.IP \(bu 2
\f[B]diverging\f[R] (the default, or with
\f[CR]\-\-chart=diverging\f[R]): at each period, all accounts are
stacked in one bar, showing each amount as its contribution to the net
total: sections that add to it (eg assets, revenues) above zero, and
sections that subtract from it (eg liabilities, expenses) below zero.
(This is also why an \f[CR]is\f[R] chart draws expenses below zero while
\f[CR]bal\f[R] draws them above, as their raw amounts are positive;
\f[CR]bal \-\-invert\f[R] gives the same signs.)
In text charts, each period is a row showing the net total, the totals
of the sections on each side at the ends of the bar (as the report\(aqs
table shows them; headed by the sections\(aq names), and with
\f[CR]net\f[R], a mark at the net total\(aqs position.
.IP \(bu 2
\f[B]grouped\f[R] (with \f[CR]\-\-chart=grouped\f[R]): at each period,
each section\(aqs accounts are stacked in a bar of their own, side by
side, so that the sections\(aq sizes can be compared.
Amounts are shown as the tables show them, eg expenses as well as
revenues are positive.
In text charts, each period has a row for each section, showing its
total, and a row showing the net total (and with \f[CR]net\f[R], marking
it).
.PP
Contra amounts \- those with the opposite sign to their section\(aqs
usual sign, like a refund recorded as a negative expense, or a contra
account like accumulated depreciation \- are drawn next to the zero
line, hatched in their account\(aqs colour (below zero in the grouped
layout, and on the other side from their section in the diverging
layout).
They are included in their section\(aqs totals.
(Cash flows, in \f[CR]cf\f[R], have no usual sign: decreases are drawn
like increases, below zero.)
Each section shows at most five accounts, combining the smallest into
\(dqother\(dq; use a depth limit (eg \f[CR]\-1\f[R] or \f[CR]\-2\f[R])
for less detail.
A single\-period report is charted the same way, with one period.
The chart data has one record per value, with fields: commodity, series
(usually an account name), role (\f[CR]item\f[R], \f[CR]other\f[R] or
\f[CR]total\f[R]), mark (\f[CR]bar\f[R], \f[CR]line\f[R] or
\f[CR]marker\f[R]), x (a period heading, period end date, or account
name), and value.
With \f[CR]\-T\f[R] or \f[CR]\-A\f[R], each commodity\(aqs total or
average follows, with role \f[CR]rowtotal\f[R] or \f[CR]average\f[R],
and an empty mark and x.
Eg:
.IP
.EX
$ hledger \-f examples/sample.journal bal \-M expenses \-N \-\-chart \-O csv
\(dqcommodity\(dq,\(dqseries\(dq,\(dqrole\(dq,\(dqmark\(dq,\(dqx\(dq,\(dqvalue\(dq
\(dq$\(dq,\(dqexpenses:food\(dq,\(dqitem\(dq,\(dqbar\(dq,\(dqJan\(dq,\(dq0\(dq
\(dq$\(dq,\(dqexpenses:food\(dq,\(dqitem\(dq,\(dqbar\(dq,\(dqFeb\(dq,\(dq0\(dq
\&...
.EE
.SS Some useful balance reports
Some frequently used \f[CR]balance\f[R] options/reports are:
.IP \(bu 2
\f[CR]bal \-M revenues expenses\f[R]
.PD 0
.P
.PD
Show revenues/expenses in each month.
Also available as the \f[CR]incomestatement\f[R] command.
.IP \(bu 2
\f[CR]bal \-M \-H assets liabilities\f[R]
.PD 0
.P
.PD
Show historical asset/liability balances at each month end.
Also available as the \f[CR]balancesheet\f[R] command.
.IP \(bu 2
\f[CR]bal \-M \-H assets liabilities equity\f[R]
.PD 0
.P
.PD
Show historical asset/liability/equity balances at each month end.
Also available as the \f[CR]balancesheetequity\f[R] command.
.IP \(bu 2
\f[CR]bal \-M assets not:receivable\f[R]
.PD 0
.P
.PD
Show changes to liquid assets in each month.
Also available as the \f[CR]cashflow\f[R] command.
.PP
Also:
.IP \(bu 2
\f[CR]bal \-M expenses \-2 \-SA\f[R]
.PD 0
.P
.PD
Show monthly expenses summarised to depth 2 and sorted by average
amount.
.IP \(bu 2
\f[CR]bal \-M \-\-budget expenses\f[R]
.PD 0
.P
.PD
Show monthly expenses and budget goals.
.IP \(bu 2
\f[CR]bal \-M \-\-valuechange investments\f[R]
.PD 0
.P
.PD
Show monthly change in market value of investment assets.
.IP \(bu 2
\f[CR]bal \-M \-H \-\-gain investments\f[R]
.PD 0
.P
.PD
Show unrealised gain on investment assets (market value minus cost) at
each month end.
.IP \(bu 2
\f[CR]bal investments \-\-valuechange \-D date:lastweek amt:\(aq>1000\(aq \-STA [\-\-invert]\f[R]
.PD 0
.P
.PD
Show top gainers [or losers] last week
.SS balancesheet
(bs)
.PP
Show the end balances in asset and liability accounts.
Amounts are shown with normal positive sign, as in conventional
financial statements.
.IP
.EX
Flags:
\-\-sum calculation mode: show sum of posting amounts
(default)
\-\-valuechange calculation mode: show total change of value
of period\-end historical balances (caused by
deposits, withdrawals, market price
fluctuations)
\-\-gain calculation mode: show unrealised capital
gain/loss (historical balance value minus cost
basis)
\-\-count calculation mode: show the count of postings
\-\-change accumulation mode: accumulate amounts from
column start to column end (in multicolumn
reports)
\-\-cumulative accumulation mode: accumulate amounts from
report start (specified by e.g. \-b/\-\-begin) to
column end
\-H \-\-historical accumulation mode: accumulate amounts from
journal start to column end (includes postings
before report start date) (default)
\-l \-\-flat list/tree mode: show accounts as a flat list
(default). Amounts exclude subaccount amounts,
except where the account is depth\-clipped.
\-t \-\-tree list/tree mode: show accounts as a tree.
Amounts include subaccount amounts.
\-\-drop=N in list mode, omit N leading account name
parts
\-\-declared include non\-parent declared accounts (best
used with \-E)
\-A \-\-average show a row average column (in multicolumn
reports)
\-T \-\-row\-total show a row total column (in multicolumn
reports)
\-\-summary\-only display only row summaries (e.g. row total,
average) (in multicolumn reports)
\-N \-\-no\-total omit the final total row
\-\-no\-elide in tree mode, don\(aqt squash boring parent
accounts; in list mode, also show parent
accounts (usually zero, hidden without \-E)
\-\-full\-names in tree mode, show full account names instead
of indented leaf names
\-\-format=FORMATSTR use this custom line format (in simple
reports)
\-S \-\-sort\-amount sort by amount instead of account code/name
\-% \-\-percent express values in percentage of each column\(aqs
total
\-\-layout=ARG how to show multi\-commodity amounts:
\(aqwide[,WIDTH]\(aq: all commodities on one line
\(aqtall\(aq : each commodity on a new line
\(aqbare\(aq : bare numbers, symbols in a
column
\-\-base\-url=URLPREFIX in html output, generate hyperlinks to
hledger\-web, with this prefix. (Usually the base
url shown by hledger\-web; can also be relative.)
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, html, csv, tsv, json, svg.
\-o \-\-output\-file=FILE write output to FILE. A file extension
matching one of the above formats selects that
format.
\-\-view write output to FILE, or to view.FMT in
hledger\(aqs cache directory, and open it in the
system\(aqs default viewer for its format (eg a web
browser for html). The default format is html.
\-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),
above it (html), or as data (csv, tsv, json).
KIND: diverging (sections above and below zero;
the default) or grouped (sections side by side).
net: also draw the net total (a line, or marks
in text charts). SCALE: the amount that fills
the chart (eg 1000 or 1000 USD; one per
commodity), for comparable charts.
\-w \-\-width=N with \-\-chart: draw the chart N characters wide
(default: the terminal width)
.EE
.PP
This command displays a balance sheet, showing historical ending
balances of asset and liability accounts.
(To see equity as well, use the balancesheetequity command.)
.PP
Accounts declared with the \f[CR]Asset\f[R], \f[CR]Cash\f[R] or
\f[CR]Liability\f[R] type are shown (see account types).
Or if no such accounts are declared, it shows top\-level accounts named
\f[CR]asset\f[R] or \f[CR]liability\f[R] (case insensitive, plurals
allowed) and their subaccounts.
.PP
Example:
.IP
.EX
$ hledger balancesheet
Balance Sheet 2008\-12\-31
|| 2008\-12\-31
====================++============
Assets ||
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
assets:bank:saving || $1
assets:cash || $\-2
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
|| $\-1
====================++============
Liabilities ||
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
liabilities:debts || $\-1
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
|| $\-1
====================++============
Net: || 0
.EE
.PP
This command is a higher\-level variant of the \f[CR]balance\f[R]
command, and supports many of that command\(aqs features, such as
multi\-period reports.
It is similar to \f[CR]hledger balance \-H assets liabilities\f[R], but
with smarter account detection, and liabilities displayed with their
sign flipped.
.PP
This command also supports the output destination and output format
options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],
\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]json\f[R], and \f[CR]svg\f[R] (a
chart; see Balance charts).
.SS balancesheetequity
(bse)
.PP
Show a balance sheet, with historical ending balances of asset,
liability and equity accounts.
Amounts are shown with normal positive sign, as in conventional
financial statements.
.IP
.EX
Flags:
\-\-sum calculation mode: show sum of posting amounts
(default)
\-\-valuechange calculation mode: show total change of value
of period\-end historical balances (caused by
deposits, withdrawals, market price
fluctuations)
\-\-gain calculation mode: show unrealised capital
gain/loss (historical balance value minus cost
basis)
\-\-count calculation mode: show the count of postings
\-\-change accumulation mode: accumulate amounts from
column start to column end (in multicolumn
reports)
\-\-cumulative accumulation mode: accumulate amounts from
report start (specified by e.g. \-b/\-\-begin) to
column end
\-H \-\-historical accumulation mode: accumulate amounts from
journal start to column end (includes postings
before report start date) (default)
\-l \-\-flat list/tree mode: show accounts as a flat list
(default). Amounts exclude subaccount amounts,
except where the account is depth\-clipped.
\-t \-\-tree list/tree mode: show accounts as a tree.
Amounts include subaccount amounts.
\-\-drop=N in list mode, omit N leading account name
parts
\-\-declared include non\-parent declared accounts (best
used with \-E)
\-A \-\-average show a row average column (in multicolumn
reports)
\-T \-\-row\-total show a row total column (in multicolumn
reports)
\-\-summary\-only display only row summaries (e.g. row total,
average) (in multicolumn reports)
\-N \-\-no\-total omit the final total row
\-\-no\-elide in tree mode, don\(aqt squash boring parent
accounts; in list mode, also show parent
accounts (usually zero, hidden without \-E)
\-\-full\-names in tree mode, show full account names instead
of indented leaf names
\-\-format=FORMATSTR use this custom line format (in simple
reports)
\-S \-\-sort\-amount sort by amount instead of account code/name
\-% \-\-percent express values in percentage of each column\(aqs
total
\-\-layout=ARG how to show multi\-commodity amounts:
\(aqwide[,WIDTH]\(aq: all commodities on one line
\(aqtall\(aq : each commodity on a new line
\(aqbare\(aq : bare numbers, symbols in a
column
\-\-base\-url=URLPREFIX in html output, generate hyperlinks to
hledger\-web, with this prefix. (Usually the base
url shown by hledger\-web; can also be relative.)
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, html, csv, tsv, json, svg.
\-o \-\-output\-file=FILE write output to FILE. A file extension
matching one of the above formats selects that
format.
\-\-view write output to FILE, or to view.FMT in
hledger\(aqs cache directory, and open it in the
system\(aqs default viewer for its format (eg a web
browser for html). The default format is html.
\-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),
above it (html), or as data (csv, tsv, json).
KIND: diverging (sections above and below zero;
the default) or grouped (sections side by side).
net: also draw the net total (a line, or marks
in text charts). SCALE: the amount that fills
the chart (eg 1000 or 1000 USD; one per
commodity), for comparable charts.
\-w \-\-width=N with \-\-chart: draw the chart N characters wide
(default: the terminal width)
.EE
.PP
This report shows accounts declared with the \f[CR]Asset\f[R],
\f[CR]Cash\f[R], \f[CR]Liability\f[R] or \f[CR]Equity\f[R] type (see
account types).
Or if no such accounts are declared, it shows top\-level accounts named
\f[CR]asset\f[R], \f[CR]liability\f[R] or \f[CR]equity\f[R] (case
insensitive, plurals allowed) and their subaccounts.
.PP
Example:
.IP
.EX
$ hledger balancesheetequity
Balance Sheet With Equity 2008\-12\-31
|| 2008\-12\-31
====================++============
Assets ||
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
assets:bank:saving || $1
assets:cash || $\-2
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
|| $\-1
====================++============
Liabilities ||
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
liabilities:debts || $\-1
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
|| $\-1
====================++============
Equity ||
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-
|| 0
====================++============
Net: || 0
.EE
.PP
This command is a higher\-level variant of the \f[CR]balance\f[R]
command, and supports many of that command\(aqs features, such as
multi\-period reports.
It is similar to
\f[CR]hledger balance \-H assets liabilities equity\f[R], but with
smarter account detection, and liabilities/equity displayed with their
sign flipped.
.PP
This report is the easiest way to see if the accounting equation (A+L+E
= 0) is satisfied (after you have done a \f[CR]close \-\-retain\f[R] to
merge revenues and expenses with equity, and perhaps added
\f[CR]\-\-infer\-equity\f[R] to balance your commodity conversions).
.PP
This command also supports the output destination and output format
options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],
\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]json\f[R], and \f[CR]svg\f[R] (a
chart; see Balance charts).
.SS cashflow
(cf)
.PP
Show a (simple) cashflow statement, with the inflows and outflows
affecting \(dqcash\(dq (ie, liquid, easily convertible) assets.
Amounts are shown with normal positive sign, as in conventional
financial statements.
.IP
.EX
Flags:
\-\-sum calculation mode: show sum of posting amounts
(default)
\-\-valuechange calculation mode: show total change of value
of period\-end historical balances (caused by
deposits, withdrawals, market price
fluctuations)
\-\-gain calculation mode: show unrealised capital
gain/loss (historical balance value minus cost
basis)
\-\-count calculation mode: show the count of postings
\-\-change accumulation mode: accumulate amounts from
column start to column end (in multicolumn
reports) (default)
\-\-cumulative accumulation mode: accumulate amounts from
report start (specified by e.g. \-b/\-\-begin) to
column end
\-H \-\-historical accumulation mode: accumulate amounts from
journal start to column end (includes postings
before report start date)
\-l \-\-flat list/tree mode: show accounts as a flat list
(default). Amounts exclude subaccount amounts,
except where the account is depth\-clipped.
\-t \-\-tree list/tree mode: show accounts as a tree.
Amounts include subaccount amounts.
\-\-drop=N in list mode, omit N leading account name
parts
\-\-declared include non\-parent declared accounts (best
used with \-E)
\-A \-\-average show a row average column (in multicolumn
reports)
\-T \-\-row\-total show a row total column (in multicolumn
reports)
\-\-summary\-only display only row summaries (e.g. row total,
average) (in multicolumn reports)
\-N \-\-no\-total omit the final total row
\-\-no\-elide in tree mode, don\(aqt squash boring parent
accounts; in list mode, also show parent
accounts (usually zero, hidden without \-E)
\-\-full\-names in tree mode, show full account names instead
of indented leaf names
\-\-format=FORMATSTR use this custom line format (in simple
reports)
\-S \-\-sort\-amount sort by amount instead of account code/name
\-% \-\-percent express values in percentage of each column\(aqs
total
\-\-layout=ARG how to show multi\-commodity amounts:
\(aqwide[,WIDTH]\(aq: all commodities on one line
\(aqtall\(aq : each commodity on a new line
\(aqbare\(aq : bare numbers, symbols in a
column
\-\-base\-url=URLPREFIX in html output, generate hyperlinks to
hledger\-web, with this prefix. (Usually the base
url shown by hledger\-web; can also be relative.)
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, html, csv, tsv, json, svg.
\-o \-\-output\-file=FILE write output to FILE. A file extension
matching one of the above formats selects that
format.
\-\-view write output to FILE, or to view.FMT in
hledger\(aqs cache directory, and open it in the
system\(aqs default viewer for its format (eg a web
browser for html). The default format is html.
\-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),
above it (html), or as data (csv, tsv, json).
KIND: diverging (sections above and below zero;
the default) or grouped (sections side by side).
net: also draw the net total (a line, or marks
in text charts). SCALE: the amount that fills
the chart (eg 1000 or 1000 USD; one per
commodity), for comparable charts.
\-w \-\-width=N with \-\-chart: draw the chart N characters wide
(default: the terminal width)
.EE
.PP
This report shows accounts declared with the \f[CR]Cash\f[R] type (see
account types).
Or if no such accounts are declared, it shows accounts
.IP \(bu 2
under a top\-level account named \f[CR]asset\f[R] (case insensitive,
plural allowed)
.IP \(bu 2
whose name contains some variation of \f[CR]cash\f[R], \f[CR]bank\f[R],
\f[CR]checking\f[R] or \f[CR]saving\f[R].
.PP
More precisely: all accounts matching this case insensitive regular
expression:
.PP
\f[CR]\(haassets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|currentcash)(:|$)\f[R]
.PP
and their subaccounts.
.PP
An example cashflow report:
.IP
.EX
$ hledger cashflow
Cashflow Statement 2008
|| 2008
====================++======
Cash flows ||
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-
assets:bank:saving || $1
assets:cash || $\-2
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-
|| $\-1
.EE
.PP
This command is a higher\-level variant of the \f[CR]balance\f[R]
command, and supports many of that command\(aqs features, such as
multi\-period reports.
It is similar to
\f[CR]hledger balance assets not:fixed not:investment not:receivable\f[R],
but with smarter account detection.
.PP
This command also supports the output destination and output format
options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],
\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]json\f[R], and \f[CR]svg\f[R] (a
chart; see Balance charts).
.SS codes
List the codes seen in transactions, in the order parsed.
.IP
.EX
Flags:
no command\-specific flags
.EE
.PP
This command prints the value of each transaction\(aqs code field, in
the order transactions were parsed.
The transaction code is an optional value written in parentheses between
the date and description, often used to store a cheque number, order
number or similar.
.PP
Transactions aren\(aqt required to have a code, and missing or empty
codes will not be shown by default.
With the \f[CR]\-E\f[R]/\f[CR]\-\-empty\f[R] flag, they will be printed
as blank lines.
.PP
You can add a query to select a subset of transactions.
.PP
Examples:
.IP
.EX
2022/1/1 (123) Supermarket
Food $5.00
Checking
2022/1/2 (124) Post Office
Postage $8.32
Checking
2022/1/3 Supermarket
Food $11.23
Checking
2022/1/4 (126) Post Office
Postage $3.21
Checking
.EE
.IP
.EX
$ hledger codes
123
124
126
.EE
.IP
.EX
$ hledger codes \-E
123
124
126
.EE
.SS commodities
(comm)
.PP
List the commodity symbols used or declared in the journal.
.IP
.EX
Flags:
\-\-used list commodities used in transactions
\-\-priced list commodities appearing in P directives
\-\-declared list commodities declared by commodity directives
\-\-undeclared list commodities used or priced but not declared
\-\-unused list commodities declared but not used or priced
\-\-find list the first commodity matched by the first
argument (a case\-insensitive infix regexp)
\-\-directives show as commodity directives (with their display
styles), for use in journals
.EE
.PP
Most of these flags can be combined.
With \f[CR]\-\-directives\f[R], it shows valid commodity directives,
declaring each commodity\(aqs (declared or inferred) display style,
which could be pasted into a journal file.
Some kinds of query argument are supported: \f[CR]cur:\f[R],
\f[CR]tag:\f[R], and \f[CR]date:\f[R] (also
\f[CR]\-b\f[R]/\f[CR]\-e\f[R]/\f[CR]\-p\f[R] report period options).
.PP
Providing a date query will affect which commodities are reported, as
follows:
.PP
.TS
tab(@);
lw(10.5n) lw(28.1n) lw(31.4n).
T{
Flag
T}@T{
No date query
T}@T{
With a date query
T}
_
T{
(none)
T}@T{
declared ∪ transacted ∪ priced
T}@T{
(transacted ∪ priced) in the period
T}
T{
\f[CR]\-\-used\f[R]
T}@T{
transacted in the journal
T}@T{
transacted in the period
T}
T{
\f[CR]\-\-priced\f[R]
T}@T{
appearing in any P directive
T}@T{
appearing in a P directive in the period
T}
T{
\f[CR]\-\-declared\f[R]
T}@T{
declared with a \f[CR]commodity\f[R] directive
T}@T{
same
T}
T{
\f[CR]\-\-undeclared\f[R]
T}@T{
(transacted ∪ priced) ∖ declared
T}@T{
(transacted ∪ priced in the period) ∖ declared
T}
T{
\f[CR]\-\-unused\f[R]
T}@T{
declared ∖ (transacted ∪ priced)
T}@T{
same
T}
T{
\f[CR]\-\-find\f[R]
T}@T{
the first commodity matching the argument
T}@T{
same
T}
.TE
.PP
Example:
.IP
.EX
$ hledger commodities
$
AAPL
EUR
.EE
.SS descriptions
(desc)
.PP
List the unique descriptions used in transactions.
.IP
.EX
Flags:
no command\-specific flags
.EE
.PP
This command lists the unique descriptions that appear in transactions,
in alphabetic order.
You can add a query to select a subset of transactions.
.PP
Example:
.IP
.EX
$ hledger descriptions
Store Name
Gas Station | Petrol
Person A
.EE
.SS files
List all input files used by the journal(s), in the order they were
read.
This includes the files used to read CSV data: each CSV file is followed
by its rules file and any rules files that includes, and each rules file
is followed by any rules files it includes and the data file it read (if
any).
With a REGEX argument, only file names matching the regular expression
(case sensitive) are shown.
.PP
To find the files, hledger reads them only as far as needed, without
processing their data.
So this command works even when the journal has errors, such as
unbalanced entries or failing balance assertions (but not syntax
errors), and it does not run \f[CR]source\f[R] commands.
If an included file does not exist (or an include\(aqs glob pattern
matches no files), it is omitted from the list, with a warning; this is
not an error.
(This helps tools which generate included files, and need to find them
before they exist.)
If a rules file\(aqs \f[CR]source\f[R] pattern matches several files,
only the one it would read is shown.
.PP
With \f[CR]\-t/\-\-tree\f[R], the files are shown as a tree: each
included file is indented below the file that includes it, and shown
with its path relative to that file\(aqs directory (for a file included
by name, the path as written in the include directive).
The files used to read a CSV or rules file are shown one level below it,
in the same way.
A file included more than once appears at each place it is included.
With a REGEX argument (which is matched against full paths), the files
including a matched file are also shown.
.IP
.EX
Flags:
\-l \-\-flat list/tree mode: show files as a flat list
(default)
\-t \-\-tree list/tree mode: show files as a tree, indenting
included files below the file that includes them
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, json.
\-o \-\-output\-file=FILE write output to FILE. A file extension matching
one of the above formats selects that format.
.EE
.PP
With \f[CR]\-O json\f[R], the files are listed as JSON, for use by other
tools.
Each file is an object with these fields: \f[CR]path\f[R] (the file\(aqs
path, or \f[CR]\-\f[R] for standard input), \f[CR]depth\f[R] (0 for a
main file, 1 for a file it includes or uses, and so on),
\f[CR]parent\f[R] (the path of the file that included or used this one,
or null for a main file), and \f[CR]exists\f[R] (false for a missing
included file, or an include\(aqs glob pattern which matched nothing).
\f[CR]\-\-tree\f[R] does not affect JSON output, and a REGEX argument
selects just the matching files.
.PP
Examples:
.IP
.EX
$ hledger \-f main.journal files
/home/user/finance/main.journal
/home/user/finance/2024.journal
.EE
.IP
.EX
$ hledger \-f main.journal files 2024
/home/user/finance/2024.journal
.EE
.IP
.EX
$ hledger \-f main.journal files \-\-tree
/home/user/finance/main.journal
2024.journal
2025.journal
prices/2025.prices
checking.rules
common.rules
data/checking.csv
.EE
.IP
.EX
$ hledger \-f main.journal files \-O json checking
[
{
\(dqdepth\(dq: 1,
\(dqexists\(dq: true,
\(dqparent\(dq: \(dq/home/user/finance/main.journal\(dq,
\(dqpath\(dq: \(dq/home/user/finance/checking.rules\(dq
},
{
\(dqdepth\(dq: 2,
\(dqexists\(dq: true,
\(dqparent\(dq: \(dq/home/user/finance/checking.rules\(dq,
\(dqpath\(dq: \(dq/home/user/finance/data/checking.csv\(dq
}
]
.EE
.SS holdings
Show a report of investment holdings.
.IP
.EX
Flags:
\-l \-\-flat list/tree mode: show accounts as a flat list
(default). Amounts exclude subaccount amounts,
except where the account is depth\-clipped.
\-t \-\-tree list/tree mode: show accounts as a tree. Amounts
include subaccount amounts.
\-\-no\-elide in tree mode, don\(aqt squash boring parent
accounts; in list mode, also show parent accounts
(usually zero, hidden without \-E)
\-\-full\-names in tree mode, show full account names instead of
indented leaf names
\-\-drop=N omit N leading account name parts; in tree mode,
remove the first N levels
\-S \-\-sort\-amount sort by value (or with \-B, cost) instead of
account name, largest first
\-N \-\-no\-total omit the final total row
\-\-change show gains during the report period, or with a
report interval, during each period (default with a
start date and no interval)
\-\-cumulative with a report interval, show gains from the
report start date to each period\(aqs end
\-H \-\-historical show gains since acquisition, ignoring the report
start date (default with a report interval)
\-\-round=TYPE 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
\-\-chart[=net,SCALE] show a chart: instead of the table (txt), above
it (html), or as data (csv, tsv, json). net: also
draw the net total (a line, or marks in text
charts). SCALE: the amount that fills the chart (eg
1000 or 1000 USD; one per commodity), for
comparable charts.
\-w \-\-width=N with \-\-chart: draw the chart N characters wide
(default: the terminal width)
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, csv, tsv, html, fods, json, svg.
\-o \-\-output\-file=FILE write output to FILE. A file extension matching
one of the above formats selects that format.
\-\-view write output to FILE, or to view.FMT in hledger\(aqs
cache directory, and open it in the system\(aqs
default viewer for its format (eg a web browser for
html). The default format is html.
.EE
.PP
This command shows your lot\-tracked assets (see Lots and capital
gains), and their performance, as of the report end date.
An example:
.IP
.EX
$ hledger holdings \-e 2023\-04\-02
Holdings on 2023\-04\-01
|| Date Age Units Avg cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR
===========================++===========================================================================================================================
assets:investments:stocks || 2022\-04\-07 359d 10 INFY 2.00 ₹ 100.00 ₹ 20.00 ₹ 1,000.00 ₹ 6.4% 980.00 ₹ 4900.0% 5252.4%
assets:investments:stocks || 73 LTTS 4.79 ₹ 200.00 ₹ 350.00 ₹ 14,600.00 ₹ 93.6% 14,250.00 ₹ 4071.4% 140.00 ₹ 4290.2%
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 370.00 ₹ 15,600.00 ₹ 100.0% 15,230.00 ₹ 4116.2% 140.00 ₹ 4342.1%
.EE
.PP
With \f[CR]\-\-lots\f[R], the individual lots are shown:
.IP
.EX
$ hledger holdings \-\-lots \-e 2023\-04\-02
Holdings on 2023\-04\-01
|| Date Age Units Unit cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR
=========================================================++============================================================================================================================
assets:investments:stocks:{2022\-04\-06, \(dq0002\(dq, 10.00 ₹} || 2022\-04\-06 360d 13 LTTS 10.00 ₹ 200.00 ₹ 130.00 ₹ 2,600.00 ₹ 16.7% 2,470.00 ₹ 1900.0% 140.00 ₹ 3876.1%
assets:investments:stocks:{2022\-04\-07, 2.00 ₹} || 2022\-04\-07 359d 10 INFY 2.00 ₹ 100.00 ₹ 20.00 ₹ 1,000.00 ₹ 6.4% 980.00 ₹ 4900.0% 5252.4%
assets:investments:stocks:{2022\-05\-06, \(dq0002\(dq, 11.00 ₹} || 2022\-05\-06 330d 20 LTTS 11.00 ₹ 200.00 ₹ 220.00 ₹ 4,000.00 ₹ 25.6% 3,780.00 ₹ 1718.2% 5032.7%
assets:investments:stocks:{2022\-06\-06, \(dq0002\(dq, 0.00 ₹} || 2022\-06\-06 299d 40 LTTS 0 200.00 ₹ 0 8,000.00 ₹ 51.3% 8,000.00 ₹
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 370.00 ₹ 15,600.00 ₹ 100.0% 15,230.00 ₹ 4116.2% 140.00 ₹ 4342.1%
.EE
.PP
The columns show:
.IP \(bu 2
each holding\(aqs acquisition date (or earlier basis date) and age
.IP \(bu 2
the number of units held
.IP \(bu 2
the unit cost basis (Unit cost; or Avg cost, the average unit cost of
several lots, or for accounts using the AVERAGE method, the pool\(aqs
running average on the report date)
.IP \(bu 2
the unit market price on the report date (Unit price)
.IP \(bu 2
the total cost basis (Total cost)
.IP \(bu 2
the total market value (Total value)
.IP \(bu 2
the percentage of the portfolio\(aqs total value (Weight).
A holding with no market price has no Weight and isn\(aqt counted in
that total, so the others\(aq weights are a little overstated.
No weights are shown if the holdings are valued in more than one
commodity.
.IP \(bu 2
the unrealised gain and gain percent (UGain, UGain%)
.IP \(bu 2
the realised gain from disposals so far (RGain)
.IP \(bu 2
and the annualised rate of return, as of the report end date (XIRR,
calculated from the holding\(aqs dated cashflows and current value, like
roi\(aqs IRR; it includes realised gains).
Lots received without a transacted cost (eg transferred from another
account) count as invested at their cost basis on their acquisition
date.
.PP
Fully disposed commodities and accounts (\(dqclosed positions\(dq) are
not shown, unless you add \f[CR]\-E/\-\-empty\f[R].
But the totals row\(aqs RGain and XIRR always include them, so those
columns may not add up to their totals; a note below the table then says
how many closed positions are not shown.
.PP
To see a commodity\(aqs performance, a market price should be declared
for it (as of the report end date).
Market prices come from P directives or (with
\f[CR]\-\-infer\-market\-prices\f[R]) from transacted prices, as usual.
Each lot is valued in its cost commodity.
A holding with no market price has no value or gains; the totals\(aq
Total value, UGain, UGain% and XIRR are then those of the other
holdings, and a note below the table names the excluded ones.
(With a report interval, the periods whose totals exclude some are
starred; and a period\(aqs gains exclude the holdings with no market
price at either its start or its end, so that they compare the same
holdings.)
In a multi\-currency portfolio, aggregated values may contain multiple
currencies; use \f[CR]\-X COMM\f[R] for a single\-currency view.
.PP
With \f[CR]\-V\f[R], \f[CR]\-X COMM\f[R] or \f[CR]\-\-value\f[R]
(Valuation), holdings are valued in the default or given valuation
commodity instead, and the cost columns are also converted to it (at the
valuation date, so percent gain is unaffected).
Cashflows are not converted, however, so the XIRR column is left blank
for holdings whose cashflows are in a different commodity.
\f[CR]\-\-value=then\f[R] is not supported, and \f[CR]\-B/\-\-cost\f[R]
doesn\(aqt change the report\(aqs figures (but see sorting and
\f[CR]balance:\f[R] below).
.PP
\f[CR]\-S/\-\-sort\-amount\f[R] sorts the lines by their Total value,
largest first, wherever their account.
Holdings with no market price come after the priced ones, sorted by
their Total cost.
In tree mode, sibling accounts are sorted likewise by their subtree\(aqs
totals, as shown on their headings (an account sorts with the unpriced
ones only when none of its holdings has a market price), and the
holdings under each account as in list mode.
With \f[CR]\-B\f[R], everything is sorted by Total cost.
Values in different commodities are compared by their numbers alone; to
compare them properly, convert them to one commodity with
\f[CR]\-X COMM\f[R].
.PP
Amounts are displayed with their commodity\(aqs display precision.
\f[CR]\-\-round\f[R] can select another rounding strategy.
The percent columns (Weight, UGain%, XIRR) are shown with the display
style configured for the \f[CR]%\f[R] commodity (eg by
\f[CR]\-c \(aq0.00 %\(aq\f[R]).
With colour enabled, the gain columns (UGain, UGain%, RGain, XIRR) show
gains in green and losses in red.
.PP
Query arguments and report flags like \f[CR]\-\-depth\f[R],
\f[CR]\-\-title\f[R] etc.
work as usual.
\f[CR]balance:\f[R] and \f[CR]change:\f[R] query terms test each line
(one commodity in one account).
A line has two amounts, its units and its Total value, and the term\(aqs
commodity symbol selects which is tested:
.IP \(bu 2
\f[CR]holdings balance:\(aq>100\(aq\f[R] \- holdings of more than 100
units (with no symbol, units are tested)
.IP \(bu 2
\f[CR]holdings balance:\(aq>100 AAPL\(aq\f[R] \- holdings of more than
100 AAPL
.IP \(bu 2
\f[CR]holdings balance:\(aq>$1000\(aq\f[R] \- holdings worth more than
$1000.
Lines with no market price have no value, and don\(aqt match.
.IP \(bu 2
\f[CR]holdings \-B balance:\(aq>$1000\(aq\f[R] \- holdings which cost
more than $1000 (with \f[CR]\-B\f[R], Total cost is tested instead of
Total value)
.PP
\f[CR]change:\f[R] tests the line\(aqs change in units during the report
period (so it needs a start date, eg \f[CR]\-b\f[R]), or with the
value\(aqs commodity symbol, the value of that change at the valuation
date.
Unlike in other reports, \f[CR]\-V\f[R]/\f[CR]\-X\f[R] don\(aqt change
which amount is tested; to test the value, write its commodity symbol.
But as in other reports, \f[CR]\-B\f[R] tests cost: the line\(aqs Total
cost, or the cost of its change, instead of their value.
The totals and tree mode\(aqs account headings then cover just the lines
shown.
But Weight is still each line\(aqs share of all the holdings, including
the hidden ones (so the total Weight shows what share the lines shown
make up).
.PP
With \f[CR]\-t/\-\-tree\f[R], holdings are grouped into account
sections: an account with subaccounts or several commodities becomes a
heading row, showing its subtree\(aqs totals computed like the totals
row, with its own holdings beneath it named by their commodity; an
account holding one commodity with no subaccounts is a single combined
row; and with \f[CR]\-\-lots\f[R], each holding\(aqs lots appear beneath
it.
Boring parent accounts are squashed into their child as usual
(considering only accounts with holdings), unless
\f[CR]\-\-no\-elide\f[R] is used.
.PP
With \f[CR]\-O html\f[R], an HTML table is produced instead.
With \f[CR]\-O fods\f[R], a spreadsheet document readable by LibreOffice
etc.
is produced.
With \f[CR]\-O csv\f[R] or \f[CR]\-O tsv\f[R], machine\-readable output
is produced: one record per holding (or lot, with \f[CR]\-\-lots\f[R]),
with full account names, age in days, bare units and gain percent
numbers, and no totals or tree\-mode heading records.
With \f[CR]\-O json\f[R], a JSON array of holding objects is produced.
In both, the cost and value fields are named \f[CR]unitcost\f[R],
\f[CR]unitprice\f[R], \f[CR]totalcost\f[R] and \f[CR]totalvalue\f[R].
.SS Gains during a period
Normally the gain columns show each holding\(aqs gains since it was
acquired.
With a report start date (eg \f[CR]\-b\f[R], \f[CR]\-p\f[R], or
\f[CR]date:\f[R]), they show the gains during the report period instead,
and the report title says so (eg \(dqgains in 2026\-11\(dq):
.IP
.EX
$ hledger holdings \-p today # today\(aqs gains
$ hledger holdings \-p thisyear # this year\(aqs gains so far
$ hledger holdings \-b 2026\-10\-01 # gains since a date (until today)
$ hledger holdings \-p 2026\-q3 # gains in a past period (the report shows holdings at its end)
.EE
.PP
The units, cost, price, value and Weight columns are unchanged; they
show holdings as of the report end date.
But:
.IP \(bu 2
UGain is the change in unrealised gain during the period: the unrealised
gain at the end, minus that on the day before the start date.
(Note that selling realises gains: UGain decreases and RGain increases.)
.IP \(bu 2
UGain% is that as a percentage of the holding\(aqs value on the day
before the start date, plus the net cost added since.
.IP \(bu 2
RGain is the realised gain from disposals during the period.
.IP \(bu 2
XIRR is the annualised rate of return for the period, counting the value
on the day before the start date as invested then.
For a short period this can be a very large number (or blank, when too
large to calculate); UGain% shows the period\(aqs un\-annualised gain.
.PP
The start date is the first day of the period, so gains are measured
from the previous day\(aqs closing prices: \f[CR]\-p today\f[R] shows
today\(aqs gains (today\(aqs market prices compared with the latest ones
before today), and \f[CR]\-b yesterday\f[R] shows yesterday\(aqs and
today\(aqs.
This way consecutive periods\(aq gains add up, and a month\(aqs gains
start from the previous month\(aqs last prices, as in a broker\(aqs
statement.
If a market price is missing at the start or the end, the gains
depending on it are left blank.
With \f[CR]\-E\f[R], holdings fully disposed during the period are shown
too.
.PP
A report start date before your first acquisition gives the same gains
as no start date.
\f[CR]\-H/\-\-historical\f[R] shows the gains since acquisition despite
a start date.
(With a report interval, gains are since acquisition unless you ask
otherwise; see below.)
.SS Holdings over time
With a report interval (eg \f[CR]\-M\f[R], \f[CR]\-Q\f[R],
\f[CR]\-Y\f[R]), holdings shows how your holdings changed: their totals
at the end of each period, each computed as on that date (eg valued at
its market prices).
When the holdings are all of one commodity (eg with a \f[CR]cur:\f[R]
query), their Units, Avg cost and Unit price are shown too.
.PP
The gain columns\(aq period is selected as in other periodic reports
(accumulation mode):
.IP \(bu 2
\f[CR]\-H/\-\-historical\f[R] (the default): gains since acquisition, up
to each period\(aqs end
.IP \(bu 2
\f[CR]\-\-change\f[R]: gains during each period, as in a single\-date
report of that period (above); these add up: the periods\(aq UGain and
RGain sum to those of the whole report period
.IP \(bu 2
\f[CR]\-\-cumulative\f[R]: gains from the report start date up to each
period\(aqs end.
.PP
With no end date, the periods continue up to today, even after your last
transaction (since values change with market prices), and the current
period\(aqs row shows today\(aqs holdings, like the report without an
interval.
List/tree mode and \f[CR]\-\-lots\f[R] make no difference to these
totals, and are ignored.
With \f[CR]\-O csv\f[R], \f[CR]tsv\f[R] or \f[CR]json\f[R], there is one
record per period end, whose \f[CR]unpriced\f[R] field lists the
commodities excluded from its totals for having no market price.
.IP
.EX
$ hledger holdings \-M \-e 2026\-04\-01
Monthly holdings, 2026\-01\-31..2026\-03\-31
|| Units Avg cost Unit price Total cost Total value UGain UGain% RGain XIRR
============++======================================================================================
2026\-01\-31 || 10 AAA $10 $12 $100 $120 $20 20.0% 820.5%
2026\-02\-28 || 6 AAA $10 $15 $60 $90 $30 50.0% $20 1566.4%
2026\-03\-31 || 6 AAA $10 $9 $60 $54 $\-6 \-10.0% $20 108.0%
.EE
.SS Holdings charts
With \f[CR]\-\-chart\f[R], holdings are shown as a chart: a bar for each
holding (or lot, with \f[CR]\-\-lots\f[R]), labelled by account and
commodity.
A holding\(aqs bar shows its cost basis, and its unrealised gain stacked
on top, reaching its market value (which is shown); or if it has lost
value, the part of its cost basis it is still worth, reaching its market
value, and the part lost beyond it (hatched).
So the solid part of a bar always reaches the market value.
In graphical charts these are coloured like assets (blue), revenues
(green) and expenses (red).
Each bar\(aqs unrealised gain percent is shown after its value, in green
if positive or red if negative.
Graphical charts show it instead of the value (which the axis shows), at
the right of the bars, which are horizontal so that there is room for
all of them.
With a report interval, each period\(aqs gain percent is above its bar,
when there is room for them all.
A holding without a market price is shown as its cost basis, in grey.
There is a chart panel for each commodity the holdings are valued in;
use \f[CR]\-X COMM\f[R] to see them all in one.
With a report interval, there is a bar for each period end instead,
showing all the holdings then: their total cost basis, and their net
unrealised gain or loss (with \f[CR]\-\-chart=net\f[R], also their
value: in graphical charts, a line joining the periods, like other
reports\(aq totals).
With \f[CR]\-\-change\f[R] or \f[CR]\-\-cumulative\f[R], the bars show
the gains the table shows instead: realised gains, and unrealised gains
(hatched, since they are not yet final), with losses below zero, and
with \f[CR]\-\-chart=net\f[R], the net gain (in graphical charts, a line
joining the periods, like other reports\(aq totals).
As in the table, the periods whose values and gains exclude holdings
with no market price are starred, with a note below the chart.
With SVG output (eg \f[CR]\-o holdings.svg\f[R], or \f[CR]\-\-view\f[R])
it is a graphical chart, and with HTML output it is shown above the
report\(aqs table.
See Charts for more.
.IP
.EX
$ hledger holdings \-\-chart \-w 70
Holdings on 2024\-12\-31
USD
█ Cost ▒ Unrealised gain ╱ Unrealised loss ▓ No market price
assets:broker AAPL 2,500.00 USD +66.7% █████████████████▒▒▒▒▒▒▒▒▒▒▒
assets:broker NEW ▓
assets:broker XYZ 450.00 USD \-40.0% █████╱╱╱
.EE
.SS incomestatement
(is)
.PP
Show revenue inflows and expense outflows during the report period.
Amounts are shown with normal positive sign, as in conventional
financial statements.
.IP
.EX
Flags:
\-\-sum calculation mode: show sum of posting amounts
(default)
\-\-valuechange calculation mode: show total change of value
of period\-end historical balances (caused by
deposits, withdrawals, market price
fluctuations)
\-\-gain calculation mode: show unrealised capital
gain/loss (historical balance value minus cost
basis)
\-\-count calculation mode: show the count of postings
\-\-change accumulation mode: accumulate amounts from
column start to column end (in multicolumn
reports) (default)
\-\-cumulative accumulation mode: accumulate amounts from
report start (specified by e.g. \-b/\-\-begin) to
column end
\-H \-\-historical accumulation mode: accumulate amounts from
journal start to column end (includes postings
before report start date)
\-l \-\-flat list/tree mode: show accounts as a flat list
(default). Amounts exclude subaccount amounts,
except where the account is depth\-clipped.
\-t \-\-tree list/tree mode: show accounts as a tree.
Amounts include subaccount amounts.
\-\-drop=N in list mode, omit N leading account name
parts
\-\-declared include non\-parent declared accounts (best
used with \-E)
\-A \-\-average show a row average column (in multicolumn
reports)
\-T \-\-row\-total show a row total column (in multicolumn
reports)
\-\-summary\-only display only row summaries (e.g. row total,
average) (in multicolumn reports)
\-N \-\-no\-total omit the final total row
\-\-no\-elide in tree mode, don\(aqt squash boring parent
accounts; in list mode, also show parent
accounts (usually zero, hidden without \-E)
\-\-full\-names in tree mode, show full account names instead
of indented leaf names
\-\-format=FORMATSTR use this custom line format (in simple
reports)
\-S \-\-sort\-amount sort by amount instead of account code/name
\-% \-\-percent express values in percentage of each column\(aqs
total
\-\-layout=ARG how to show multi\-commodity amounts:
\(aqwide[,WIDTH]\(aq: all commodities on one line
\(aqtall\(aq : each commodity on a new line
\(aqbare\(aq : bare numbers, symbols in a
column
\-\-base\-url=URLPREFIX in html output, generate hyperlinks to
hledger\-web, with this prefix. (Usually the base
url shown by hledger\-web; can also be relative.)
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, html, csv, tsv, json, svg.
\-o \-\-output\-file=FILE write output to FILE. A file extension
matching one of the above formats selects that
format.
\-\-view write output to FILE, or to view.FMT in
hledger\(aqs cache directory, and open it in the
system\(aqs default viewer for its format (eg a web
browser for html). The default format is html.
\-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),
above it (html), or as data (csv, tsv, json).
KIND: diverging (sections above and below zero;
the default) or grouped (sections side by side).
net: also draw the net total (a line, or marks
in text charts). SCALE: the amount that fills
the chart (eg 1000 or 1000 USD; one per
commodity), for comparable charts.
\-w \-\-width=N with \-\-chart: draw the chart N characters wide
(default: the terminal width)
.EE
.PP
This command displays an income statement, showing revenues and expenses
during one or more periods.
.PP
It shows accounts declared with the \f[CR]Revenue\f[R] or
\f[CR]Expense\f[R] type (see account types).
Or if no such accounts are declared, it shows top\-level accounts named
\f[CR]revenue\f[R] or \f[CR]income\f[R] or \f[CR]expense\f[R] (case
insensitive, plurals allowed) and their subaccounts.
.PP
Example:
.IP
.EX
$ hledger incomestatement
Income Statement 2008
|| 2008
===================++======
Revenues ||
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-
income:gifts || $1
income:salary || $1
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-
|| $2
===================++======
Expenses ||
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-
expenses:food || $1
expenses:supplies || $1
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-
|| $2
===================++======
Net: || 0
.EE
.PP
This command is a higher\-level variant of the \f[CR]balance\f[R]
command, and supports many of that command\(aqs features, such as
multi\-period reports.
It is similar to
\f[CR]hledger balance \(aq(revenues|income)\(aq expenses\f[R], but with
smarter account detection, and revenues/income displayed with their sign
flipped.
.PP
This command also supports the output destination and output format
options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],
\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]json\f[R], and \f[CR]svg\f[R] (a
chart; see Balance charts).
.SS notes
List the unique notes that appear in transactions.
.IP
.EX
Flags:
no command\-specific flags
.EE
.PP
This command lists the unique notes that appear in transactions, in
alphabetic order.
You can add a query to select a subset of transactions.
The note is the part of the transaction description after a | character
(or if there is no |, the whole description).
.PP
Example:
.IP
.EX
$ hledger notes
Petrol
Snacks
.EE
.SS payees
List the payee/payer names used or declared in the journal.
.IP
.EX
Flags:
\-\-used list payees used
\-\-declared list payees declared
\-\-undeclared list payees used but not declared
\-\-unused list payees declared but not used
\-\-find list the first payee matched by the first
argument (a case\-insensitive infix regexp)
\-\-directives show as payee directives, for use in journals
.EE
.PP
This command lists unique payee/payer names \- all of them by default,
or just the ones which have been used in transaction descriptions, or
declared with \f[CR]payee\f[R] directives, or used but not declared, or
declared but not used, or just the first one matched by a pattern (with
\f[CR]\-\-find\f[R], returning a non\-zero exit code if it fails).
.PP
The payee/payer name is the part of the transaction description before a
| character (or if there is no |, the whole description).
.PP
With \f[CR]\-\-directives\f[R], it shows valid payee directives, which
could be pasted into a journal file.
.PP
You can add query arguments to select a subset of transactions or
payees.
Note that transaction\-specific query terms like \f[CR]date:\f[R] will
exclude declared\-but\-unused payees, which don\(aqt have that field.
.PP
Example:
.IP
.EX
$ hledger payees
Store Name
Gas Station
Person A
.EE
.SS prices
Print the market prices declared with P directives.
With \-\-infer\-market\-prices, also show any additional prices inferred
from costs.
With \-\-show\-reverse, also show additional prices inferred by
reversing known prices.
With \-\-show\-aliases, also show the exchange rates provided by
commodity aliases.
.IP
.EX
Flags:
\-\-show\-reverse also show the prices inferred by reversing known
prices
\-\-show\-aliases also show the exchange rates provided by
commodity aliases
\-\-summary summarise declared prices per commodity instead
of listing them
\-\-locations also show where prices where declared
.EE
.PP
With \f[CR]\-\-locations\f[R], each price line gets a trailing
\f[CR]; location: FILE:LINE\f[R] comment showing where it came from.
Declared prices point at their P directive; prices inferred from costs
point at the parent transaction\(aqs first line.
Reversed prices keep the source position of the directive they were
derived from.
.PP
With \f[CR]\-\-show\-aliases\f[R], each commodity alias which provides
an exchange rate (between a commodity and its alias, when there are no
market prices between them) is shown as a price dated 0000\-01\-01 with
a \f[CR]; commodity alias\f[R] comment.
Its location is the commodity directive which declared the alias.
These are used only when market prices can\(aqt provide a conversion,
see Finding market price.
.PP
Price amounts are always displayed with their full precision, except for
reverse prices which are limited to 8 decimal digits.
.PP
Prices can be filtered by a date:, cur:, amt: or find: query.
.PP
Generally if you run this command with \-\-infer\-market\-prices
\-\-show\-reverse \-\-show\-aliases, it will show the same prices used
internally to calculate value reports.
But if in doubt, you can inspect those directly by running the value
report with \-\-debug=2.
.PP
Examples:
.IP
.EX
$ hledger prices
P 2024\-01\-01 AAPL $150
P 2024\-02\-01 AAPL $160
P 2024\-02\-01 EUR $1.08
.EE
.IP
.EX
$ hledger prices \-\-infer\-market\-prices
P 2024\-01\-01 AAPL $150
P 2024\-01\-05 AAPL $150
P 2024\-02\-01 AAPL $160
P 2024\-02\-01 EUR $1.08
.EE
.SS prices summary
With \f[CR]\-\-summary\f[R], instead of listing individual prices,
\f[CR]prices\f[R] prints one row per commodity used in the journal
(other than the base currency), with the following columns:
.IP \(bu 2
\f[B]Commodity\f[R] \(em the commodity, as an ISO 4217 code if possible.
.IP \(bu 2
\f[B]Prices\f[R] \(em the number of market price declarations for that
commodity.
.IP \(bu 2
\f[B]Earliest\f[R] / \f[B]Latest\f[R] \(em the date range of those
prices.
.IP \(bu 2
\f[B]Period\f[R] \(em the duration between earliest and latest.
.IP \(bu 2
\f[B]Coverage\f[R] \(em the percentage of weekdays in that period that
have a price declared (or blank when fewer than two prices).
.PP
Summary mode is a quick way to spot gaps in your price data, and pairs
naturally with getprices.
Only prices declared with P directives are counted; prices inferred with
\f[CR]\-\-show\-reverse\f[R] or \f[CR]\-\-infer\-market\-prices\f[R] are
ignored.
.PP
Queries (\f[CR]cur:\f[R], \f[CR]date:\f[R], \f[CR]amt:\f[R],
\f[CR]find:\f[R]) can be used to narrow the prices that are summarised.
.SS print
Show transactions\(aq journal entries, or export journal data to another
format.
.IP
.EX
Flags:
\-a \-\-all show all details (\-\-explicit \-\-lots
\-\-verbose\-tags)
\-x \-\-explicit show all inferred info explicitly
\-\-verbose\-tags add tags indicating generated/modified data
\-\-invert display all amounts with reversed sign
\-\-locations add tags showing file paths and line numbers
\-\-export reproduce the whole journal, with directives and
comments preserved and included files inlined
\-m \-\-match=DESC fuzzy search for one recent transaction with
description closest to DESC
\-\-new show only newer\-dated transactions added in each
file since last run
\-\-round=TYPE how much rounding or padding should be done when
displaying amounts ?
none \- show original decimal digits,
as in journal (default)
soft \- just add or remove decimal zeros
to match precision
hard \- round posting amounts to precision
(can unbalance transactions)
all \- also round cost amounts to precision
(can unbalance transactions)
\-\-layout=hledger1|COL how should posting amounts be aligned ?
hledger1 \- right\-align amounts, as in hledger 1
COL \- align decimal marks at column COL
(default: 53)
\-\-base\-url=URLPREFIX in html output, generate links to hledger\-web,
with this prefix. (Usually the base url shown by
hledger\-web; can also be relative.)
\-O \-\-output\-format=FMT select the output format. Supported formats:
journal, ledger, beancount, csv, tsv, html, fods,
json, sql.
\-o \-\-output\-file=FILE write output to FILE. A file extension matching
one of the above formats selects that format.
\-\-view write output to FILE, or to view.FMT in hledger\(aqs
cache directory, and open it in the system\(aqs
default viewer for its format (eg a web browser for
html). The default format is html.
.EE
.PP
The print command displays full journal entries (transactions) from the
journal file, sorted by date (or with \f[CR]\-\-date2\f[R], by secondary
date).
(For a compact one\-line\-per\-transaction overview, see the
\f[CR]transactions\f[R] command.)
.PP
By default, directives and inter\-transaction comments are not shown
(except for comment lines immediately preceding a transaction, which are
shown with it), and entries are sorted by date.
So the default print output is somewhat lossy.
To reproduce the whole journal, including directives and comments, use
\f[CR]\-\-export\f[R] (see below).
.PP
Eg:
.IP
.EX
$ hledger print \-f examples/sample.journal date:200806
2008/06/01 gift
assets:bank:checking $1
income:gifts $\-1
2008/06/02 save
assets:bank:saving $1
assets:bank:checking $\-1
2008/06/03 * eat & shop
expenses:food $1
expenses:supplies $1
assets:cash $\-2
.EE
.SS print explicitness
Normally, whether posting amounts are implicit or explicit is preserved.
For example, when an amount is omitted in the journal, it will not
appear in the output.
Similarly, if a conversion cost is implied but not written, it will not
appear in the output.
.PP
You can use the \f[CR]\-x\f[R]/\f[CR]\-\-explicit\f[R] flag to force
explicit display of all amounts and costs.
This can be useful for troubleshooting or for making your journal more
readable and robust against data entry errors.
\f[CR]\-x\f[R] is also implied by using any of
\f[CR]\-B\f[R],\f[CR]\-V\f[R],\f[CR]\-X\f[R],\f[CR]\-\-value\f[R].
.PP
The \f[CR]\-x\f[R]/\f[CR]\-\-explicit\f[R] flag will cause any postings
with a multi\-commodity amount (which can arise when a multi\-commodity
transaction has an implicit amount) to be split into multiple
single\-commodity postings, keeping the output parseable.
.PP
To see more details \(em not just inferred amounts and costs, but also
lot subaccounts and postings, and the hidden tags that hledger adds to
classify things \(em use \f[CR]\-a\f[R]/\f[CR]\-\-all\f[R], which is
equivalent to \f[CR]\-\-explicit \-\-lots \-\-verbose\-tags\f[R].
.SS print layout
By default, \f[CR]print\f[R] aligns posting amounts so that their
decimal mark is at column 53 (or would be if they had a decimal mark).
If needed, it will shift a transaction\(aqs amounts further to the right
to ensure at least 2 spaces between account names and amounts.
Also, any balance assertion/assignment operators (\f[CR]=\f[R],
\f[CR]=*\f[R] etc.)
are aligned to the right of the posting amounts; and the
assertion/assignment amounts will be aligned by their decimal marks.
.PP
You can customise this with \f[CR]\-\-layout\f[R]:
.IP \(bu 2
\f[CR]\-\-layout=COL\f[R] \(em sets a different target column for
posting amounts\(aq decimal mark
.IP \(bu 2
\f[CR]\-\-layout=hledger1\f[R] \(em use hledger 1 layout (right\-aligned
posting amounts in each transaction).
.PP
If you want to change the default, put something like this in
\f[CR]\(ti/.hledger.conf\f[R]:
.IP
.EX
[print]
\-\-layout=hledger1
.EE
.PP
Other print\-like commands (close, import, rewrite, add) also accept
\f[CR]\-\-layout\f[R].
.SS print amount style
Amounts will be displayed mostly in their commodity\(aqs display style,
with standardised symbol placement, decimal mark, and digit group marks.
This does not apply to their decimal digits; \f[CR]print\f[R] normally
shows the same decimal digits that are recorded in each journal entry.
(Calculated amounts with a repeating decimal, eg from converting
\f[CR]10 min\f[R] to hours, are shown with 8 decimal places.)
.PP
You can override the decimal precisions with \f[CR]print\f[R]\(aqs
special \f[CR]\-\-round\f[R] option.
\f[CR]\-\-round\f[R] tries to show amounts with their commodities\(aq
standard decimal precisions, increasingly strongly:
.IP \(bu 2
\f[CR]\-\-round=none\f[R] show amounts with original precisions
(default)
.IP \(bu 2
\f[CR]\-\-round=soft\f[R] add/remove decimal zeros in amounts (except
costs)
.IP \(bu 2
\f[CR]\-\-round=hard\f[R] round amounts (except costs), possibly hiding
significant digits
.IP \(bu 2
\f[CR]\-\-round=all\f[R] round all amounts and costs
.PP
\f[CR]soft\f[R] is good for non\-lossy cleanup, displaying more
consistent decimals where possible, without making entries unbalanced.
.PP
\f[CR]hard\f[R] or \f[CR]all\f[R] can be good for stronger cleanup, when
decimal rounding is wanted.
Note rounding can produce unbalanced journal entries, perhaps requiring
manual fixup.
.SS print parseability
Usually, print\(aqs output is a valid hledger journal, which you can
pipe into a second hledger command for further processing.
This is sometimes convenient for rewriting journal entries:
.IP
.EX
# Make today\(aqs shopping entry explicit. (\-f \- means read from standard input.)
$ hledger print date:today desc:shop | hledger \-f\- print \-x
.EE
.PP
or for achieving certain kinds of query:
.IP
.EX
# Show running total of food expenses paid from cash.
$ hledger print assets:cash | hledger \-f\- reg expenses:food
.EE
.PP
But here are some things which can cause print\(aqs output to become
unparseable:
.IP \(bu 2
\f[CR]\-\-round\f[R] (see above) can disrupt transaction balancing.
.IP \(bu 2
Account aliases or pivoting can disrupt account names, balance
assertions, or balance assignments.
.IP \(bu 2
Value reporting also can disrupt balance assertions or balance
assignments.
.IP \(bu 2
Auto postings can generate too many amountless postings.
.IP \(bu 2
\f[CR]\-\-infer\-costs or \-\-infer\-equity\f[R] can generate
too\-complex redundant costs.
.IP \(bu 2
Because print always shows transactions in date order, balance
assertions involving non\-date\-ordered transactions (and same\-day
postings) could be disrupted.
.PP
Also, printing a subset of journal entries can disrupt validation of
balance assertions or lot entries.
And print does not reproduce directives (unless \f[CR]\-\-export\f[R] is
used).
Lot entries are printed with their inferred cost basis annotations, so
they can still be read without the commodity\(aqs \f[CR]lots:\f[R]
declaration when the default cost basis method is used; but with other
methods, or \f[CR]lots: NONE\f[R] accounts, the missing declarations
will change how they are read.
(\f[CR]\-\-export\f[R] output keeps lot entries as written, since it
reproduces the declarations.)
To suppress errors from these, we often use the \f[CR]\-I\f[R] flag
(short for \f[CR]\-\-ignore\-assertions \-\-ignore\-lots\f[R]).
So any time you are reading from standard input with \f[CR]\-f\-\f[R],
consider adding \f[CR]\-I\f[R] also.
.SS print export mode
With \f[CR]\-\-export\f[R], print reproduces the whole journal in its
original order, with directives, top\-level comment lines and
\f[CR]comment\f[R] blocks preserved verbatim, and with each transaction
shown as print normally shows it (so \f[CR]\-x\f[R],
\f[CR]\-\-round\f[R], \f[CR]\-\-layout\f[R] etc.
still apply).
Blank lines are normalised: there is one blank line between
transactions, and between groups of directive or comment lines.
The output can be read by hledger as an equivalent journal, so this is
the mode to use when reformatting or regenerating a journal file.
Some details:
.IP \(bu 2
Included files are inlined at the position of their \f[CR]include\f[R]
directive, and the \f[CR]include\f[R] line itself is dropped.
If you want to preserve a multi\-file structure rather than flattening
it, currently the best way is: comment out the \f[CR]include\f[R]
directives (they will be preserved as comments), export each file
individually, then uncomment the \f[CR]include\f[R] directives in the
exported main file.
(A file which depends on directives in its parent file, such as
\f[CR]Y\f[R] or \f[CR]decimal\-mark\f[R], might need those added
temporarily while it is exported.)
.IP \(bu 2
\f[CR]apply account\f[R], \f[CR]alias\f[R] and their \f[CR]end\f[R]
directives are dropped, since their effect is already applied to the
account names shown.
(An \f[CR]account\f[R] declaration inside an \f[CR]apply account\f[R]
block is reproduced as written, without the parent account prefix.)
.IP \(bu 2
Directives which hledger ignores (for compatibility with Ledger) are not
exported.
.IP \(bu 2
By default, periodic transaction rules (\f[CR]\(ti\f[R]) and auto
posting rules (\f[CR]=\f[R]) are exported as directives.
With \f[CR]\-\-forecast\f[R] and/or \f[CR]\-\-auto\f[R], the generated
transactions (at the end of the output) and postings are exported
instead, and the rules are not.
In other words, these flags materialise the rules.
Postings generated by \f[CR]\-\-infer\-equity\f[R] are exported too.
(In Beancount output, these rules are never exported, only whatever has
been generated.)
.IP \(bu 2
A query still selects which transactions are shown, but all directives
and comments are kept.
.IP \(bu 2
Transactions from non\-journal files (eg an included CSV file) are added
at the end.
.IP \(bu 2
The \f[CR]journal\f[R] (default), \f[CR]ledger\f[R] and
\f[CR]beancount\f[R] output formats are supported.
With \f[CR]\-O ledger\f[R], transactions use Ledger\(aqs lot syntax, and
directives which hledger accepts but Ledger does not
(\f[CR]decimal\-mark\f[R], a one\-line \f[CR]commodity\f[R] directive
with an amount, a periodic transaction rule with a description, an auto
posting rule with \f[CR]*N\f[R] amount multipliers) are commented out,
with an explanatory comment.
Other hledger\-specific syntax may remain; see Ledger output.
With \f[CR]\-O beancount\f[R], Beancount \f[CR]option\f[R],
\f[CR]commodity\f[R], \f[CR]open\f[R] and \f[CR]price\f[R] directives
are generated from the journal\(aqs declarations and data, other
directives (which have no Beancount equivalent) are dropped, and
comments are converted to Beancount comments; see Beancount output.
Note for both Ledger and Beancount, manual fixups may still be required
in some cases; but the export will be a good start.
.SS print, other features
With \f[CR]\-B\f[R]/\f[CR]\-\-cost\f[R], amounts with costs are shown
converted to cost.
.PP
With \f[CR]\-\-invert\f[R], posting amounts are shown with their sign
flipped.
It could be useful if you have accidentally recorded some transactions
with the wrong signs.
.PP
With \f[CR]\-\-new\f[R], print shows only transactions it has not seen
on a previous run.
This uses the same deduplication system as the \f[CR]import\f[R]
command.
(See import\(aqs docs for details.)
.PP
With \f[CR]\-m DESC\f[R]/\f[CR]\-\-match=DESC\f[R], print shows one
recent transaction whose description is most similar to DESC.
DESC should contain at least two characters.
If there is no similar\-enough match, no transaction will be shown and
the program exit code will be non\-zero.
.PP
With \f[CR]\-\-locations\f[R], print adds the source file and line
number to every transaction, as a tag.
.SS print output format
This command also supports the output destination and output format
options The output formats supported are \f[CR]journal\f[R] (the
default; \f[CR]txt\f[R] is also accepted), \f[CR]ledger\f[R],
\f[CR]beancount\f[R], \f[CR]csv\f[R], \f[CR]tsv\f[R], \f[CR]html\f[R],
\f[CR]fods\f[R], \f[CR]json\f[R] and \f[CR]sql\f[R].
.PP
The \f[CR]ledger\f[R] format is currently the same as \f[CR]journal\f[R]
except it renders amounts\(aq cost basis using Ledger\(aqs lot syntax
(\f[CR][DATE] (LABEL) {COST}\f[R]) instead of hledger\(aqs
(\f[CR]{DATE, \(dqLABEL\(dq, COST}\f[R]).
.PP
The \f[CR]beancount\f[R] format tries to produce Beancount\-compatible
output, as follows:
.IP \(bu 2
Transaction and postings with unmarked status are converted to cleared
(\f[CR]*\f[R]) status.
.IP \(bu 2
Transactions\(aq payee and note are backslash\-escaped and
double\-quote\-escaped and wrapped in double quotes.
.IP \(bu 2
Transaction and posting tags are converted to Beancount metadata lines.
.IP \(bu 2
Commodity symbols are converted to upper case, and a small number of
currency symbols like \f[CR]$\f[R] are converted to the corresponding
currency names.
.IP \(bu 2
Account name parts are capitalised and unsupported characters are
replaced with \f[CR]\-\f[R].
The first part must be one of Assets, Liabilities, Equity, Income or
Expenses; if it is not, but the account\(aqs type is known (declared or
inferred), the corresponding one of those is prepended; otherwise an
error is raised.
(Or, use \f[CR]\-\-alias\f[R] options to bring your accounts into
compliance.)
.IP \(bu 2
Balance assignments are converted to explicit amounts.
.IP \(bu 2
Virtual and balanced virtual postings are dropped.
.PP
By default only transactions are shown.
With \f[CR]\-\-export\f[R], the directives Beancount needs are also
generated: options (a commented\-out tolerance option, and
\f[CR]operating_currency\f[R] for the currencies used in costs), a
\f[CR]commodity\f[R] directive for each declared commodity, an
\f[CR]open\f[R] directive for each declared or used account (on the
account\(aqs earliest posting date, or the earliest transaction date),
and \f[CR]price\f[R] directives.
Account and commodity tags become metadata on those directives, and an
account\(aqs \f[CR]lots:\f[R] tag becomes the Beancount booking method.
Other hledger directives are dropped, and top\-level comments are
converted to Beancount comments.
.PP
Here\(aqs an example of print\(aqs CSV output:
.IP
.EX
$ hledger print \-Ocsv
\(dqtxnidx\(dq,\(dqdate\(dq,\(dqdate2\(dq,\(dqstatus\(dq,\(dqcode\(dq,\(dqdescription\(dq,\(dqcomment\(dq,\(dqaccount\(dq,\(dqamount\(dq,\(dqcommodity\(dq,\(dqdebit\(dq,\(dqcredit\(dq,\(dqposting\-status\(dq,\(dqposting\-comment\(dq
\(dq1\(dq,\(dq2008/01/01\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqincome\(dq,\(dq\(dq,\(dqassets:bank:checking\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq
\(dq1\(dq,\(dq2008/01/01\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqincome\(dq,\(dq\(dq,\(dqincome:salary\(dq,\(dq\-1\(dq,\(dq$\(dq,\(dq\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq
\(dq2\(dq,\(dq2008/06/01\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqgift\(dq,\(dq\(dq,\(dqassets:bank:checking\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq
\(dq2\(dq,\(dq2008/06/01\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqgift\(dq,\(dq\(dq,\(dqincome:gifts\(dq,\(dq\-1\(dq,\(dq$\(dq,\(dq\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq
\(dq3\(dq,\(dq2008/06/02\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqsave\(dq,\(dq\(dq,\(dqassets:bank:saving\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq
\(dq3\(dq,\(dq2008/06/02\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqsave\(dq,\(dq\(dq,\(dqassets:bank:checking\(dq,\(dq\-1\(dq,\(dq$\(dq,\(dq\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq
\(dq4\(dq,\(dq2008/06/03\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqeat & shop\(dq,\(dq\(dq,\(dqexpenses:food\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq
\(dq4\(dq,\(dq2008/06/03\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqeat & shop\(dq,\(dq\(dq,\(dqexpenses:supplies\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq
\(dq4\(dq,\(dq2008/06/03\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqeat & shop\(dq,\(dq\(dq,\(dqassets:cash\(dq,\(dq\-2\(dq,\(dq$\(dq,\(dq\(dq,\(dq2\(dq,\(dq\(dq,\(dq\(dq
\(dq5\(dq,\(dq2008/12/31\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqpay off\(dq,\(dq\(dq,\(dqliabilities:debts\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq
\(dq5\(dq,\(dq2008/12/31\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqpay off\(dq,\(dq\(dq,\(dqassets:bank:checking\(dq,\(dq\-1\(dq,\(dq$\(dq,\(dq\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq
.EE
.IP \(bu 2
There is one CSV record per posting, with the parent transaction\(aqs
fields repeated.
.IP \(bu 2
The \(dqtxnidx\(dq (transaction index) field shows which postings belong
to the same transaction.
(This number might change if transactions are reordered within the file,
files are parsed/included in a different order, etc.)
.IP \(bu 2
The amount is separated into \(dqcommodity\(dq (the symbol) and
\(dqamount\(dq (numeric quantity) fields.
.IP \(bu 2
The numeric amount is repeated in either the \(dqdebit\(dq or
\(dqcredit\(dq column, for convenience.
(Those names are not accurate in the accounting sense; it just puts zero
or greater amounts under debit and negative amounts under credit.)
.SS register
(reg)
.PP
Show postings & running total across accounts.
.IP
.EX
Flags:
\-\-cumulative accumulation mode: show running total from report
start date (default)
\-H \-\-historical accumulation mode: show historical running
total/balance (includes postings before report
start date)
\-A \-\-average show running average of posting amounts instead
of total (implies \-\-empty)
\-m \-\-match=DESC fuzzy search for one recent posting with
description closest to DESC
\-r \-\-related show postings\(aq siblings instead
\-\-invert display all amounts with reversed sign
\-\-drop=N omit N leading account name parts
\-\-sort=FIELDS sort by: date, desc, account, amount, absamount,
or a comma\-separated combination of these. For a
descending sort, prefix with \-. (Default: date)
\-w \-\-width=N set output width (default: terminal width). \-wN,M
sets description width as well.
\-\-align\-all guarantee alignment across all lines (slower)
\-\-base\-url=URLPREFIX in html output, generate links to hledger\-web,
with this prefix. (Usually the base url shown by
hledger\-web; can also be relative.)
\-O \-\-output\-format=FMT select the output format. Supported formats:
txt, csv, tsv, html, fods, json, svg.
\-o \-\-output\-file=FILE write output to FILE. A file extension matching
one of the above formats selects that format.
\-\-view write output to FILE, or to view.FMT in hledger\(aqs
cache directory, and open it in the system\(aqs
default viewer for its format (eg a web browser for
html). The default format is html.
\-\-chart[=net,SCALE] show a chart: instead of the table (txt), above
it (html), or as data (csv, tsv, json). net: also
draw the net total (a line, or marks in text
charts). SCALE: the amount that fills the chart (eg
1000 or 1000 USD; one per commodity), for
comparable charts.
.EE
.PP
The register command displays matched postings, across all accounts, in
date order, with their running total or running historical balance.
(See also the \f[CR]aregister\f[R] command, which shows matched
transactions in a specific account.)
.PP
register normally shows line per posting, but note that multi\-commodity
amounts will occupy multiple lines (one line per commodity).
.PP
It is typically used with a query selecting a particular account, to see
that account\(aqs activity:
.IP
.EX
$ hledger register checking
2008/01/01 income assets:bank:checking $1 $1
2008/06/01 gift assets:bank:checking $1 $2
2008/06/02 save assets:bank:checking $\-1 $1
2008/12/31 pay off assets:bank:checking $\-1 0
.EE
.PP
With \f[CR]\-\-date2\f[R], it shows and sorts by secondary date instead.
.PP
Postings with a zero amount (including amounts inferred from a balance
assignment) are not shown by default; use the
\f[CR]\-\-empty\f[R]/\f[CR]\-E\f[R] flag to see them.
.PP
For performance reasons, column widths are chosen based on the first
1000 lines; this means unusually wide values in later lines can cause
visual discontinuities as column widths are adjusted.
If you want to ensure perfect alignment, at the cost of more time and
memory, use the \f[CR]\-\-align\-all\f[R] flag.
.PP
The \f[CR]\-\-historical\f[R]/\f[CR]\-H\f[R] flag adds the balance from
any undisplayed prior postings to the running total.
This is useful when you want to see only recent activity, with a
historically accurate running balance:
.IP
.EX
$ hledger register checking \-b 2008/6 \-\-historical
2008/06/01 gift assets:bank:checking $1 $2
2008/06/02 save assets:bank:checking $\-1 $1
2008/12/31 pay off assets:bank:checking $\-1 0
.EE
.PP
The \f[CR]\-\-depth\f[R] option limits the amount of sub\-account detail
displayed.
.PP
The \f[CR]\-\-drop\f[R] option will trim leading segments from account
names.
.PP
The \f[CR]\-\-average\f[R]/\f[CR]\-A\f[R] flag shows the running average
posting amount instead of the running total (so, the final number
displayed is the average for the whole report period).
This flag implies \f[CR]\-\-empty\f[R] (see below).
It is affected by \f[CR]\-\-historical\f[R].
It works best when showing just one account and one commodity.
.PP
The \f[CR]\-\-related\f[R]/\f[CR]\-r\f[R] flag shows the \f[I]other\f[R]
postings in the transactions of the postings which would normally be
shown.
.PP
The \f[CR]\-\-invert\f[R] flag negates all amounts.
For example, it can be used on an income account where amounts are
normally displayed as negative numbers.
It\(aqs also useful to show postings on the checking account together
with the related account:
.PP
The \f[CR]\-\-sort=FIELDS\f[R] flag sorts by the fields given, which can
be any of \f[CR]account\f[R], \f[CR]amount\f[R], \f[CR]absamount\f[R],
\f[CR]date\f[R], or \f[CR]desc\f[R]/\f[CR]description\f[R], optionally
separated by commas.
For example, \f[CR]\-\-sort account,amount\f[R] will group all
transactions in each account, sorted by transaction amount.
Each field can be negated by a preceding \f[CR]\-\f[R], so
\f[CR]\-\-sort \-amount\f[R] will show transactions ordered from
smallest amount to largest amount.
.IP
.EX
$ hledger register \-\-related \-\-invert assets:checking
.EE
.PP
With a reporting interval, register shows summary postings, one per
interval, aggregating the postings to each account:
.IP
.EX
$ hledger register \-\-monthly income
2008/01 income:salary $\-1 $\-1
2008/06 income:gifts $\-1 $\-2
.EE
.PP
Here too, periods with no activity, and summary postings with a zero
amount, are not shown by default; use the
\f[CR]\-\-empty\f[R]/\f[CR]\-E\f[R] flag to see them:
.IP
.EX
$ hledger register \-\-monthly income \-E
2008/01 income:salary $\-1 $\-1
2008/02 0 $\-1
2008/03 0 $\-1
2008/04 0 $\-1
2008/05 0 $\-1
2008/06 income:gifts $\-1 $\-2
2008/07 0 $\-2
2008/08 0 $\-2
2008/09 0 $\-2
2008/10 0 $\-2
2008/11 0 $\-2
2008/12 0 $\-2
.EE
.PP
Often, you\(aqll want to see just one line per interval.
The \f[CR]\-\-depth\f[R] option helps with this, causing subaccounts to
be aggregated:
.IP
.EX
$ hledger register \-\-monthly assets \-\-depth 1
2008/01 assets $1 $1
2008/06 assets $\-1 0
2008/12 assets $\-1 $\-1
.EE
.PP
Note when using report intervals, if you specify start/end dates these
will be adjusted outward if necessary to contain a whole number of
intervals.
This ensures that the first and last intervals are full length and
comparable to the others in the report.
.PP
If you have a deeply nested account tree some reports might benefit from
trimming leading segments from the account names using
\f[CR]\-\-drop\f[R].
.IP
.EX
$ hledger register \-\-monthly income \-\-drop 1
2008/01 salary $\-1 $\-1
2008/06 gifts $\-1 $\-2
.EE
.PP
With \f[CR]\-m DESC\f[R]/\f[CR]\-\-match=DESC\f[R], register does a
fuzzy search for one recent posting whose description is most similar to
DESC.
DESC should contain at least two characters.
If there is no similar\-enough match, no posting will be shown and the
program exit code will be non\-zero.
.SS Custom register output
register normally uses the full terminal width (or 80 columns if it
can\(aqt detect that).
You can override this with the \f[CR]\-\-width\f[R]/\f[CR]\-w\f[R]
option.
.PP
The description and account columns normally share the space equally
(about half of (width \- 40) each).
You can adjust this by adding a description width as part of
\-\-width\(aqs argument, comma\-separated: \f[CR]\-\-width W,D\f[R] .
Here\(aqs a diagram (won\(aqt display correctly in \-\-help):
.IP
.EX
<\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- width (W) \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\->
date (10) description (D) account (W\-41\-D) amount (12) balance (12)
DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA
.EE
.PP
and some examples:
.IP
.EX
$ hledger reg # use terminal width (or 80 on windows)
$ hledger reg \-w 100 # use width 100
$ hledger reg \-w 100,40 # set overall width 100, description width 40
.EE
.PP
This command also supports the output destination and output format
options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],
\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]fods\f[R], \f[CR]json\f[R], and
\f[CR]svg\f[R].
.SS Register charts
With \f[CR]\-\-chart\f[R], or with \f[CR]svg\f[R] output
(\f[CR]\-o FILE.svg\f[R]), it shows a chart instead.
Without a report interval, this is the running total (or average) after
each posting, as a line over time; with postings to several accounts,
each account\(aqs own running total is shown too, in its account
type\(aqs colour (starting from its balance before the report period,
with \f[CR]\-H\f[R]), at most eight of them, the smallest combined into
\(dqother\(dq.
A text chart has a row per posting, with the accounts\(aq running totals
stacked.
With a report interval, it is each account\(aqs amount in each period,
as stacked bars, with the period\(aqs total.
Charts draw the overall running total (with several accounts) or the
periods\(aq totals only with \f[CR]\-\-chart=net\f[R].
With \f[CR]\-\-chart \-O csv\f[R] (or tsv or json) it shows the
chart\(aqs data.
See also Balance charts.
.SS roi
Show the money\-weighted (IRR) and time\-weighted (TWR) rate of return
on your investments.
.IP
.EX
Flags:
\-\-cashflow show all amounts that were used to compute
returns
\-\-investment=QUERY query to select your investment transactions
\-\-profit\-loss=QUERY \-\-pnl query to select profit\-and\-loss or
appreciation/valuation transactions (optional)
.EE
.PP
At a minimum, you need to supply a query (which could be just an account
name) to select your investment(s) with \f[CR]\-\-inv\f[R].
.PP
An optional second query to identify your profit and loss transactions
could be given with \f[CR]\-\-pnl\f[R].
If your investment\(aqs value changes are captured solely through price
directives (rather than manual P&L journal entries), or if you do not
need TWR, you can simply omit \f[CR]\-\-pnl\f[R], and no transactions
will be classed as profit and loss in this case.
.PP
This command will compute and display the internal rate of return (IRR,
also known as money\-weighted rate of return) and time\-weighted rate of
return (TWR) for your investments for the time period requested.
IRR is always annualized due to the way it is computed, but TWR is
reported both as a rate over the chosen reporting period and as an
annual rate.
.PP
Price directives will be taken into account if you supply appropriate
\f[CR]\-\-cost\f[R] or \f[CR]\-\-value\f[R] flags (see Value reporting).
.PP
Some special cases of IRR have no solution in the usual sense, and are
reported as:
.IP \(bu 2
0%, when there are no cash flows, or when they all fall on the same day
and add up to zero (nothing is gained or lost, and no time passes)
.IP \(bu 2
\-100%, when money is put in, but nothing comes out of the investment or
is left in it (all of it is lost).
A total loss is \-100% however long the money was invested, even for a
day.
(But a partial loss within one day is an error, below, since its annual
rate depends on how much time passes.)
.PP
In some cases a rate of return can\(aqt be computed.
Then its cell in the report shows \f[CR]error\f[R], the rest of the
report is still shown, and the reasons (each with its period) are
printed after it as a warning.
The reasons can be:
.IP \(bu 2
No solution for Internal Rate of Return (IRR).
Possible causes: IRR is huge (>1000000%), balance of investment becomes
negative at some point in time.
.IP \(bu 2
No solution for Internal Rate of Return (IRR), because money only came
out of the investment in that period (or is still in it at the end), and
none was put in (counting its value at the start as put in), so the IRR
is infinite.
.IP \(bu 2
No solution for Internal Rate of Return (IRR), because all of a
period\(aqs cash flows (including the values at its start and end) fall
on the same day, so no time passes for the gain or loss to happen in.
.IP \(bu 2
Failed to find solution for Internal Rate of Return (IRR).
Either search does not converge to a solution, or converges too slowly.
.IP \(bu 2
Cannot compute the time\-weighted return for DATES (PART): the
investment\(aqs value at the start (...)
plus deposits (...)
is negative.
Possible cause: the balance of the investment becomes negative, eg more
is sold than is held (a short position).
.PP
And in some cases the whole report can\(aqt be produced:
.IP \(bu 2
Error: Could not value the investment on DATE: no market price ...
is known for COMMODITY on or before that date.
A holding has no market price, and none of the investment\(aqs
transactions on or before that date records a price for buying or
selling it.
Add a P directive for it, or record the price of its purchase.
.IP \(bu 2
Error: Period ...
has multiple commodities: ...
The investment, its cash flows or its profit and loss are in more than
one commodity.
Use \-\-value to convert them to one (eg
\f[CR]\-\-value=end,$ \-\-infer\-market\-prices\f[R]).
.PP
Examples:
.IP \(bu 2
Using roi to compute total return of investment in stocks:
https://github.com/hledgerorg/hledger/blob/main/examples/investing/roi\-unrealised.ledger
.IP \(bu 2
Cookbook > Return on Investment: https://hledger.org/roi.html
.SS Spaces and special characters in \f[CR]\-\-inv\f[R] and \f[CR]\-\-pnl\f[R]
Note that \f[CR]\-\-inv\f[R] and \f[CR]\-\-pnl\f[R]\(aqs argument is a
query, and queries could have several space\-separated terms (see
QUERIES).
.PP
To indicate that all search terms form single command\-line argument,
you will need to put them in quotes (see Special characters):
.IP
.EX
$ hledger roi \-\-inv \(aqterm1 term2 term3 ...\(aq
.EE
.PP
If any query terms contain spaces themselves, you will need an extra
level of nested quoting, eg:
.IP
.EX
$ hledger roi \-\-inv=\(dq\(aqAssets:Test 1\(aq cur:USD\(dq \-\-pnl=\(dq\(aqEquity:Unrealized Profit and Loss\(aq\(dq
.EE
.SS Semantics of \f[CR]\-\-inv\f[R] and \f[CR]\-\-pnl\f[R]
Query supplied to \f[CR]\-\-inv\f[R] has to match all transactions that
are related to your investment.
Transactions not matching \f[CR]\-\-inv\f[R] will be ignored.
.PP
In these transactions, ROI will consider postings that match
\f[CR]\-\-inv\f[R] to be \(dqinvestment postings\(dq and other postings
(not matching \f[CR]\-\-inv\f[R]) will be sorted into two categories:
\(dqcash flow\(dq and \(dqprofit and loss\(dq, as ROI needs to know
which part of the investment value is your contributions and which is
due to the return on investment.
.IP \(bu 2
\(dqCash flow\(dq is depositing or withdrawing money, buying or selling
assets, or otherwise converting between your investment commodity and
any other commodity.
Example:
.RS 2
.IP
.EX
2019\-01\-01 Investing in Snake Oil
assets:cash \-$100
investment:snake oil
2020\-01\-01 Selling my Snake Oil
assets:cash $10
investment:snake oil = 0
.EE
.RE
.IP \(bu 2
\(dqProfit and loss\(dq is change in the value of your investment:
.RS 2
.IP
.EX
2019\-06\-01 Snake Oil falls in value
investment:snake oil = $57
equity:unrealized profit or loss
.EE
.RE
.PP
All non\-investment postings are assumed to be \(dqcash flow\(dq, unless
they match \f[CR]\-\-pnl\f[R] query.
Changes in value of your investment due to \(dqprofit and loss\(dq
postings will be considered as part of your investment return.
.PP
The amount of each cash flow is measured from the investment\(aqs
perspective: it is the cost of the transaction\(aqs investment postings,
minus any profit and loss in that transaction.
Its date is the date of those investment postings, even if the
money\(aqs posting has a different date (eg a settlement date).
This means that other postings in the same transaction, such as fees,
don\(aqt change the amount of the cash flow.
.PP
In this example, the investment receives $100, so without
\f[CR]\-\-pnl\f[R] the cash flow is a $100 deposit, and the $1 fee is
not part of the investment at all.
With \f[CR]\-\-pnl expenses\f[R], the fee counts as part of the
investment\(aqs return instead: the cash flow is a $101 deposit, of
which $1 is immediately lost (shown as profit/loss of \-$1):
.IP
.EX
2019\-01\-01 Buying Snake Oil, with a fee
assets:cash \-$101
expenses:fees $1
investment:snake oil $100
.EE
.PP
Example: if you use \f[CR]\-\-inv snake \-\-pnl equity:unrealized\f[R],
then postings in the example below would be classifed as:
.IP
.EX
2019\-01\-01 Snake Oil #1
assets:cash \-$100 ; cash flow posting
investment:snake oil ; investment posting
2019\-03\-01 Snake Oil #2
equity:unrealized pnl \-$100 ; profit and loss posting
snake oil ; investment posting
2019\-07\-01 Snake Oil #3
equity:unrealized pnl ; profit and loss posting
cash \-$100 ; cash flow posting
snake oil $50 ; investment posting
.EE
.SS Using roi with lots
If your journal records lots, each disposal transaction has a realised
gain posting, by default to \f[CR]revenues:gain\f[R].
Make sure \f[CR]\-\-pnl\f[R] matches that account, eg
\f[CR]\-\-pnl revenues:gain\f[R], so realised gains are counted as
profit.
Cash flows are measured at the investment postings\(aq cost, which for
lots is their cost basis, so without \f[CR]\-\-pnl\f[R] a sale is a
withdrawal of its cost basis only, and its gain is not counted at all:
IRR and TWR will understate the return (eg showing 0% for a buy and a
sale at a profit).
.SS IRR and TWR explained
\(dqROI\(dq stands for \(dqreturn on investment\(dq.
Traditionally this was computed as a difference between current value of
investment and its initial value, expressed in percentage of the initial
value.
.PP
However, this approach is only practical in simple cases, where the
investment receives no in\-flows or out\-flows of money and the rate of
growth is fixed over time.
For more complex scenarios you need different ways to compute rate of
return, and this command implements two of them: IRR and TWR.
.PP
\f[B]Internal rate of return (IRR)\f[R], also called money\-weighted
rate of return, answers the question: \f[I]what single constant annual
interest rate, applied to your actual sequence of deposits and
withdrawals, would produce exactly the ending balance you have?\f[R]
.PP
IRR is inherently personal.
If you deposited a large sum right before a bad period, your IRR is
dragged down \- not because the investment was poorly managed, but
because your timing was bad.
Conversely, investing heavily just before a rally makes your IRR look
great.
This is what makes IRR \(dqmoney\-weighted\(dq: periods when more of
your money is at stake contribute more to the result.
.PP
In technical terms, IRR uses the same approach as computation of net
present value, and tries to find a discount rate that makes the net
present value of all the cash flows of your investment add up to zero.
The implementation in hledger produces results that match the
\f[CR]=XIRR\f[R] formula in Excel.
.PP
\f[B]Time\-weighted rate of return (TWR)\f[R] strips out the effect of
your deposit and withdrawal timing, measuring the investment\(aqs own
performance rather than your experience of it.
.PP
hledger computes TWR from the value of your investment at the end of
each day: its balance at the end of the day, valued (with
\f[CR]\-\-value\f[R]) using the prices in effect on that day.
The order of transactions and prices within a day doesn\(aqt matter.
.IP \(bu 2
The days between two days with cash flows form one stretch, which starts
at the end of the earlier cash flow day and ends at the end of the day
before the later one.
Its return is the ratio of the investment\(aqs values at those two
moments.
For example, with cash flows on March 1 and March 10, the stretch is
March 2 to 9, and its return is (value at the end of March 9) / (value
at the end of March
.RS 2
.IP "1)" 3
\(bu .RS 2
.IP "1." 3
(March 10 itself is a day with cash flows, handled as below.)
.RE
.RE
.IP \(bu 2
A day with cash flows is split in two parts:
.RS 2
.IP "1." 3
The day\(aqs price changes: the return of the holdings carried over from
the previous day, from their value at the previous day\(aqs prices to
their value at this day\(aqs prices.
(This part is skipped if no prices changed.)
.IP "2." 3
The cash flows, as if all of the day\(aqs trades were made at the
day\(aqs closing prices.
Its return is (value at the end of the day \- withdrawals) / (value
after part 1 + deposits) \- 1, with withdrawals negative.
That is, the day\(aqs deposits count as invested during this part, as if
made at its start, and its withdrawals count as still invested during
it, as if made at its end.
So any difference between the prices you traded at and the closing
prices shows up in this part\(aqs return.
.RE
.IP \(bu 2
Times when nothing is invested earn nothing.
That includes a day on which something arrives in an empty investment
only as profit and loss (eg a stock grant, booked to an account matched
by \f[CR]\-\-pnl\f[R]): there is nothing to compute a return on, so that
day\(aqs return is 0%.
.IP \(bu 2
A holding which has no market price is valued at the price of the
investment\(aqs latest purchase or sale of it, on or before that day (as
\f[CR]\-\-infer\-market\-prices\f[R] would do, but only from the
investment\(aqs own transactions, and only while no market price is
known).
If there are several on a day, the last one recorded is used.
Like any price, it applies to the whole holding on that day, including
what was held before the trade, so a trade at a new price can show up in
\f[CR]\-\-cashflow\f[R] output as a \(dqprices\(dq row, before its cash
flows.
And a trade recorded at zero cost (eg a gift, recorded with
\f[CR]\(at $0\f[R]) gives a price of 0, so such a holding is worth
nothing until a market price is known; add a P directive for it.
.PP
All these returns are then multiplied together (geometrically chained)
to give the TWR for the full period.
In multi\-period reports, each period begins with the value the previous
one ended with, so the periods\(aq returns chain to the total.
.PP
Use \f[CR]\-\-value=then\f[R] for TWR, so that each day is valued with
the prices of that day.
With \f[CR]\-\-value=end\f[R], \f[CR]\-\-value=now\f[R] or
\f[CR]\-\-value=DATE\f[R], all the values in a period use the same
prices, so its TWR only reflects recorded profit and loss and the
differences between the prices you traded at and those prices.
With \f[CR]\-\-value=end\f[R], each period is also valued with its own
end\(aqs prices, so the periods\(aq returns don\(aqt chain to the total.
.PP
TWR can only be as good as the values your journal gives for each day.
If you record changes in value only occasionally (with
\f[CR]\-\-pnl\f[R] transactions, or with sparse price directives), the
growth since the previous record is attributed to the day you record it,
and so is counted on whatever was invested on that day.
If you made a large deposit or withdrawal in between, that can make TWR
quite different from what it would be if the growth had been spread out.
So record a valuation around large deposits and withdrawals
(professional performance standards require this too), or use price
directives, or \f[CR]\-\-infer\-market\-prices\f[R] if your transactions
record their prices.
.PP
\f[B]In short:\f[R] TWR tells you how good the investment was; IRR tells
you how good your experience of the investment was.
.SS Checking the results
\f[CR]\-\-cashflow\f[R] shows everything that IRR and TWR are computed
from, so that you can check them against your journal, against other
hledger reports, or in a spreadsheet:
.IP \(bu 2
\f[B]IRR cash flows\f[R]: one row per cash flow, with the
transaction\(aqs description, the cost of its investment postings, and
its profit or loss, between the investment\(aqs value at the start and
its value at the end (dated the day after the period\(aqs last day,
since it is the value at the end of that day).
Amounts are from your point of view: what you put in is negative, what
you take out or still have is positive.
The dates and amounts can be given to Excel\(aqs \f[CR]=XIRR\f[R] as
they are.
.IP \(bu 2
\f[B]TWR returns\f[R]: one row for each stretch without cash flows, and
for each day with cash flows, a row for its price changes (if any) and a
row for its cash flows.
Each row\(aqs Value (begin) is the previous row\(aqs Value (end), and
each row\(aqs return is
.RS 2
.PP
(Value (end) \- Withdrawals) / (Value (begin) + Deposits) \- 1
.PP
where withdrawals are negative.
The Cumulative column chains the returns by multiplication: each
row\(aqs (1 + Cumulative) is the previous row\(aqs (1 + Cumulative)
times (1 + Return).
Its last row is the period\(aqs TWR.
.RE
.PP
The values can be checked with \f[CR]hledger balance\f[R]: the value at
the end of a day D is the investment\(aqs historical balance at the end
of that day, valued then.
For example, if you ran \f[CR]roi \-\-value=then,$\f[R], check the value
at the end of day D with:
.IP
.EX
$ hledger balance \-\-historical \-\-value=end,$ \-e D+1 INVESTMENTQUERY
.EE
.PP
(where \f[CR]D+1\f[R] is the day after D; \f[CR]\-\-value=end\f[R]
values at the end of the report period, which is day D).
Holdings which have no market price are the exception, as \f[CR]roi\f[R]
values them at the price of their latest purchase or sale.
.PP
\f[B]When each matters\f[R]
.PP
Use IRR when you want to know your actual personal return \- what you
earned on your money, accounting for when you chose to move it.
It is the right measure when evaluating your own deposit and withdrawal
timing decisions.
.PP
Use TWR when you want to evaluate the investment vehicle itself,
independent of your deposit timing.
It is the right measure when comparing two funds or strategies, or when
asking whether you would have been better off elsewhere.
TWR is the standard that professional investment managers use to report
fund performance, precisely because it removes the distortion caused by
investor cash flows.
.PP
References:
.IP \(bu 2
Explanation of rate of return
.IP \(bu 2
Explanation of IRR
.IP \(bu 2
Explanation of TWR
.IP \(bu 2
IRR vs TWR
.IP \(bu 2
Examples of computing IRR and TWR and discussion of the limitations of
both metrics
.SS stats
Show journal and performance statistics.
.IP
.EX
Flags:
\-q \-\-oneline show a single line of output
\-v \-\-verbose show more detailed output
\-o \-\-output\-file=FILE write output to FILE.
.EE
.PP
The stats command shows summary information for the whole journal, or a
matched part of it.
With a reporting interval, it shows a report for each report period.
.PP
It also shows some performance statistics:
.IP \(bu 2
how long the program ran for
.IP \(bu 2
the number of transactions processed per second
.IP \(bu 2
the peak live memory in use by the program to do its work
.IP \(bu 2
the peak allocated memory as seen by the program
.PP
By default, the output is reasonably discreet; it reveals the main file
name, your activity level, and the speed of your machine.
.PP
With \f[CR]\-v/\-\-verbose\f[R], more details are shown: the full paths
of all files, and the names of the commodities you work with.
.PP
With \f[CR]\-q/\-\-oneline\f[R], only one line of output is shown, in a
machine\-friendly tab\-separated format: the program version, the main
journal file name, and the performance stats,
.PP
The run time of \f[CR]stats\f[R] is similar to that of a balance report.
.PP
Example:
.IP
.EX
$ hledger stats \-f examples/1ktxns\-1kaccts.journal
Main file : .../1ktxns\-1kaccts.journal
Included files : 0
Txns span : 2000\-01\-01 to 2002\-09\-27 (1000 days)
Last txn : 2002\-09\-26 (7827 days ago)
Txns : 1000 (1.0 per day)
Txns last 30 days : 0 (0.0 per day)
Txns last 7 days : 0 (0.0 per day)
Payees/descriptions : 1000
Accounts : 1000 (depth 10)
Commodities : 26
Base currency : B
Market prices : 1000
Runtime stats : 0.12 s elapsed, 8266 txns/s, 4 MB live, 16 MB alloc
.EE
.IP
.EX
$ hledger stats \-q \-f examples/10ktxns\-1kaccts.journal
1.50.99\-g0835a2485\-20251119, mac\-aarch64 10ktxns\-1kaccts.journal 0.66 s elapsed 15244 txns/s 28 MB live 86 MB alloc
.EE
.PP
This command supports the \-o/\-\-output\-file option (but not
\-O/\-\-output\-format).
.SS tags
List the tag names used or declared in the journal, or their values.
.IP
.EX
Flags:
\-\-used list tags used
\-\-declared list tags declared
\-\-undeclared list tags used but not declared
\-\-unused list tags declared but not used
\-\-find list the first tag whose name is matched by the
first argument (a case\-insensitive infix regexp)
\-\-values list tag values instead of tag names
\-\-parsed show them in the order they were parsed (mostly),
including duplicates
\-\-directives show tag names as tag directives, for use in
journals
.EE
.PP
This command lists tag names \- all of them by default, or just the ones
which have been used on transactions/postings/accounts, or declared with
\f[CR]tag\f[R] directives, or used but not declared, or declared but not
used, or just the first one matched by a pattern (with
\f[CR]\-\-find\f[R], returning a non\-zero exit code if it fails).
.PP
Note this command\(aqs non\-standard first argument: it is a
case\-insensitive infix regular expression for matching tag names, which
limits the tags shown.
Any additional arguments are standard query arguments, which limit the
transactions, postings, or accounts providing tags.
.PP
With \f[CR]\-\-values\f[R], the tags\(aq unique non\-empty values are
listed instead.
.PP
With \f[CR]\-E\f[R]/\f[CR]\-\-empty\f[R], blank/empty values are also
shown.
.PP
With \f[CR]\-\-parsed\f[R], tags or values are shown in the order they
were parsed, with duplicates included.
(Except, tags from account declarations are always shown first.)
.PP
With \f[CR]\-\-directives\f[R], tag names are shown as valid tag
directives, which could be pasted into a journal file.
.PP
Remember that accounts also acquire tags from their parents; postings
also acquire tags from their account and transaction; and transactions
also acquire tags from their postings.
.PP
Examples:
.IP
.EX
$ hledger tags
broker
receipt
trip
.EE
.IP
.EX
$ hledger tags \-\-values
acme
paris
.EE
.SS transactions
(tx)
.PP
List transactions, one per line.
.IP
.EX
Flags:
\-m \-\-match=DESC fuzzy search for one recent transaction with
description closest to DESC
.EE
.PP
This command shows each transaction\(aqs first line only (the date,
status, code, description, and any same\-line comment), giving a compact
overview of a journal, in the manner of \f[CR]git log \-\-oneline\f[R].
You can add a query to select a subset of transactions.
(To see full journal entries, use the \f[CR]print\f[R] command.)
.PP
Example:
.IP
.EX
$ hledger transactions \-f examples/sample.journal
2008\-01\-01 income
2008\-06\-01 gift
2008\-06\-02 save
2008\-06\-03 * eat & shop
2008\-12\-31 * pay off
.EE
.SH Maintenance commands
.SS setup
Check the status of the hledger installation.
.IP
.EX
Flags:
no command\-specific flags
.EE
.PP
\f[CR]setup\f[R] tests your hledger installation and prints a list of
results, sometimes with helpful hints.
This is a good first command to run after installing hledger.
Also after upgrading, or when something\(aqs not working, or just when
you want a reminder of where things are.
.PP
It makes one network request to detect the latest hledger release
version.
It\(aqs ok if this fails or times out.
It will use ANSI color by default, unless disabled by NO_COLOR or
\-\-color=n.
It does not use a pager or a config file.
.PP
It expects that the hledger version you are running is installed in your
PATH.
If not, it will stop until you have done that (to keep things simple).
.PP
Example:
.IP
.EX
$ hledger setup
Checking your setup (and contacting hledger.org to find out the current release):
hledger
is running on macos 27.0 on aarch64
is built with a supported compiler/RTS yes ghc 9.14.1, using threaded RTS
is a native binary for this machine ? yes aarch64
is a released version ? yes hledger 1.52.4, mac\-aarch64
is up to date ? checking latest... yes latest is 1.52.4, 1.52.4 is installed
is installed in PATH (this version) ? yes /Users/user/.local/bin/hledger
has a system text encoding configured ? yes UTF\-8, data files must use this encoding
has a user config file ? yes /Users/user/.hledger.conf
has a local config file ? no
the config file is readable ? yes
terminal
the TERM variable is defined ? yes xterm\-256color
the terminal supports ANSI color ? yes
...
journal
the LEDGER_FILE variable is defined ? yes /Users/user/finance/main.journal
a default journal file is readable ? yes /Users/user/finance/main.journal
...
.EE
.SS init
Create starter files for a new hledger setup, or add missing ones to an
existing setup.
.IP
.EX
Flags:
\-\-layout=LAYOUT which file layout to write: simple, default, years
(default: default)
\-\-dry\-run just show the files that would be created
.EE
.PP
With no argument, or a directory argument, \f[CR]init\f[R] writes a set
of files in that directory (the current directory by default), creating
it if needed.
Which files depends on the layout chosen with \f[CR]\-\-layout\f[R].
Note, these are just to help you get started; you can always change the
file layout to suit your needs.
.PP
\f[B]simple\f[R]:
.PP
Just one file.
Good if you want simplicity and manual data entry.
.IP \(bu 2
\f[CR]main.journal\f[R] \- the journal file, with optional declarations
.PP
\f[B]default\f[R] (the default):
.PP
Declarations are kept separate; subdirectories and starter scripts for
data\-fetching are provided.
This is a good maintainable layout that hledger commands understand
well.
.IP \(bu 2
\f[CR]main.journal\f[R] \- the main journal file, with a few example
transactions
.IP \(bu 2
\f[CR]accounts.journal\f[R], \f[CR]commodities.journal\f[R],
\f[CR]payees.journal\f[R] \- declarations
.IP \(bu 2
\f[CR]data/\f[R] \- downloaded CSV files go here, with
\f[CR]data/getdata\f[R], a starter script for get
.IP \(bu 2
\f[CR]prices/\f[R] \- market prices go here, with
\f[CR]prices/getprices\f[R], a starter script for get
.IP \(bu 2
\f[CR]rules/\f[R] \- CSV rules files go here
.IP \(bu 2
an example CSV file and rules file
.PP
\f[B]years\f[R]:
.PP
Like default, but each year has its own journal file.
This gives you a choice of loading all years or one year at a time (see
close).
It makes life a little more complicated, but it is worthwhile if you
have enough data that a single file becomes slow on your machine; or if
you want to compartmentalise the data for other reasons.
.IP \(bu 2
\f[CR]YEAR.journal\f[R] (eg \f[CR]2026.journal\f[R]) \- this year\(aqs
journal, with a few example transactions.
.IP \(bu 2
\f[CR]all.journal\f[R] \- includes all the year journals, for
multi\-year reports
.IP \(bu 2
the same declaration files, directories and examples as default
.PP
With a journal file argument (a path ending with \f[CR].journal\f[R],
\f[CR].j\f[R], \f[CR].hledger\f[R] or \f[CR].ledger\f[R]), you\(aqll get
the simple layout, written to that file.
.PP
Files that already exist are never changed; they are skipped, with a
warning.
So you can run \f[CR]init\f[R] again to add missing files.
After writing the files, it suggests some next steps.
.PP
These and other file layouts can also be seen in the hledger repo\(aqs
examples/file\-layouts directory.
.PP
Examples:
.IP
.EX
$ hledger init \-\-dry\-run # show what would be created in the current directory
$ hledger init \(ti/finance # create a standard setup in \(ti/finance
$ hledger init \-\-layout years \(ti/finance # create a setup with a journal per year in \(ti/finance
$ hledger init 2026.journal # create a single journal file
.EE
.SS check
Check that your data is valid, using hledger\(aqs built\-in correctness
checks.
.IP
.EX
Flags:
no command\-specific flags
.EE
.PP
hledger provides a number of built\-in correctness checks to help
validate your data and prevent errors.
Some are run automatically, some when you enable \f[CR]\-\-strict\f[R]
mode; or you can run any of them on demand by providing them as
arguments to the \f[CR]check\f[R] command.
\f[CR]check\f[R] produces no output and a zero exit code if all is well.
Eg:
.IP
.EX
hledger check # run default checks
hledger check \-s # run default and strict checks
hledger check ordereddates payees # run default checks and two others
hledger check \(aqassert none daily type:A balance:<0\(aq # run default checks and a custom rule
.EE
.PP
If you are an Emacs user, you can also configure flycheck\-hledger to
run these checks, providing instant feedback as you edit the journal.
.PP
Here are the checks currently available.
They are generally checked in the order they are shown here, and only
the first failure will be reported.
.SS Default checks
These important checks are performed by default, by almost all hledger
commands:
.IP \(bu 2
\f[B]parseable\f[R] \- data files are in a supported format, with no
syntax errors and no invalid include directives.
This ensures that all files exist and are readable.
.IP \(bu 2
\f[B]autobalanced\f[R] \- all transactions are balanced, after
automatically inferring missing amounts and conversion rates and then
converting amounts to cost.
This ensures that each transaction\(aqs journal entry is well formed.
.IP \(bu 2
\f[B]assertions\f[R] \- all balance assertions and assert directives in
the journal are passing.
Balance assertions are a strong defense against errors, catching many
problems; assert directives check standing rules, like \(dqno asset
account is ever negative\(dq.
This check is on by default, but if it gets in your way, you can disable
it temporarily with \f[CR]\-I\f[R] or \f[CR]\-\-ignore\-assertions\f[R],
or as a default by adding that flag to your config file.
If you put it in your config file, you can override that with
\f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R] or
\f[CR]hledger check assertions\f[R].
When a journal has both kinds of problem, lot errors are reported before
assertion failures, and balance assertion failures before assert
directive failures.
.IP \(bu 2
\f[B]lots\f[R] \- all lot entries are valid.
Checks lot posting classifications, lot movements, that an acquisition
writing both a cost basis and a transacted cost has them agree (a
mismatch would silently miscalculate gains), and that any user\-written
realised gain amount on a disposal matches the calculated gain.
This check can be disabled by \f[CR]\-I\f[R] or
\f[CR]\-\-ignore\-lots\f[R].
If you put it in your config file, you can override that with
\f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R] or \f[CR]hledger check lots\f[R].
.SS Strict checks
When the \f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R] flag is used (AKA strict
mode), all commands will perform the following additional checks.
These provide extra error\-catching power to help you keep your data
clean and correct:
.IP \(bu 2
\f[B]balanced\f[R] \- like \f[CR]autobalanced\f[R], but implicit
conversions between commodities are not allowed; all conversion
transactions must use cost notation or equity postings.
This prevents wrong conversions caused by typos.
.IP \(bu 2
\f[B]commodities\f[R] \- all commodity symbols used must be declared.
This guards against mistyping or omitting commodity symbols.
.IP \(bu 2
\f[B]accounts\f[R] \- all account names used must be declared.
This prevents the use of mis\-spelled or outdated account names.
(Except lot subaccounts, like \f[CR]:{2026\-01\-15, $50}\f[R], which are
automatically exempt; only their base account needs to be declared.
And the accounts of postings generated by hledger, such as equity
conversion, gain, and imbalance postings.)
.PP
Also, strict mode ensures that the \f[CR]assertions\f[R] and
\f[CR]lots\f[R] checks run (overriding their ignore flags).
.SS Other checks
These are not wanted by everyone, but can be run using the
\f[CR]check\f[R] command:
.IP \(bu 2
\f[B]tags\f[R] \- all tags used must be declared (tags on transactions,
postings, and account and commodity directives; except the special
tags).
This prevents mis\-spelled tag names.
Note hledger fairly often finds unintended tags in comments.
.IP \(bu 2
\f[B]payees\f[R] \- all payees used in transactions must be declared.
This will force you to declare any new payee name before using it.
Most people will probably find this a bit too strict.
.IP \(bu 2
\f[B]ordereddates\f[R] \- within each file, transactions must be ordered
by date.
(Forecast transactions are not checked.)
This is a simple and effective error catcher.
It\(aqs not included in strict mode, but you can add it by running
\f[CR]hledger check \-s ordereddates\f[R].
If enabled, this check is performed before balance assertions.
.IP \(bu 2
\f[B]recentassertions\f[R] \- all accounts with balance assertions must
have one that\(aqs within the 7 days before their latest posting.
This will encourage adding balance assertions for your active
asset/liability accounts, which in turn should encourage you to
reconcile regularly with those real world balances \- another strong
defense against errors.
(\f[CR]hledger close \-\-assert >>$LEDGER_FILE\f[R] is a convenient way
to add new balance assertions.
Later these become quite redundant, and you might choose to remove them
to reduce clutter.)
.IP \(bu 2
\f[B]uniqueleafnames\f[R] \- no two accounts may have the same last
account name part (eg the \f[CR]checking\f[R] in
\f[CR]assets:bank:checking\f[R]).
This ensures each account can be matched by a unique short name, easier
to remember and to type.
.SS Assert rules
You can also check custom rules, written like assert directives.
Give each one as a single quoted argument, written exactly as the
directive would be written in the journal.
Eg:
.IP
.EX
hledger check \(aqassert none daily type:A balance:<0\(aq
hledger check \(aqassert some monthly income:salary\(aq \(aqassert none assets:oldbank date:2025\-\(aq
.EE
.PP
This is a convenient way to try out a rule before adding it to the
journal, or to check rules you don\(aqt want to keep there.
Unlike assert directives, these rules check all of the data files read,
combined (not each file tree separately), and they are checked even with
\f[CR]\-I\f[R].
They are checked after any other checks requested.
(A plain \f[CR]assert\f[R] argument, with nothing after it, is short for
the \f[CR]assertions\f[R] check.)
.SS Custom checks
You can build your own custom checks with add\-on command scripts.
See also Cookbook > Scripting.
Here are some examples from hledger/bin/:
.IP \(bu 2
\f[B]hledger\-check\-tagfiles\f[R] \- all tag values containing
\f[CR]/\f[R] exist as file paths
.SS diff
Compare a particular account\(aqs transactions in two input files.
It shows any transactions to this account which are in one file but not
in the other.
.IP
.EX
Flags:
no command\-specific flags
.EE
.PP
More precisely: for each posting affecting this account in either file,
this command looks for a corresponding posting in the other file which
posts the same amount to the same account (ignoring date, description,
etc).
.PP
Since it compares postings, not transactions, this also works when
multiple bank transactions have been combined into a single journal
entry.
.PP
This command is useful eg if you have downloaded an account\(aqs
transactions from your bank (eg as CSV data): when hledger and your bank
disagree about the account balance, you can compare the bank data with
your journal to find out the cause.
.PP
Examples:
.IP
.EX
$ hledger diff \-f $LEDGER_FILE \-f bank.csv assets:bank:giro
These transactions are in the first file only:
2014/01/01 Opening Balances
assets:bank:giro EUR ...
...
equity:opening balances EUR \-...
These transactions are in the second file only:
.EE
.SH Data generation commands
.SS close
(equity)
.PP
Print several kinds of \(dqclosing\(dq and/or \(dqopening\(dq
transactions, useful eg when migrating balances to a new journal file,
retaining earnings into equity, consolidating balances, or viewing lot
costs.
Like \f[CR]print\f[R], it prints valid journal entries.
You can copy these into your journal file(s) when you are happy with how
they look.
.IP
.EX
Flags:
\-\-clopen[=TAGVAL] show closing and opening balances transactions,
for AL accounts by default
\-\-close[=TAGVAL] show just a closing balances transaction
\-\-open[=TAGVAL] show just an opening balances transaction
\-\-assert[=TAGVAL] show a balance assertions transaction
\-\-assign[=TAGVAL] show a balance assignments transaction
\-\-retain[=TAGVAL] show a retain earnings transaction, for RX
accounts by default
\-x \-\-explicit show all amounts explicitly
\-\-show\-costs show amounts with different costs separately
\-\-interleaved show source and destination postings together
\-\-assertion\-type=TYPE =, ==, =* or ==*
\-\-close\-desc=DESC set closing transaction\(aqs description
\-\-close\-acct=ACCT set closing transaction\(aqs destination account
\-\-open\-desc=DESC set opening transaction\(aqs description
\-\-open\-acct=ACCT set opening transaction\(aqs source account
\-\-round=TYPE how much rounding or padding should be done when
displaying amounts ?
none \- show original decimal digits,
as in journal (default)
soft \- just add or remove decimal zeros
to match precision
hard \- round posting amounts to precision
(can unbalance transactions)
all \- also round cost amounts to precision
(can unbalance transactions)
\-\-layout=hledger1|COL how should posting amounts be aligned ?
hledger1 \- right\-align amounts, as in hledger 1
COL \- align decimal marks at column COL
(default: 53)
.EE
.PP
\f[CR]close\f[R] has six modes, selected by choosing one of the mode
flags: \f[CR]\-\-clopen\f[R], \f[CR]\-\-close\f[R] (default),
\f[CR]\-\-open\f[R], \f[CR]\-\-assert\f[R], \f[CR]\-\-assign\f[R], or
\f[CR]\-\-retain\f[R].
They are all doing the same kind of operation, but with different
defaults for different situations.
.PP
The journal entries generated by \f[CR]close\f[R] will have a
\f[CR]clopen:\f[R] tag, which is helpful when you want to exclude them
from reports.
If the main journal file name contains a number, the tag\(aqs value will
be that base file name with the number incremented.
Eg if the journal file is 2025.journal, the tag will be
\f[CR]clopen:2026\f[R].
Or you can set the tag value by providing an argument to the mode flag.
Eg \f[CR]\-\-close=foo\f[R] or \f[CR]\-\-clopen=2025\-main\f[R].
.SS close \-\-clopen
This is useful if migrating balances to a new journal file at the start
of a new year.
It prints a \(dqclosing balances\(dq transaction that zeroes out account
balances (Asset and Liability accounts, by default), and an opposite
\(dqopening balances\(dq transaction that restores them again.
Typically, you would run
.IP
.EX
hledger close \-\-clopen \-e NEWYEAR >> $LEDGER_FILE
.EE
.PP
and then move the opening transaction from the old file to the new file
(and probably also update your LEDGER_FILE environment variable).
.PP
Why might you do this ?
If your reports are fast, you may not need it.
But at some point you will probably want to partition your data by time,
for performance or data integrity or regulatory reasons.
A new file or set of files per year is common.
Then, having each file/fileset \(dqbookended\(dq with opening and
closing balance transactions will allow you to freely pick and choose
which files to read \- just the current year, any past year, any
sequence of years, or all of them \- while showing correct account
balances in each case.
The earliest opening balances transaction sets correct starting
balances, and any later closing/opening pairs will harmlessly cancel
each other out.
.PP
The balances will be transferred to and from
\f[CR]equity:opening/closing balances\f[R] by default.
You can override this by using \f[CR]\-\-close\-acct\f[R] and/or
\f[CR]\-\-open\-acct\f[R].
.PP
You can select a different set of accounts to close/open by providing an
account query.
Eg to add Equity accounts, provide arguments like
\f[CR]assets liabilities equity\f[R] or \f[CR]type:ALE\f[R].
When migrating to a new file, you\(aqll usually want to bring along the
AL or ALE accounts, but not the RX accounts (Revenue, Expense).
.PP
Assertions will be added indicating and checking the new balances of the
closed/opened accounts.
.SS close \-\-close
This prints just the closing balances transaction of
\f[CR]\-\-clopen\f[R].
It is the default if you don\(aqt specify a mode.
.PP
More customisation options are described below.
Among other things, you can use \f[CR]close \-\-close\f[R] to generate a
transaction moving the balances from any set of accounts, to a different
account.
(If you need to move just a portion of the balance, see hledger\-move.)
.SS close \-\-open
This prints just the opening balances transaction of
\f[CR]\-\-clopen\f[R].
(It is similar to Ledger\(aqs equity command.)
.SS close \-\-assert
This prints a transaction that asserts the account balances as they are
on the end date (and adds an \f[CR]assert:\f[R] tag).
It could be useful as documention and to guard against changes.
.SS close \-\-assign
This prints a transaction that assigns the account balances as they are
on the end date (and adds an \(dqassign:\(dq tag).
Unlike balance assertions, assignments will post changes to balances as
needed to reach the specified amounts.
.PP
This is another way to set starting balances when migrating to a new
file, and it will set them correctly even in the presence of earlier
files which do not have a closing balances transaction.
However, it can hide errors, and disturb the accounting equation, so
\f[CR]\-\-clopen\f[R] is usually recommended.
.SS close \-\-retain
This is like \f[CR]\-\-close\f[R], but it closes Revenue and Expense
account balances by default.
They will be transferred to \f[CR]equity:retained earnings\f[R], or
another account specified with \f[CR]\-\-close\-acct\f[R].
.PP
Revenues and expenses correspond to changes in equity.
They are categorised separately for reporting purposes, but
traditionally at the end of each accounting period, businesses
consolidate them into equity, This is called \(dqretaining earnings\(dq,
or \(dqclosing the books\(dq.
.PP
In personal accounting, there\(aqs not much reason to do this, and most
people don\(aqt.
(One reason to do it is to help the \f[CR]balancesheetequity\f[R] report
show a zero total, demonstrating that the accounting equation (A\-L=E)
is satisfied.)
.SS close customisation
In all modes, the following things can be overridden:
.IP \(bu 2
the accounts to be closed/opened, with account query arguments
.IP \(bu 2
the closing/opening dates, with \f[CR]\-e OPENDATE\f[R]
.IP \(bu 2
the balancing account, with \f[CR]\-\-close\-acct=ACCT\f[R] and/or
\f[CR]\-\-open\-acct=ACCT\f[R]
.IP \(bu 2
the transaction descriptions, with \f[CR]\-\-close\-desc=DESC\f[R] and
\f[CR]\-\-open\-desc=DESC\f[R]
.IP \(bu 2
the transactions\(aq \f[CR]clopen\f[R] tag value, with a
\f[CR]TAGVAL\f[R] argument for the mode flag (see above).
.PP
By default, the closing date is yesterday, or the journal\(aqs end date,
whichever is later; and the opening date is always one day after the
closing date.
You can change these by specifying a report end date; the closing date
will be the last day of the report period.
Eg \f[CR]\-e 2024\f[R] means \(dqclose on 2023\-12\-31, open on
2024\-01\-01\(dq.
.PP
With \f[CR]\-\-x/\-\-explicit\f[R], the balancing amount will be shown
explicitly, and if it involves multiple commodities, a separate posting
will be generated for each of them (similar to \f[CR]print \-x\f[R]).
.PP
With \f[CR]\-\-interleaved\f[R], each individual transfer is shown with
source and destination postings next to each other (perhaps useful for
troubleshooting).
.PP
With \f[CR]\-\-show\-costs\f[R], balances\(aq costs are also shown, with
different costs kept separate.
This may generate very large journal entries, if you have many currency
conversions or investment transactions.
\f[CR]close \-\-show\-costs\f[R] is currently the best way to view
investment lots with hledger.
(To move or dispose of lots, see the more capable
\f[CR]hledger\-move\f[R] script.)
With \f[CR]\-\-lots\f[R], lot subaccount balances are always shown
without costs, even under \f[CR]\-\-show\-costs\f[R]: their cost
information is carried by the lot name itself, and transacted costs on
lot postings would prevent the output from being read back.
For lots using the AVERAGE or AVERAGEALL cost basis method, whose lot
names normally leave out the cost, the pool\(aqs average cost as of the
closing date is added to each lot name (eg
\f[CR]{2026\-01\-15, $55}\f[R]), so that the output can be read back, eg
to start a new file.
A non\-terminating average is written with up to 8 decimal places, so
the re\-opened lots\(aq total cost basis may differ from the original by
a tiny amount.
.SS close and balance assertions
\f[CR]close\f[R] adds balance assertions verifying that the accounts
have been reset to zero in a closing transaction or restored to their
previous balances in an opening transaction.
These provide useful error checking, but you can ignore them temporarily
with \f[CR]\-I\f[R], or remove them if you prefer.
.PP
With \f[CR]\-\-lots\f[R], balance assertions are not generated for the
lot subaccount postings in closing transactions (assertions on lot
postings get confusing, because they apply to the parent account).
.PP
Single\-commodity, subaccount\-exclusive balance assertions
(\f[CR]=\f[R]) are generated by default.
This can be changed with \f[CR]\-\-assertion\-type=\(aq==*\(aq\f[R]
(eg).
.PP
When running \f[CR]close\f[R] you should probably avoid using
\f[CR]\-C\f[R], \f[CR]\-R\f[R], \f[CR]status:\f[R] (filtering by status
or realness) or \f[CR]\-\-auto\f[R] (generating postings), since the
generated balance assertions would then require these.
.PP
Transactions with multiple dates (eg posting dates) spanning the file
boundary also can disrupt the balance assertions:
.IP
.EX
2023\-12\-30 a purchase made in december, cleared in january
expenses:food 5
assets:bank:checking \-5 ; date: 2023\-01\-02
.EE
.PP
To solve this you can transfer the money to and from a temporary
account, splitting the multi\-day transaction into two single\-day
transactions:
.IP
.EX
; in 2022.journal:
2022\-12\-30 a purchase made in december, cleared in january
expenses:food 5
equity:pending \-5
; in 2023.journal:
2023\-01\-02 last year\(aqs transaction cleared
equity:pending 5 = 0
assets:bank:checking \-5
.EE
.SS close examples
.SS Retain earnings
Record 2022\(aqs revenues/expenses as retained earnings on 2022\-12\-31,
appending the generated transaction to the journal:
.IP
.EX
$ hledger close \-\-retain \-f 2022.journal \-p 2022 >> 2022.journal
.EE
.PP
After this, to see 2022\(aqs revenues and expenses you must exclude the
retain earnings transaction:
.IP
.EX
$ hledger \-f 2022.journal is not:desc:\(aqretain earnings\(aq
.EE
.SS Migrate balances to a new file
Close assets/liabilities on 2022\-12\-31 and re\-open them on
2023\-01\-01:
.IP
.EX
$ hledger close \-\-clopen \-f 2022.journal \-p 2022
# copy/paste the closing transaction to the end of 2022.journal
# copy/paste the opening transaction to the start of 2023.journal
.EE
.PP
After this, to see 2022\(aqs end\-of\-year balances you must exclude the
closing balances transaction:
.IP
.EX
$ hledger \-f 2022.journal bs not:desc:\(aqclosing balances\(aq
.EE
.PP
For more flexibility, it helps to tag closing and opening transactions
with eg \f[CR]clopen:NEWYEAR\f[R], then you can ensure correct balances
by excluding all opening/closing transactions except the first, like so:
.IP
.EX
$ hledger bs \-Y \-f 2021.j \-f 2022.j \-f 2023.j expr:\(aqtag:clopen=2021 or not tag:clopen\(aq
$ hledger bs \-Y \-f 2021.j \-f 2022.j expr:\(aqtag:clopen=2021 or not tag:clopen\(aq
$ hledger bs \-Y \-f 2022.j \-f 2023.j expr:\(aqtag:clopen=2022 or not tag:clopen\(aq
$ hledger bs \-Y \-f 2021.j expr:\(aqtag:clopen=2021 or not tag:clopen\(aq
$ hledger bs \-Y \-f 2022.j expr:\(aqtag:clopen=2022 or not tag:clopen\(aq
$ hledger bs \-Y \-f 2023.j # unclosed file, no query needed
.EE
.SS More detailed close examples
See examples/multi\-year.
.SS rewrite
Print all transactions, adding auto postings to some of them.
For now the only rewrite available is adding new postings, like print
\-\-auto.
.IP
.EX
Flags:
\-\-add\-posting=\(aqACCT AMTEXPR\(aq add a posting to ACCT, which may be
parenthesised. AMTEXPR is either a literal
amount, or *N which means the transaction\(aqs
first matched amount multiplied by N (a
decimal number). Two spaces separate ACCT
and AMTEXPR.
\-\-diff generate diff suitable as an input for
patch tool
\-\-verbose\-tags add tags indicating generated/modified
data
\-\-layout=hledger1|COL how should posting amounts be aligned ?
hledger1 \- right\-align amounts, as in
hledger 1
COL \- align decimal marks at column
COL (default: 53)
.EE
.PP
This is a start at a generic rewriter of transaction entries.
It reads the default journal and prints the transactions, like print,
but adds one or more specified postings to any transactions matching
QUERY.
The posting amounts can be fixed, or a multiplier of the existing
transaction\(aqs first posting amount.
.PP
Examples:
.IP
.EX
$ hledger\-rewrite.hs \(haincome \-\-add\-posting \(aq(liabilities:tax) *.33 ; income tax\(aq \-\-add\-posting \(aq(reserve:gifts) $100\(aq
$ hledger\-rewrite.hs expenses:gifts \-\-add\-posting \(aq(reserve:gifts) *\-1\(dq\(aq
$ hledger\-rewrite.hs \-f rewrites.hledger
.EE
.PP
rewrites.hledger may consist of entries like:
.IP
.EX
= \(haincome amt:<0 date:2017
(liabilities:tax) *0.33 ; tax on income
(reserve:grocery) *0.25 ; reserve 25% for grocery
(reserve:) *0.25 ; reserve 25% for grocery
.EE
.PP
Note the single quotes to protect the dollar sign from bash, and the two
spaces between account and amount.
.PP
More:
.IP
.EX
$ hledger rewrite [QUERY] \-\-add\-posting \(dqACCT AMTEXPR\(dq ...
$ hledger rewrite \(haincome \-\-add\-posting \(aq(liabilities:tax) *.33\(aq
$ hledger rewrite expenses:gifts \-\-add\-posting \(aq(budget:gifts) *\-1\(dq\(aq
$ hledger rewrite \(haincome \-\-add\-posting \(aq(budget:foreign currency) *0.25 JPY; diversify\(aq
.EE
.PP
Argument for \f[CR]\-\-add\-posting\f[R] option is a usual posting of
transaction with an exception for amount specification.
More precisely, you can use \f[CR]\(aq*\(aq\f[R] (star symbol) before
the amount to indicate that that this is a factor for an amount of
original matched posting.
If the amount includes a commodity name, the new posting amount will be
in the new commodity; otherwise, it will be in the matched posting
amount\(aqs commodity.
.SS Re\-write rules in a file
During the run this tool will execute so called \(dqAutomated
Transactions\(dq found in any journal it process.
I.e instead of specifying this operations in command line you can put
them in a journal file.
.IP
.EX
$ rewrite\-rules.journal
.EE
.PP
Make contents look like this:
.IP
.EX
= \(haincome
(liabilities:tax) *.33
= expenses:gifts
budget:gifts *\-1
assets:budget *1
.EE
.PP
Note that \f[CR]\(aq=\(aq\f[R] (equality symbol) that is used instead of
date in transactions you usually write.
It indicates the query by which you want to match the posting to add new
ones.
.IP
.EX
$ hledger rewrite \-f input.journal \-f rewrite\-rules.journal > rewritten\-tidy\-output.journal
.EE
.PP
This is something similar to the commands pipeline:
.IP
.EX
$ hledger rewrite \-f input.journal \(aq\(haincome\(aq \-\-add\-posting \(aq(liabilities:tax) *.33\(aq \(rs
| hledger rewrite \-f \- expenses:gifts \-\-add\-posting \(aqbudget:gifts *\-1\(aq \(rs
\-\-add\-posting \(aqassets:budget *1\(aq \(rs
> rewritten\-tidy\-output.journal
.EE
.PP
It is important to understand that relative order of such entries in
journal is important.
You can re\-use result of previously added postings.
.SS Diff output format
To use this tool for batch modification of your journal files you may
find useful output in form of unified diff.
.IP
.EX
$ hledger rewrite \-\-diff \-f examples/sample.journal \(aq\(haincome\(aq \-\-add\-posting \(aq(liabilities:tax) *.33\(aq
.EE
.PP
Output might look like:
.IP
.EX
\-\-\- /tmp/examples/sample.journal
+++ /tmp/examples/sample.journal
\(at\(at \-28,13 +28,15 \(at\(at
; declare commodities:
; commodity $
\-2008/01/01 income
\- assets:bank:checking $1
+2008\-01\-01 income
+ assets:bank:checking $1
income:salary
+ (liabilities:tax) $0
\-2008/06/01 gift
\- assets:bank:checking $1
+2008\-06\-01 gift
+ assets:bank:checking $1
income:gifts
+ (liabilities:tax) $0
2008/06/02 save
assets:bank:saving $1
.EE
.PP
If you\(aqll pass this through \f[CR]patch\f[R] tool you\(aqll get
transactions containing the posting that matches your query be updated.
Note that multiple files might be update according to list of input
files specified via \f[CR]\-\-file\f[R] options and \f[CR]include\f[R]
directives inside of these files.
.PP
Changed transactions are re\-rendered in \f[CR]print\f[R]\(aqs standard
format, so the diff shows any reformatting as well as the postings you
added: amounts are realigned, and dates are written with \f[CR]\-\f[R]
separators.
Transactions you didn\(aqt change are left exactly as they are.
\f[CR]\-\-layout\f[R] selects the amount alignment, so choosing one
which matches your journal will keep the diff small.
Here is the example above again, with \f[CR]\-\-layout=26\f[R] to match
this journal\(aqs own alignment:
.IP
.EX
\(at\(at \-28,13 +28,15 \(at\(at
; declare commodities:
; commodity $
\-2008/01/01 income
+2008\-01\-01 income
assets:bank:checking $1
income:salary
+ (liabilities:tax) $0
\-2008/06/01 gift
+2008\-06\-01 gift
assets:bank:checking $1
income:gifts
+ (liabilities:tax) $0
2008/06/02 save
assets:bank:saving $1
.EE
.PP
Only transactions which exist as journal entries in a file can be
patched this way.
Transactions read from other data formats, such as CSV or timeclock, and
transactions generated by a periodic transaction rule, have no journal
entry of their own; these are left out of the diff, and reported on
stderr.
To rewrite those, convert them to journal entries first, eg with
\f[CR]hledger print\f[R] or \f[CR]hledger import\f[R].
.PP
Be careful.
Whole transaction being re\-formatted in a style of output from
\f[CR]hledger print\f[R].
.PP
See also:
.PP
https://github.com/hledgerorg/hledger/issues/99
.SS rewrite vs. print \-\-auto
This command predates print \-\-auto, and currently does much the same
thing, but with these differences:
.IP \(bu 2
with multiple files, rewrite lets rules in any file affect all other
files.
print \-\-auto uses standard directive scoping; rules affect only child
files.
.IP \(bu 2
rewrite\(aqs query limits which transactions can be rewritten; all are
printed.
print \-\-auto\(aqs query limits which transactions are printed.
.IP \(bu 2
rewrite applies rules specified on command line or in the journal.
print \-\-auto applies rules specified in the journal.
.PP
.SH PART 3: DATA FORMATS
.SH Journal
hledger\(aqs usual data source is a plain text file containing journal
entries in hledger \f[CR]journal\f[R] format.
If you\(aqre looking for a quick reference, jump ahead to the journal
cheatsheet.
.PP
This file represents an accounting General Journal.
The \f[CR].journal\f[R] file extension is most often used, though not
strictly required.
The journal file contains a number of transaction entries, each
describing a transfer of money (or any commodity) between two or more
named accounts, in a simple format readable by both hledger and humans.
.PP
hledger\(aqs journal format is compatible with most of Ledger\(aqs
journal format, but not all of it.
The differences and interoperation tips are described at hledger and
Ledger.
With some care, and by avoiding incompatible features, you can keep your
hledger journal readable by Ledger and vice versa.
This can useful eg for comparing the behaviour of one app against the
other.
.PP
You can use hledger without learning any more about this file; just use
the add or web or import commands to create and update it.
.PP
Many users, though, edit the journal file with a text editor, and track
changes with a version control system such as git.
Editor add\-ons such as ledger\-mode or hledger\-mode for Emacs,
vim\-ledger for Vim, and hledger\-vscode for Visual Studio Code, make
this easier, adding colour, formatting, tab completion, and useful
commands.
See Editors at hledger.org for the full list.
.PP
A hledger journal file can contain three kinds of thing: comment lines,
transactions, and/or directives (including periodic transaction rules
and auto posting rules).
Understanding the journal file format will also give you a good
understanding of hledger\(aqs data model.
Here\(aqs a quick cheatsheet/overview, followed by detailed descriptions
of each part.
.SS Journal cheatsheet
.IP
.EX
# Here is the main syntax of hledger\(aqs journal format
# (omitting extra Ledger compatibility syntax).
###############################################################################
# 1. These are comment lines, for notes or temporarily disabling things.
; They begin with # or ;
comment
Or, lines can be enclosed within \(dqcomment\(dq / \(dqend comment\(dq.
This is a block of
commented lines.
end comment
# Some journal entries can have semicolon comments at end of line ; like this
# Some of them require 2 or more spaces before the semicolon.
###############################################################################
# 2. Directives customise processing or output in some way.
# You don\(aqt need any directives to get started.
# But they can add more error checking, or change how things are displayed.
# They begin with a word, letter, or symbol.
# They are most often placed at the top, before transactions.
account assets ; Declare valid account names and display order.
account assets:savings ; A subaccount. This one represents a bank account.
account assets:checking ; Another. Note, 2+ spaces after the account name.
account assets:receivable ; Accounting type is inferred from english names,
account passifs ; or declared with a \(dqtype\(dq tag, type:L
account expenses ; type:X
; A follow\-on comment line, indented.
account expenses:rent ; Expense and revenue categories are also accounts.
; Subaccounts inherit their parent\(aqs type.
commodity $0.00 ; Declare valid commodities and their display styles.
commodity 1.000,00 EUR
decimal\-mark . ; The decimal mark used in this file (if ambiguous).
payee Whole Foods ; Declare a valid payee name.
tag trip ; Declare a valid tag name.
P 2024\-03\-01 AAPL $179 ; Declare a market price for AAPL in $ on this date.
include other.journal ; Include another journal file here.
# Declare a recurring \(dqperiodic transaction\(dq, for budget/forecast reports
\(ti monthly set budget goals ; <\- Note, 2+ spaces before the description.
(expenses:rent) $1000
(expenses:food) $500
# Declare an auto posting rule, to modify existing transactions in reports
= revenues:consulting
liabilities:tax:2024:us *0.25 ; Add a tax liability & expense
expenses:tax:2024:us *\-0.25 ; for 25% of the revenue.
###############################################################################
# 3. Transactions are what it\(aqs all about.
# They are dated events, usually movements of money between 2 or more accounts.
# They begin with a numeric date.
# Here is their basic shape:
#
# DATE DESCRIPTION ; The transaction\(aqs date and optional description.
# ACCOUNT1 AMOUNT ; A posting of an amount to/from this account, indented.
# ACCOUNT2 AMOUNT ; A second posting, balancing the first.
# ... ; More if needed. Amounts must sum to zero.
# ; Note, 2+ spaces between account names and amounts.
2024\-01\-01 opening balances ; At the start, declare pre\-existing balances this way.
assets:savings $10000 ; Account names can be anything. lower case is easy to type.
assets:checking $1000 ; assets, liabilities, equity, revenues, expenses are common.
liabilities:credit card $\-500 ; liabilities, equity, revenues balances are usually negative.
equity:start ; One amount can be left blank. $\-10500 is inferred here.
; Some of these accounts we didn\(aqt declare above,
; so \-s/\-\-strict would complain.
2024\-01\-03 ! (12345) pay rent
; Additional transaction comment lines, indented.
; There can be a ! or * after the date meaning \(dqpending\(dq or \(dqcleared\(dq.
; There can be a parenthesised (code) after the date/status.
; Amounts\(aq sign shows direction of flow.
assets:checking $\-500 ; Minus means removed from this account (credit).
expenses:rent $500 ; Plus means added to this account (debit).
; Keeping transactions in date order is optional (but helps error checking).
2024\-01\-02 Gringott\(aqs Bank | withdrawal ; Description can be PAYEE | NOTE
assets:bank:gold \-10 gold
assets:pouch 10 gold
2024\-01\-02 shopping
expenses:clothing 1 gold
expenses:wands 5 gold
assets:pouch \-6 gold
2024\-01\-02 receive gift
revenues:gifts \-3 \(dqChocolate Frogs\(dq ; Complex commodity symbols
assets:pouch 3 \(dqChocolate Frogs\(dq ; must be in double quotes.
2024\-01\-15 buy some shares, in two lots ; Cost can be noted.
assets:investments:2024\-01\-15 2.0 AAAA \(at $1.50 ; \(at means per\-unit cost
assets:investments:2024\-01\-15\-02 3.0 AAAA \(at\(at $4 ; \(at\(at means total cost
; \(ha Per\-lot subaccounts are sometimes useful.
assets:checking $\-7
2024\-01\-15 assert some account balances on this date
; Balances can be asserted in any transaction, with =, for extra error checking.
; Assertion txns like this one can be made with hledger close \-\-assert \-\-show\-costs
;
assets:savings $0 = $10000
assets:checking $0 = $493
assets:bank:gold 0 gold = \-10 gold
assets:pouch 0 gold = 4 gold
assets:pouch 0 \(dqChocolate Frogs\(dq = 3 \(dqChocolate Frogs\(dq
assets:investments:2024\-01\-15 0.0 AAAA = 2.0 AAAA \(at $1.50
assets:investments:2024\-01\-15\-02 0.0 AAAA = 3.0 AAAA \(at\(at $4
liabilities:credit card $0 = $\-500
2024\-02\-01 note some event, or a transaction not yet fully entered, on this date
; Postings are not required.
# Consistent YYYY\-MM\-DD date format is recommended,
# but you can use . or / and omit leading zeros if you prefer.
2024.01.01
2024/1/1
.EE
.SS Comments
Lines in the journal will be ignored if they begin with a hash
(\f[CR]#\f[R]) or a semicolon (\f[CR];\f[R]).
(See also Other syntax.)
hledger will also ignore regions beginning with a \f[CR]comment\f[R]
line, and ending with an \f[CR]end comment\f[R] line or file end.
Here\(aqs a suggestion for choosing between them:
.IP \(bu 2
\f[CR]#\f[R] for top\-level notes
.IP \(bu 2
\f[CR];\f[R] for commenting out things temporarily
.IP \(bu 2
\f[CR]comment\f[R] for quickly commenting large regions (remember
it\(aqs there, or you might get confused)
.PP
Eg:
.IP
.EX
# a comment line
; another commentline
comment
A multi\-line comment block,
continuing until \(dqend comment\(dq directive
or the end of the current file.
end comment
.EE
.PP
Some hledger entries can have same\-line comments attached to them, from
; (semicolon) to end of line.
See Transaction comments, Posting comments, and Account comments below.
.PP
Comment lines immediately preceding a transaction (with no blank line in
between) are attached to that transaction, and are shown before it, as
written, in \f[CR]print\f[R] output.
.SS Transactions
Transactions are the main unit of information in a journal file.
They represent events, typically a movement of some quantity of
commodities between two or more named accounts.
.PP
Each transaction is recorded as a journal entry, beginning with a simple
date in column 0.
This can be followed by any of the following optional fields, separated
by spaces:
.IP \(bu 2
a status character (empty, \f[CR]!\f[R], or \f[CR]*\f[R])
.IP \(bu 2
a code (any short number or text, enclosed in parentheses)
.IP \(bu 2
a description (any remaining text until end of line or a semicolon)
.IP \(bu 2
a comment (any remaining text following a semicolon until end of line,
and any following indented lines beginning with a semicolon)
.IP \(bu 2
0 or more indented \f[I]posting\f[R] lines, describing what was
transferred and the accounts involved (indented comment lines are also
allowed, but not blank lines or non\-indented lines).
.PP
Here\(aqs a simple journal file containing one transaction:
.IP
.EX
2008/01/01 income
assets:bank:checking $1
income:salary $\-1
.EE
.SS Dates
.SS Simple dates
Dates in the journal file use \f[I]simple dates\f[R] format:
\f[CR]YYYY\-MM\-DD\f[R] or \f[CR]YYYY/MM/DD\f[R] or
\f[CR]YYYY.MM.DD\f[R], with leading zeros optional.
The year may be omitted, in which case it will be inferred from the
context: the current transaction, the default year set with a
\f[CR]Y\f[R] directive, or the current date when the command is run.
Some examples: \f[CR]2010\-01\-31\f[R], \f[CR]2010/01/31\f[R],
\f[CR]2010.1.31\f[R], \f[CR]1/31\f[R].
.PP
(On the command line and in the UIs, you can also use the more flexible
smart dates.)
.SS Posting dates
You can give individual postings a different date from their parent
transaction, by adding a posting comment containing a tag (see below)
like \f[CR]; date:DATE\f[R].
(There\(aqs also a Ledger\-compatible syntax, \f[CR]; [DATE]\f[R], which
can be convenient.)
.PP
This is probably the best way to control posting dates precisely.
Eg in this example the expense should appear in May reports, and the
deduction from checking should be reported on 6/1 for easy bank
reconciliation:
.IP
.EX
2015/5/30
expenses:food $10 ; food purchased on saturday 5/30
assets:checking ; bank cleared it on monday, date:6/1
.EE
.IP
.EX
$ hledger \-f t.j register food
2015\-05\-30 expenses:food $10 $10
.EE
.IP
.EX
$ hledger \-f t.j register checking
2015\-06\-01 assets:checking $\-10 $\-10
.EE
.PP
DATE should be a simple date; if the year is not specified it will use
the year of the transaction\(aqs date.
.PD 0
.P
.PD
A non\-empty \f[CR]date:\f[R] tag value must begin with a valid simple
date.
A \f[CR]date:\f[R] tag with an empty value is allowed, and sets no date.
(To disable a date tag temporarily, without removing the date, insert a
comma before the date.)
.SS Status
Transactions (or individual postings within a transaction) can have a
status mark, which is a single character before the transaction
description (or posting account name), separated from it by a space,
indicating one of three statuses:
.PP
.TS
tab(@);
l l.
T{
mark \
T}@T{
status
T}
_
T{
\
T}@T{
unmarked
T}
T{
\f[CR]!\f[R]
T}@T{
pending
T}
T{
\f[CR]*\f[R]
T}@T{
cleared
T}
.TE
.PP
When reporting, you can filter by status with the
\f[CR]\-U/\-\-unmarked\f[R], \f[CR]\-P/\-\-pending\f[R], and
\f[CR]\-C/\-\-cleared\f[R] flags (and you can combine these, eg
\f[CR]\-UP\f[R] to match all except cleared things).
Or you can use the \f[CR]status:\f[R], \f[CR]status:!\f[R], and
\f[CR]status:*\f[R] queries, or the U, P, C keys in hledger\-ui.
.PP
(Note: in Ledger the \(dqunmarked\(dq state is called \(dquncleared\(dq;
in hledger we renamed it to \(dqunmarked\(dq for semantic clarity.)
.PP
Status marks are optional, but can be helpful eg for reconciling with
real\-world accounts.
Some editor modes provide highlighting and shortcuts for working with
status.
Eg in Emacs ledger\-mode, you can toggle transaction status with C\-c
C\-e, or posting status with C\-c C\-c.
.PP
What \(dquncleared\(dq, \(dqpending\(dq, and \(dqcleared\(dq actually
mean is up to you.
Here\(aqs one suggestion:
.PP
.TS
tab(@);
lw(9.7n) lw(60.3n).
T{
status
T}@T{
meaning
T}
_
T{
uncleared
T}@T{
recorded but not yet reconciled; needs review
T}
T{
pending
T}@T{
tentatively reconciled (if needed, eg during a big reconciliation)
T}
T{
cleared
T}@T{
complete, reconciled as far as possible, and considered correct
T}
.TE
.PP
With this scheme, you would use \f[CR]\-PC\f[R] to see the current
balance at your bank, \f[CR]\-U\f[R] to see things which will probably
hit your bank soon (like uncashed checks), and no flags to see the most
up\-to\-date state of your finances.
.SS Code
After the status mark, but before the description, you can optionally
write a transaction \(dqcode\(dq, such as a check number or transaction
id, enclosed in parentheses.
.PP
This has a few limitations: The code must not contain a closing
parenthesis (or it will be truncated).
Codes tend to disrupt alignment of the register report, making it harder
to scan visually.
And you can\(aqt store more than one value there per transaction.
For these reasons you might want to avoid the code field and use tags
instead.
.SS Description
After the date, status mark and/or code fields, the rest of the line (or
until a comment is begun with \f[CR];\f[R]) is the transaction\(aqs
description.
Here you can describe the transaction (called the \(dqnarration\(dq in
traditional bookkeeping), or you can record a payee/payer name, or you
can leave it empty.
.PP
Transaction descriptions show up in print output and in register
reports, and can be listed with the descriptions command.
.PP
You can query by description with \f[CR]desc:DESCREGEX\f[R], or pivot on
description with \f[CR]\-\-pivot desc\f[R].
.SS Payee and note
Sometimes people want a dedicated payee/payer field that can be queried
and checked more strictly.
If you want that, you can write a \f[CR]|\f[R] (pipe) character in the
description.
This divides it into a \(dqpayee\(dq field on the left, and a
\(dqnote\(dq field on the right.
(Either can be empty.)
.PP
You can query these with \f[CR]payee:PAYEEREGEX\f[R] and
\f[CR]note:NOTEREGEX\f[R], list their values with the payees and notes
commands, or pivot on \f[CR]payee\f[R] or \f[CR]note\f[R].
.PP
Note: in transactions with no \f[CR]|\f[R] character, description,
payee, and note all have the same value.
Once a \f[CR]|\f[R] is added, they become distinct.
.PP
If you want more strict error checking, you can declare the valid payee
names with payee directives, and then enforce these with hledger check
payees.
(Note: because of the above, for this you\(aqll need to ensure every
transaction description contains a \f[CR]|\f[R] and therefore a
checkable payee name, even if it\(aqs empty.)
.SS Transaction comments
Text following \f[CR];\f[R], after a transaction description, and/or on
indented lines immediately below it, form comments for that transaction.
They are reproduced by \f[CR]print\f[R] but otherwise ignored, except
they may contain tags, which are not ignored.
.IP
.EX
2012\-01\-01 something ; a transaction comment
; a second line of transaction comment
expenses 1
assets
.EE
.SS Postings
A posting is an addition of some amount to, or removal of some amount
from, an account.
Each posting line begins with at least one space or tab (2 or 4 spaces
is common), followed by:
.IP \(bu 2
(optional) a status character (empty, \f[CR]!\f[R], or \f[CR]*\f[R]),
followed by a space
.IP \(bu 2
(required) an account name (any text, optionally including single
spaces.
If anything follows the account name on the same line, the account name
must be ended by \f[B]two or more spaces\f[R].)
.IP \(bu 2
(optional) an amount
.IP \(bu 2
(optional) a same\-line posting comment, beginning with a semicolon
(\f[CR];\f[R]).
.PP
If the amount is positive, it is being added to the account; if
negative, it is being removed from the account.
.PP
The posting amounts in a transaction must sum up to zero, indicating
that the inflows and outflows are equal.
We call this a balanced transaction.
(You can read more about the details of transaction balancing below.)
.PP
If no amount is written, it will be calculated automatically from the
other postings in the transaction, so as to balance the transaction.
In other words, in any transaction you can leave one posting amountless
to save typing.
.SS Debits and credits
The traditional accounting concepts of debit and credit of course exist
in hledger, but we represent them with numeric sign.
Positive and negative posting amounts represent debits and credits
respectively.
.PP
You don\(aqt need to remember that, but if you would like to \- eg for
helping newcomers or for talking with your accountant \- here\(aqs a
handy mnemonic:
.PP
\f[I]\f[CI]debit / plus / left / short words\f[I]\f[R]
.PD 0
.P
.PD
\f[I]\f[CI]credit / minus / right / longer words\f[I]\f[R]
.SS Account names
Accounts are the main way of categorising things in hledger.
As in Double Entry Bookkeeping, they can represent real world accounts
(such as a bank account), or more abstract categories such as \(dqmoney
spent on food\(dq or \(dqmoney borrowed from Frank\(dq.
.PP
Account names are flexible.
They may be capitalised or not; they may contain letters, numbers,
punctuation, symbols, or single spaces; they may be in any language.
Their parts, separated by \f[CR]:\f[R], can\(aqt be empty; so an account
name can\(aqt begin or end with \f[CR]:\f[R], or contain \f[CR]::\f[R].
.PP
Typically we use the five traditional accounting categories as the
starting point for account names.
In english they are:
.PP
\f[CR]assets\f[R], \f[CR]liabilities\f[R], \f[CR]equity\f[R],
\f[CR]revenues\f[R], \f[CR]expenses\f[R]
.PP
These will be discussed more in Account types below.
In hledger docs you may see them referred to as A, L, E, R, X for short.
.SS Two space delimiter
Note that hledger\(aqs account names, like Ledger\(aqs, may contain
single spaces.
Because of this, they must be separated from anything following them on
the same line by \f[B]two or more spaces\f[R].
(Two or more tabs also work; but spaces are preferred.
A single tab is not a separator, unlike in Ledger.)
.PP
This lets us use expressive account names, while still keeping the
syntax light.
Here are some examples:
.IP
.EX
assets:accounts receivable ; bad, only one space before the comment
assets:accounts receivable ; good
.EE
.IP
.EX
assets:accounts receivable $10 ; bad, one space before the amount
assets:accounts receivable $10 ; good
.EE
.IP
.EX
assets:accounts receivable = $1000 ; bad, one space before the balance assignment
assets:accounts receivable = $1000 ; good
.EE
.PP
The two\-space delimiter is also required in periodic transaction rules,
between period expression and description:
.IP
.EX
\(ti every 5th day YouTube Premium ; bad, one space before the description
\(ti every 5th day YouTube Premium ; good
.EE
.PP
When you are starting out, you can expect this delimiter will trip you
up once or twice.
(If it happens too much, you can check account names strictly to prevent
it.)
.SS Account hierarchy
For more precise reporting, we usually divide accounts into more
detailed subaccounts, subsubaccounts, and so on, by writing a full colon
between account name parts.
For example, instead of writing \f[CR]assets\f[R] and
\f[CR]expenses\f[R], we might write \f[CR]assets:bank:checking\f[R] and
\f[CR]expenses:food\f[R].
From these names hledger will infer this hierarchy of five accounts:
.IP
.EX
assets
assets:bank
assets:bank:checking
expenses
expenses:food
.EE
.PP
Or as an outline:
.IP
.EX
assets
bank
checking
expenses
food
.EE
.PP
hledger reports can summarise the account tree to any depth, so you can
make your subcategories as detailed as you like.
But don\(aqt go overboard, especially when getting started; simpler
categories can be less work.
.SS Other account name features
Enclosing the account name in parentheses or brackets, like
\f[CR](expenses:food)\f[R], enables a non\-standard bookkeeping feature:
virtual postings.
.PP
Account names can be rewritten and restructured, temporarily or
permanently, by account aliases.
.SS Amounts
After the account name, there is usually an amount.
(Remember: between account name and amount, there must be two or more
spaces.)
.PP
hledger\(aqs amount format is flexible, supporting several international
formats.
Here are some examples.
Amounts have a number (the \(dqquantity\(dq):
.IP
.EX
1
.EE
.PP
\&..and usually a currency symbol or commodity name (more on this
below), to the left or right of the quantity, with or without a
separating space:
.IP
.EX
$1
4000 AAPL
3 \(dqgreen apples\(dq
.EE
.PP
Amounts can be preceded by a minus sign (or a plus sign, though plus is
the default), The sign can be written before or after a left\-side
commodity symbol:
.IP
.EX
\-$1
$\-1
.EE
.PP
One or more spaces between the sign and the number are acceptable when
parsing (but they won\(aqt be displayed in output):
.IP
.EX
+ $1
$\- 1
.EE
.PP
Scientific E notation is allowed:
.IP
.EX
1E\-6
EUR 1E3
.EE
.PP
.SS Decimal marks
A \f[I]decimal mark\f[R] can be written as a period or a comma:
.IP
.EX
1.23
1,23
.EE
.PP
Both of these are common in international number formats, so hledger is
not biased towards one or the other.
Because hledger also supports digit group marks (eg thousands
separators), this means that a number like \f[CR]1,000\f[R] or
\f[CR]1.000\f[R] containing just one period or comma is ambiguous.
In such cases, hledger by default assumes it is a decimal mark, and will
parse both of those as 1.
.PP
To help hledger parse such ambiguous numbers accurately, if you use
digit group marks, we recommend declaring the decimal mark explicitly.
You can declare it per commodity with \f[CR]commodity\f[R] directives,
or per file with a \f[CR]decimal\-mark\f[R] directive at the top of each
journal file (described below).
.PP
hledger also accepts numbers like \f[CR]10.\f[R] with no digits after
the decimal mark (and will sometimes display numbers that way to
disambiguate them \- see Trailing decimal marks).
.SS Digit group marks
In the integer part of the amount quantity (left of the decimal mark),
groups of digits can optionally be separated by a \f[I]digit group
mark\f[R] \- a comma or period (whichever is not used as decimal mark),
an underscore, an apostrophe, or a space (several Unicode space
variants, like no\-break space, are also accepted).
So these are all valid amounts in a journal file:
.IP
.EX
$1,000,000.00
EUR 2.000.000,00
INR 9,99,99,999.00
CHF 1\(aq000\(aq000.00
1_000_000.00
1 000 000.00 ; <\- ordinary space
1\ 000\ 000.00 ; <\- no\-break space
.EE
.SS Commodity
Amounts in hledger have both a \(dqquantity\(dq, which is a signed
decimal number, and a \(dqcommodity\(dq, which is a currency symbol,
stock ticker, or any word or phrase describing something you are
tracking.
.PP
If the commodity name contains non\-letters (spaces, numbers, or
punctuation), you must always write it inside double quotes
(\f[CR]\(dqgreen apples\(dq\f[R], \f[CR]\(dqABC123\(dq\f[R]).
In particular, in a posting amount, a symbol that begins with
\f[CR](\f[R] before the number, or with \f[CR]/\f[R] after it, or that
contains \f[CR])\f[R] inside parentheses, must be quoted, eg
\f[CR]\(dq(X)\(dq 10\f[R] or \f[CR]10 \(dq/x\(dq\f[R], or it would be
read as part of an amount expression.
.PP
If you write just a bare number, that too will have a commodity, with
name \f[CR]\(dq\(dq\f[R]; we call that the \(dqno\-symbol commodity\(dq.
.PP
Actually, hledger combines these single\-commodity amounts into more
powerful multi\-commodity amounts, which are what it works with most of
the time.
A multi\-commodity amount could be, eg:
\f[CR]1 USD, 2 EUR, 3.456 TSLA\f[R].
In practice, you will only see multi\-commodity amounts in hledger\(aqs
output; you can\(aqt write them directly in the journal file.
.PP
By default, the format of amounts in the journal influences how hledger
displays them in output.
This is explained in Commodity display style below.
.PP
A posting amount can also be an arithmetic expression, like
\f[CR]$47.97 + $15.75\f[R]; see Amount expressions.
.PP
.SS Costs
When one commodity is exchanged for another \- a currency conversion, or
a purchase or sale of stock \- you can record the transacted price or
conversion rate by writing \f[CR]\(at UNITCOST\f[R] or
\f[CR]\(at\(at TOTALCOST\f[R] after a posting amount.
(hledger docs generically call this a \(dqcost\(dq, whether buying or
selling, though \(dqcost\(dq is an overloaded word.
\(dqTransacted cost\(dq or \(dqtransacted price\(dq is more precise.)
Eg:
.IP
.EX
2026\-01\-01 buy euros
assets:dollars $\-123
assets:euros €100 \(at $1.23 ; unit cost (exchange rate)
.EE
.PP
or:
.IP
.EX
2026\-01\-01 buy euros
assets:dollars $\-123
assets:euros €100 \(at\(at $123 ; total cost
.EE
.PP
The cost should normally be a positive amount.
Negative costs are supported, but can be confusing, as discussed at
\-\-infer\-market\-prices: market prices from transactions.
.PP
Costs participate in transaction balancing: amounts are converted to
their cost before checking if the transaction is balanced.
So you could also write the above less redundantly, like so:
.IP
.EX
2026\-01\-01 buy euros
assets:dollars ; $\-123 is inferred
assets:euros €100 \(at $1.23
.EE
.PP
or:
.IP
.EX
2026\-01\-01 buy euros
assets:dollars ; $\-123 is inferred
assets:euros €100 \(at\(at $123
.EE
.PP
or even:
.IP
.EX
2026\-01\-01 buy euros
assets:euros €100 ; \(at\(at $123 is inferred
assets:dollars $\-123
.EE
.PP
This last form works for transactions involving exactly two commodities,
with neither cost notation nor equity postings.
If one of the postings is recognised as a lot posting, the cost will be
attached to that one.
Otherwise the cost will be attached to the first (top) posting \- so it
can be important to put the right one first.
Here we had to switch the order of postings, to get the same meaning as
above.
.PP
This form is the easiest to make undetected errors with; so it is
rejected by \f[CR]hledger check balanced\f[R], and by strict mode.
.PP
Reports can show amounts converted to their cost when you add the
\f[CR]\-B/\-\-cost\f[R] flag.
.PP
Costs can also be recorded in a more traditional double entry way, with
equity postings; or with both notations at once.
See Cost reporting for a comparison of these styles, and how hledger can
convert between them.
.SS Cost basis
This section briefly describes the \f[CR]{}\f[R] cost basis syntax, used
to record the nominal cost of an investment being acquired, or to select
lots being transferred or disposed.
This is described in more detail later in Lots and capital gains.
If you\(aqre not tracking investment lots and capital gains, you can
skip this.
.PP
hledger\(aqs cost basis annotations look like Beancount\(aqs:
comma\-separated parts enclosed in curly braces, after an amount.
All parts are optional, but when present they must be in this order:
.IP "1." 3
a date, in YYYY\-MM\-DD format
.IP "2." 3
a text label, enclosed in double quotes
.IP "3." 3
a cost, as a single\-commodity hledger amount.
.PP
Here are some valid hledger cost basis annotations:
.IP
.EX
{2026\-01\-15, \(dq12:05\(dq, $50}
{2026\-01\-15, $50}
{1.000.000,33 EUR}
{$50}
{}
.EE
.PP
This means: selling 10 AAPL, originally purchased at $50 each, for $60
each:
.IP
.EX
\-10 AAPL {$50} \(at $60
.EE
.PP
Note the preferred order is to write {} before \(at, as shown.
.PP
hledger can also read Ledger\(aqs cost basis syntax.
Here, the parts are written separately, in any order, with different
enclosing characters:
.IP
.EX
10 AAPL {$50} [2026\-01\-15] (12:05)
.EE
.PP
If a Ledger\-style label annotation contains double quotes, they will be
stripped (\f[CR](\(dqfoo\(dq)\f[R] is read as label \f[CR]foo\f[R]).
.SS Balance assertions
hledger supports Ledger\-style balance assertions in journal files.
These look like, for example, \f[CR]= EXPECTEDBALANCE\f[R] following a
posting\(aqs amount.
Eg here we assert the expected dollar balance in accounts a and b after
each posting:
.IP
.EX
2013/1/1
a $1 = $1
b = $\-1
2013/1/2
a $1 = $2
b $\-1 = $\-2
.EE
.PP
After reading a journal file, hledger will check all balance assertions
and report an error if any of them fail.
Balance assertions can protect you from, eg, inadvertently disrupting
reconciled balances while cleaning up old entries.
You can disable them temporarily with the \f[CR]\-I\f[R] or
\f[CR]\-\-ignore\-assertions\f[R] flag, which can be useful for
troubleshooting or for reading Ledger files.
(Note: this flag currently does not disable balance assignments,
described below).
.PP
To check rules which should hold at all times, such as \(dqno asset
account is ever negative\(dq, see assert directives.
.SS Assertions and ordering
hledger calculates and checks an account\(aqs balance assertions in date
order (and when there are multiple assertions on the same day, in parse
order).
Note this is different from Ledger, which checks assertions always in
parse order, ignoring dates.
.PP
This means in hledger you can freely reorder transactions, postings, or
files, and balance assertions will usually keep working.
The exception is when you reorder multiple postings on the same day, to
the same account, which have balance assertions; those will likely need
updating.
.SS Assertions and multiple files
If an account has transactions appearing in multiple files, balance
assertions can still work \- but \f[I]only if those files are part of a
hierarchy made by include directives\f[R].
.PP
If the same files are specified with two \f[CR]\-f\f[R] options on the
command line, the assertions in the second will not see the balances
from the first.
.PP
To work around this, arrange your files in a hierarchy with
\f[CR]include\f[R].
Or, you could concatenate the files temporarily, and process them like
one big file.
.PP
This is for stable, predictable reports: the file hierarchy is part of
your data, while the order of command line arguments is not, and
reordering your arguments should not change whether your assertions
pass.
.SS Assertions and costs
Balance assertions ignore costs, and should normally be written without
one:
.IP
.EX
2019/1/1
(a) $1 \(at €1 = $1
.EE
.PP
We do allow costs to be written in balance assertion amounts, however,
and print shows them, but they don\(aqt affect whether the assertion
passes or fails.
This is for backward compatibility (hledger\(aqs close command used to
generate balance assertions with costs), and because balance
\f[I]assignments\f[R] do use costs (see below).
.SS Assertions and commodities
The balance assertions described so far are \(dq\f[B]single commodity
balance assertions\f[R]\(dq: they assert and check the balance in one
commodity, ignoring any others that may be present.
This is how balance assertions work in Ledger also.
.PP
If an account contains multiple commodities, you can assert their
balances by writing multiple postings with balance assertions, one for
each commodity:
.IP
.EX
2013/1/1
usd $\-1
eur €\-1
both
2013/1/2
both 0 = $1
both 0 = €1
.EE
.PP
In hledger you can make a stronger \(dq\f[B]sole commodity balance
assertion\f[R]\(dq by writing two equals signs
(\f[CR]== EXPECTEDBALANCE\f[R]).
This also asserts that there are no other commodities in the account
besides the asserted one (or at least, that their current balance is
zero):
.IP
.EX
2013/1/1
usd $\-1 == $\-1 ; these sole commodity assertions succeed
eur €\-1 == €\-1
both ;== $1 ; this one would fail because \(aqboth\(aq contains $ and €
.EE
.PP
It\(aqs less easy to make a \(dq\f[B]sole commodities balance
assertion\f[R]\(dq (note the plural) \- ie, asserting that an account
contains two or more specified commodities and no others.
It can be done by
.IP "1." 3
isolating each commodity in a subaccount, and asserting those
.IP "2." 3
and also asserting there are no commodities in the parent account
itself:
.IP
.EX
2013/1/1
usd $\-1
eur €\-1
both 0 == 0 ; nothing up my sleeve
both:usd $1 == $1 ; a dollar here
both:eur €1 == €1 ; a euro there
.EE
.SS Assertions and subaccounts
All of the balance assertions above (both \f[CR]=\f[R] and
\f[CR]==\f[R]) are \(dq\f[B]subaccount\-exclusive balance
assertions\f[R]\(dq; they ignore any balances that exist in deeper
subaccounts.
.PP
In hledger you can make \(dq\f[B]subaccount\-inclusive balance
assertions\f[R]\(dq by adding a star after the equals (\f[CR]=*\f[R] or
\f[CR]==*\f[R]):
.IP
.EX
2019/1/1
equity:start
assets:checking $10
assets:savings $10
assets $0 ==* $20 ; assets + subaccounts contains $20 and nothing else
.EE
.SS Assertions and lot subaccounts
Lot subaccounts (a special kind of subaccount for tracking lots,
discussed in \(dqLots and capital gains\(dq below) have only limited
support for balance assertions: the assertions will be checked correctly
only if all postings to that lot mention the subaccount name explicitly.
.PP
Since it\(aqs common practice to leave lot subaccounts implicit,
generally you should avoid writing balance assertions on individual
lots.
(\f[CR]close \-\-lots\f[R] also follows this rule.)
If you forget, the balance assertion failure message will remind you.
If you really need a balance assertion, you can usually write it on the
parent account instead.
.PP
(The restriction is because transaction balancing amounts, balance
assignments, and balance assertions must be calculated and checked
before lot movements are known.)
See also Lot postings and balance assertions.
.SS Assertions and status
Balance assertions always consider postings of all statuses (unmarked,
pending, or cleared); they are not affected by the
\f[CR]\-U\f[R]/\f[CR]\-\-unmarked\f[R] /
\f[CR]\-P\f[R]/\f[CR]\-\-pending\f[R] /
\f[CR]\-C\f[R]/\f[CR]\-\-cleared\f[R] flags or the \f[CR]status:\f[R]
query.
.SS Assertions and virtual postings
Balance assertions always consider both real and virtual postings; they
are not affected by the \f[CR]\-\-real/\-R\f[R] flag or \f[CR]real:\f[R]
query.
.SS Assertions and auto postings
Balance assertions \f[I]are\f[R] affected by the \f[CR]\-\-auto\f[R]
flag, which generates auto postings, which can alter account balances.
Because auto postings are optional in hledger, accounts affected by them
effectively have two balances.
But balance assertions can only test one or the other of these.
So to avoid making fragile assertions, either:
.IP \(bu 2
assert the balance calculated with \f[CR]\-\-auto\f[R], and always use
\f[CR]\-\-auto\f[R] with that file
.IP \(bu 2
or assert the balance calculated without \f[CR]\-\-auto\f[R], and never
use \f[CR]\-\-auto\f[R] with that file
.IP \(bu 2
or avoid balance assertions on accounts affected by auto postings (or
avoid auto postings entirely).
.SS Assertions and precision
Balance assertions compare the exactly calculated amounts, which are not
always what is shown by reports.
Eg a commodity directive may limit the display precision, but this will
not affect balance assertions.
Balance assertion failure messages show exact amounts.
.SS Assertions and hledger add
The \f[CR]add\f[R] command also accepts balance assertions (and
assignments), and re\-checks all of the journal\(aqs assertions as you
enter amounts; see add and balance assertions.
.SS Posting comments
Text following \f[CR];\f[R], at the end of a posting line, and/or on
indented lines immediately below it, form comments for that posting.
They are reproduced by \f[CR]print\f[R] but otherwise ignored, except
they may contain tags, which are not ignored.
.IP
.EX
2012\-01\-01
expenses 1 ; a comment for posting 1
assets
; a comment for posting 2
; a second comment line for posting 2
.EE
.SS Tags
Tags are a way to add extra labels or data fields to transactions,
postings, or accounts, which you can match with a \f[CR]tag:\f[R] query
in reports.
(See queries below.)
.PP
Tags are a single word or hyphenated word, immediately followed by a
full colon, written within a comment.
(Yes, storing data in comments is slightly weird.)
Here\(aqs a transaction with a tag:
.IP
.EX
2025\-01\-01 groceries ; some\-tag:
assets:checking
expenses:food $1
.EE
.PP
A tag can have a value: a single line of text written after the colon
(tag values can\(aqt contain newlines):
.IP
.EX
2025\-01\-01 groceries ; tag1: this is tag1\(aqs value
.EE
.PP
Multiple tags can be separated by comma (so tag values can\(aqt contain
commas):
.IP
.EX
2025\-01\-01 groceries ; tag1:value 1, tag2:value 2, comment text
.EE
.PP
A tag can have multiple values:
.IP
.EX
2025\-01\-01 groceries ; tag1:value 1, tag1:value 2
.EE
.PP
You can write each tag on its own line if you prefer (but they still
can\(aqt contain commas):
.IP
.EX
2025\-01\-01 groceries
; tag1: value 1
; tag2: value 2
.EE
.PP
Tags can be attached to individual postings, rather than the overall
transaction:
.IP
.EX
2025\-01\-01 rent
assets:checking
expenses:rent $1000 ; postingtag:
.EE
.PP
Tags can be attached to accounts, in their account directive:
.IP
.EX
account assets:checking ; acct\-number: 123\-45\-6789
.EE
.SS Tag propagation
In addition to what they are attached to, tags also affect related data
in a few ways, allowing more powerful queries:
.IP "1." 3
Accounts \-> postings.
Postings inherit tags from their account.
.IP "2." 3
Transactions \-> postings.
Postings inherit tags from their transaction.
.IP "3." 3
Postings \-> transactions.
Transactions also acquire the tags of their postings.
.PP
So when you use a \f[CR]tag:\f[R] query to match whole transactions,
individual postings, or accounts, it\(aqs good to understand how tags
behave.
Here\(aqs an example showing all three kinds of propagation:
.IP
.EX
account assets:checking
account expenses:food ; atag:
2025\-01\-01 groceries ; ttag:
assets:checking ; p1tag:
expenses:food $1 ; p2tag:
.EE
.PP
.TS
tab(@);
lw(13.3n) lw(13.8n) lw(43.0n).
T{
data part
T}@T{
has tags
T}@T{
explanation
T}
_
T{
assets:checking\ account
T}@T{
T}@T{
no tags attached
T}
T{
expenses:food account
T}@T{
atag
T}@T{
atag: in comment
T}
T{
assets:checking posting
T}@T{
p1tag, ttag
T}@T{
p1tag: in comment, ttag acquired from transaction
T}
T{
expenses:food posting
T}@T{
p2tag, atag, ttag
T}@T{
p2tag: in comment, atag from account, ttag from transaction
T}
T{
groceries transaction
T}@T{
ttag, p1tag, p2tag, atag
T}@T{
ttag: in comment, p1tag from first posting, p2tag and atag from second
posting
T}
.TE
.SS Displaying tags
You can use the \f[CR]tags\f[R] command to list tag names or values.
.PP
The \f[CR]print\f[R] command also shows tags.
.PP
You can use \-\-pivot to display tag values in other reports, in various
ways (eg appended to account names, like pseudo subaccounts).
.SS When to use tags ?
Tags provide more dimensions of categorisation, complementing accounts
and transaction descriptions.
When to use each of these is somewhat a matter of taste.
Accounts have the most built\-in support, and regex queries on
descriptions are also quite powerful.
So you may not need tags at all.
But if you want to track multiple cross\-cutting categories, they can be
a good fit.
For example, you could tag trip\-related transactions with
\f[CR]trip: YEAR:PLACE\f[R], without disturbing your usual account
categories.
.SS Tag names
What is allowed in a tag name ?
Any sequence of non\-whitespace non\-newline characters.
Eg \f[CR]😀:\f[R] is a valid tag.
.PP
For extra error checking, you can declare valid tag names with the
\f[CR]tag\f[R] directive, and then enforce these with the
\f[CR]check\f[R] command.
But note that tags are detected quite loosely at present, sometimes
where you didn\(aqt intend them.
Eg a comment like \f[CR]; see https://foo.com\f[R] adds a
\f[CR]https\f[R] tag.
.PP
There are several tag names which have special significance to hledger.
They are explained elsewhere, but here\(aqs a quick reference:
.IP
.EX
type \-\- declares an account\(aqs type
alias \-\- declares an account\(aqs or commodity\(aqs alias
lots \-\- declares an account\(aqs or commodity\(aqs lot tracking (cost basis method)
date \-\- overrides a posting\(aqs date
date2 \-\- overrides a posting\(aqs secondary date
assert \-\- appears on txns generated by close \-\-assert
retain \-\- appears on txns generated by close \-\-retain
start \-\- appears on txns generated by close \-\-migrate/\-\-close/\-\-open/\-\-assign
t \-\- appears on postings generated from timedot letters
generated\-transaction \-\- appears on txns generated by a periodic rule
modified\-transaction \-\- appears on txns which have had auto postings added
generated\-posting \-\- appears on generated postings
cost\-posting \-\- appears on postings which have (or could have) a cost,
and which have equivalent conversion postings in the transaction
conversion\-posting \-\- appears on postings which are to a V/Conversion account
and which have an equivalent cost posting in the transaction
ptype \-\- appears on lot postings, with their type (acquire, dispose, etc.)
feesplit\-posting \-\- appears on fee parts split off a lot transfer posting
lotsplit\-posting \-\- appears on the parts of a posting split across several lots (with \-\-lots)
lot\-parent\-assertion \-\- appears on postings carrying a balance assertion moved
from a posting that was split across several lots
.EE
.PP
The second group above (generated\-transaction, etc.)
are normally hidden, with a \f[CR]_\f[R] prefix added.
This means \f[CR]print\f[R] doesn\(aqt show them by default; but you can
still use them in queries.
You can add the \f[CR]\-\-verbose\-tags\f[R] flag to make them visible
in \f[CR]print\f[R] output, which can be useful for troubleshooting.
.SS Tag values
What is allowed in a tag value ?
Any sequence of non\-comma non\-newline characters, with surrounding
whitespace removed.
.PP
Note a tag can have multiple values, if the tag is repeated.
Eg \f[CR]; foo:a, foo:b\f[R].
.SS Directives
You can add directives to a \f[CR]journal\f[R] file, to add error
checking, improve parsing, et cetera.
Directives begin with a keyword, not a date.
Some of them can have indented subdirectives.
hledger\(aqs directives are broadly similar to Ledger\(aqs, though with
differences.
.SS Directive scopes
Directives differ in which entries they affect.
Some affect only the following entries, others affect both preceding and
following entries; and some reach only the current file and its
subfiles, others reach every file.
Assuming this command and file layout:
.IP
.EX
hledger \-f main.journal \-f other.journal
main.journal ; the parent file
include a.journal ; a child of main.journal
include aa.journal ; a child of a.journal
include b.journal ; a child of main.journal, and a sibling of a.journal
other.journal ; a separate file tree
.EE
.PP
here are the possible scopes, for a directive written in
\f[CR]a.journal\f[R]:
.PP
.TS
tab(@);
lw(14.7n) lw(55.3n).
T{
scope
T}@T{
affects
T}
_
T{
\f[B]rest of file + subfiles\f[R]
T}@T{
following entries in or below \f[CR]a.journal\f[R] (including
\f[CR]aa.journal\f[R] if it is included after the directive)
T}
T{
\f[B]rest of file tree\f[R]
T}@T{
as above, plus following entries in parent files
(\f[CR]main.journal\f[R] entries after the \f[CR]include a.journal\f[R]
directive, including \f[CR]b.journal\f[R])
T}
T{
\f[B]file tree\f[R]
T}@T{
all entries in \f[CR]main.journal\f[R], \f[CR]a.journal\f[R],
\f[CR]aa.journal\f[R] and \f[CR]b.journal\f[R], before and after the
directive
T}
T{
\f[B]all files\f[R]
T}@T{
all entries in all file trees, no matter where the directive is written
T}
.TE
.PP
The limited scopes help keep reports stable and deterministic,
independent of the order of \-f options or include directives.
This is sometimes inconvenient, but there are usually workarounds.
In particular, to have account aliases affect all entries in a file
tree, declare them at the start of the main file, before any
\f[CR]include\f[R]s.
(Or to affect all file trees specified at runtime, use
\f[CR]\-\-alias\f[R] options.)
.SS Combining file trees
When you read several file trees (with several \f[CR]\-f\f[R] options),
hledger reads and processes each one separately, then combines them.
So one file tree can\(aqt change how another\(aqs entries are read:
account and commodity aliases, decimal marks, transaction balancing,
balance assertions and assert directives, auto postings, forecast
transactions and lot tracking all work within each file tree.
.PP
But a few declarations reach all file trees (\(dqall files\(dq in the
table below):
.IP \(bu 2
Account declarations, including account types and display order.
.IP \(bu 2
Commodity declarations, including display styles.
If file trees declare a commodity\(aqs display style differently, the
last one is used.
.IP \(bu 2
Payee and tag declarations.
.IP \(bu 2
\f[CR]P\f[R] market prices, used for valuation.
.IP \(bu 2
Commodity aliases, but only for valuation, and only as a last resort:
when market prices can\(aqt convert an amount, eg if it\(aqs in an alias
declared by another file tree.
If file trees declare an alias differently (for a different commodity,
or with a different quantity), converting to or from it this way is an
error.
.PP
So you can combine file trees that weren\(aqt designed to work together.
The interactions to watch for are conflicting display styles, account
types, and market prices.
.SS Directives summary
.PP
.TS
tab(@);
lw(7.9n) lw(51.6n) lw(10.5n).
T{
directive
T}@T{
what it does
T}@T{
scope
T}
_
T{
T}@T{
\f[B]Affects file reading:\f[R]
T}@T{
T}
T{
\f[B]\f[CB]include\f[B]\f[R]
T}@T{
Includes entries from another file (a \(dqsubfile\(dq), as if they were
written inline.
T}@T{
T}
T{
\f[B]\f[CB]comment\f[B]\f[R]
T}@T{
Ignores following entries and directives, until \f[CR]end comment\f[R].
T}@T{
rest of file + subfiles
T}
T{
\f[B]\f[CB]alias\f[B]\f[R]
T}@T{
Rewrites following matched account names, until \f[CR]end aliases\f[R].
T}@T{
rest of file + subfiles
T}
T{
\f[B]\f[CB]account\f[B]\f[R] \f[CR]alias:\f[R] tag
T}@T{
Rewrites following matched account names to this account\(aqs full name,
until \f[CR]end aliases\f[R].
T}@T{
rest of file + subfiles
T}
T{
\f[B]\f[CB]decimal\-mark\f[B]\f[R]
T}@T{
Declares the decimal mark for parsing following amounts of all
commodities, until the next \f[CR]decimal\-mark\f[R] (subfiles can
override).
T}@T{
rest of file + subfiles
T}
T{
\f[B]\f[CB]commodity\f[B]\f[R] sample amount
T}@T{
Declares the decimal mark for parsing following amounts of this
commodity (\f[CR]decimal\-mark\f[R] can override).
T}@T{
rest of file tree
T}
T{
T}@T{
\f[B]Declares data:\f[R]
T}@T{
T}
T{
\f[B]\f[CB]account\f[B]\f[R]
T}@T{
Declares an account, and its display order.
T}@T{
all files
T}
T{
\f[B]\f[CB]account\f[B]\f[R] \f[CR]type:\f[R] tag
T}@T{
Declares the account\(aqs type.
T}@T{
all files
T}
T{
\f[B]\f[CB]account\f[B]\f[R] \f[CR]lots:\f[R] tag
T}@T{
Declares the account\(aqs cost basis method.
T}@T{
file tree
T}
T{
\f[B]\f[CB]commodity\f[B]\f[R]
T}@T{
Declares a commodity symbol.
T}@T{
all files
T}
T{
\f[B]\f[CB]commodity\f[B]\f[R] sample amount
T}@T{
Declares the commodity\(aqs display style.
T}@T{
all files
T}
T{
\f[B]\f[CB]commodity\f[B]\f[R] \f[CR]alias:\f[R] tag
T}@T{
Declares equivalent or related symbols for this commodity.
T}@T{
file tree
T}
T{
\f[B]\f[CB]commodity\f[B]\f[R] \f[CR]lots:\f[R] tag
T}@T{
Declares that the commodity tracks lots, and optionally their cost basis
method.
T}@T{
file tree
T}
T{
\f[B]\f[CB]payee\f[B]\f[R]
T}@T{
Declares a payee name.
T}@T{
all files
T}
T{
\f[B]\f[CB]tag\f[B]\f[R]
T}@T{
Declares a tag name.
T}@T{
all files
T}
T{
\f[B]\f[CB]P\f[B]\f[R]
T}@T{
Declares a commodity\(aqs market price on some date, for value and gain
reports.
T}@T{
all files
T}
T{
T}@T{
\f[B]Generates data:\f[R]
T}@T{
T}
T{
\f[B]\f[CB]=\f[B]\f[R]
T}@T{
Generates extra postings (after matched postings), with
\f[CR]\-\-auto\f[R].
(Does not see sibling files: #1212.)
T}@T{
file tree
T}
T{
\f[B]\f[CB]\(ti\f[B]\f[R]
T}@T{
Generates future transactions (after latest transaction in file tree, by
default), with \f[CR]\-\-forecast\f[R].
T}@T{
file tree
T}
T{
\f[B]\f[CB]\(ti\f[B]\f[R]
T}@T{
Generates budget goals and actual/goal percentages, with
\f[CR]balance \-\-budget\f[R].
T}@T{
all files
T}
T{
T}@T{
\f[B]Checks data:\f[R]
T}@T{
T}
T{
\f[B]\f[CB]assert\f[B]\f[R]
T}@T{
Declares a standing rule, a query that must match no rows or some rows,
checked like balance assertions.
T}@T{
file tree
T}
T{
T}@T{
\f[B]File reading (legacy/deprecated):\f[R]
T}@T{
T}
T{
\f[CR]apply account\f[R]
T}@T{
Prepends a common parent account to all following account names, until
\f[CR]end apply account\f[R].
T}@T{
rest of file + subfiles
T}
T{
\f[CR]apply year\f[R]
T}@T{
Sets a default year for following yearless dates, until
\f[CR]end apply year\f[R].
T}@T{
rest of file + subfiles
T}
T{
\f[CR]D\f[R]
T}@T{
Sets a default commodity for following no\-symbol amounts.
Also sets its parsing decimal mark (overridden by \f[CR]commodity\f[R]
or \f[CR]decimal\-mark\f[R]) and display style (overridden by
\f[CR]commodity\f[R]).
T}@T{
rest of file + subfiles
T}
T{
\f[CR]Y\f[R]
T}@T{
Sets a default year for following yearless dates.
T}@T{
rest of file + subfiles
T}
T{
other
T}@T{
These other Ledger directives are accepted but ignored.
T}@T{
T}
.TE
.SS \f[CR]account\f[R] directive
\f[CR]account\f[R] directives can be used to declare accounts (ie, the
places that amounts are transferred from and to).
Though not required, these declarations can provide several benefits:
.IP \(bu 2
They can document your intended chart of accounts, providing a
reference.
.IP \(bu 2
They can store additional account information as comments, or as tags
which can be used to filter or pivot reports.
.IP \(bu 2
They can restrict which accounts may be posted to by transactions, eg in
strict mode, which helps prevent errors.
.IP \(bu 2
They influence account display order in reports, allowing
non\-alphabetic sorting (eg Revenues to appear above Expenses).
.IP \(bu 2
They can help hledger know your accounts\(aq types (asset, liability,
equity, revenue, expense), enabling reports like balancesheet and
incomestatement.
.IP \(bu 2
They help with account name completion (in hledger add, hledger\-web,
hledger\-iadd, ledger\-mode, etc.)
.PP
They are written as the word \f[CR]account\f[R] followed by a
hledger\-style account name.
Eg:
.IP
.EX
account assets:bank:checking
.EE
.PP
Any indented subdirectives are ignored, except Ledger\(aqs
\f[CR]alias\f[R] subdirective (see Account aliases).
.SS Account comments
Text following \f[B]two or more spaces\f[R] and \f[CR];\f[R] at the end
of an account directive line, and/or following \f[CR];\f[R] on indented
lines immediately below it, form comments for that account.
.PP
Same\-line account comments require two+ spaces before \f[CR];\f[R]
because that character can appear in account names.
.IP
.EX
account assets:bank:checking ; same\-line comment, at least 2 spaces before the semicolon
; next\-line comment
; some tags \- type:A, acctnum:12345
.EE
.SS Account tags
An account directive\(aqs comment may contain tags.
These will be inherited by all postings using that account, except where
the posting already has a value for that tag.
(A posting tag overrides an account tag.)
Note, these tags will be queryable but won\(aqt be shown in
\f[CR]print\f[R] output, even with \-\-verbose\-tags.
.SS Account aliases
An \f[CR]alias:\f[R] tag on an account directive declares an alternate,
usually shorter, name for that account.
This could make data entry quicker, and your journal less verbose (but
also adds more names for you to remember).
Eg:
.IP
.EX
account assets:bank:checking ; alias: checking
2024\-01\-01
expenses:food 5
checking
.EE
.PP
When hledger reads this, it rewrites \f[CR]checking\f[R] to
\f[CR]assets:bank:checking\f[R].
Reports, queries and \f[CR]print\f[R] output show only the full name.
Subaccounts are rewritten too: \f[CR]checking:pending\f[R] becomes
\f[CR]assets:bank:checking:pending\f[R].
(The alias must match the whole account name or its leading components,
exactly and case sensitively; \f[CR]Checking\f[R],
\f[CR]checkingfoo\f[R] or \f[CR]old:checking\f[R] would not be
affected.)
.PP
To declare multiple aliases, add more \f[CR]alias:\f[R] tags.
A Ledger\-style \f[CR]alias\f[R] subdirective, indented below the
account directive, is also accepted, and treated as an \f[CR]alias:\f[R]
tag.
To list the accounts with their aliases, run
\f[CR]hledger accounts \-\-show\-aliases\f[R]; to find the account(s)
with a certain alias, run
\f[CR]hledger accounts \-\-show\-aliases ALIAS\f[R].
.PP
An alias affects the entries which follow it, in the current file and
any files it includes (see directive scopes), until an
\f[CR]end aliases\f[R] directive.
So it\(aqs best to declare accounts at the start of your main file,
before any \f[CR]include\f[R] directives.
.PP
More powerful aliases, such as regular expression aliases which rewrite
many accounts at once, can be declared with the \f[CR]alias\f[R]
directive, described below.
An alias: tag is equivalent to a basic alias directive written just
after the account directive:
.IP
.EX
account assets:bank:checking ; alias: checking
.EE
.IP
.EX
account assets:bank:checking
alias checking = assets:bank:checking
.EE
.PP
You can also apply aliases at runtime, without editing your files, using
the \f[CR]\-\-alias\f[R] option.
.SS Account error checking
By default, accounts need not be declared; they come into existence when
a posting references them.
This is convenient, but it means hledger can\(aqt warn you when you
mis\-spell an account name in the journal.
Usually you\(aqll find that error later, as an extra account in balance
reports, or an incorrect balance when reconciling.
.PP
In strict mode, enabled with the \f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R]
flag, or when you run \f[CR]hledger check accounts\f[R], hledger will
report an error if any transaction uses an account name that has not
been declared by an account directive.
Some notes:
.IP \(bu 2
The declaration is case\-sensitive; transactions must use the correct
account name capitalisation.
.IP \(bu 2
Account declarations affect all files (see directive scopes).
The position of account directives within the file does not matter,
though it\(aqs usual to put them at the top.
.IP \(bu 2
Accounts can only be declared in \f[CR]journal\f[R] files, but will
affect included files of all types.
.IP \(bu 2
It\(aqs currently not possible to declare \(dqall possible
subaccounts\(dq with a wildcard; every account posted to must be
declared.
.IP \(bu 2
As an exception: lot subaccounts (a final account name component like
\f[CR]:{2026\-01\-15, $50}\f[R]) are always ignored by
\f[CR]check accounts\f[R], and need not be declared.
.IP \(bu 2
Also exempt are the accounts which hledger chooses for the postings it
generates: equity conversion postings (from
\f[CR]\-\-infer\-equity\f[R]), gain postings (in lot disposals), and
imbalance postings (from \f[CR]\-\-infer\-imbalance\f[R]).
Postings which you write to those accounts are checked as usual.
.SS Account display order
Account directives also cause hledger to display accounts in a
particular order, not just alphabetically.
Eg, here is a conventional ordering for the top\-level accounts:
.IP
.EX
account assets
account liabilities
account equity
account revenues
account expenses
.EE
.PP
Now hledger displays them in that order:
.IP
.EX
$ hledger accounts
assets
liabilities
equity
revenues
expenses
.EE
.PP
If there are undeclared accounts, those will be displayed last, in
alphabetical order.
.PP
Sorting is done within each group of sibling accounts, at each level of
the account tree.
Eg, a declaration like \f[CR]account parent:child\f[R] influences
\f[CR]child\f[R]\(aqs position among its siblings.
.PP
Note, it does not affect \f[CR]parent\f[R]\(aqs position; for that, you
need an \f[CR]account parent\f[R] declaration.
.PP
Sibling accounts are always displayed together; hledger won\(aqt display
\f[CR]x:y\f[R] in between \f[CR]a:b\f[R] and \f[CR]a:c\f[R].
.PP
An account directive both declares an account as a valid posting target,
and declares its display order; you can\(aqt easily do one without the
other.
.SS Account types
hledger knows that in accounting there are three main account types:
.PP
.TS
tab(@);
l l l.
T{
\f[CR]Asset\f[R]
T}@T{
\f[CR]A\f[R]
T}@T{
things you own
T}
T{
\f[CR]Liability\f[R]
T}@T{
\f[CR]L\f[R]
T}@T{
things you owe
T}
T{
\f[CR]Equity\f[R]
T}@T{
\f[CR]E\f[R]
T}@T{
owner\(aqs investment, balances the two above
T}
.TE
.PP
and two more representing changes in these:
.PP
.TS
tab(@);
l l l.
T{
\f[CR]Revenue\f[R]
T}@T{
\f[CR]R\f[R]
T}@T{
inflows (also known as \f[CR]Income\f[R])
T}
T{
\f[CR]Expense\f[R]
T}@T{
\f[CR]X\f[R]
T}@T{
outflows
T}
.TE
.PP
hledger also uses a few subtypes:
.PP
.TS
tab(@);
lw(23.3n) lw(23.3n) lw(23.3n).
T{
\f[CR]Cash\f[R]
T}@T{
\f[CR]C\f[R]
T}@T{
liquid assets (subtype of Asset)
T}
T{
\f[CR]Conversion\f[R]
T}@T{
\f[CR]V\f[R]
T}@T{
commodity conversions equity (subtype of Equity)
T}
T{
\f[CR]Gain\f[R]
T}@T{
\f[CR]G\f[R]
T}@T{
realised capital gains/losses (subtype of Revenue)
T}
T{
\f[CR]UnrealisedGain\f[R]
T}@T{
\f[CR]U\f[R]
T}@T{
accumulated unrealised capital gains (subtype of Equity)
T}
T{
\f[CR]Imbalance\f[R]
T}@T{
\f[CR]M\f[R]
T}@T{
transactions\(aq tolerated imbalances, shown by
\f[CR]\-\-infer\-imbalance\f[R] (subtype of Equity)
T}
.TE
.PP
As a convenience, hledger will detect these types automatically from
english account names.
But it\(aqs better to declare them explicitly by adding a
\f[CR]type:\f[R] tag in the account directives.
The tag\(aqs value can be any of the types or one\-letter abbreviations
above.
.PP
Here is a typical set of account type declarations.
Subaccounts will inherit their parent\(aqs type, or can override it:
.IP
.EX
account assets ; type: A
account liabilities ; type: L
account equity ; type: E
account revenues ; type: R
account expenses ; type: X
account assets:bank ; type: C
account assets:cash ; type: C
account equity:conversion ; type: V
account equity:unrealised\-gain ; type: U
account revenues:gain ; type: G
.EE
.PP
This enables the easy balancesheet, balancesheetequity, cashflow and
incomestatement reports, and querying by type:.
.PP
Tips:
.IP \(bu 2
You can list accounts and their types, for troubleshooting:
.RS 2
.IP
.EX
$ hledger accounts \-\-types [ACCTPAT] [type:TYPECODES] [\-DEPTH] [\-\-locations]
.EE
.RE
.IP \(bu 2
It\(aqs a good idea to declare at least one account for each account
type.
Having some types declared and some inferred can disrupt certain
reports.
.IP \(bu 2
The rules for inferring types from account names are as follows (using
Regular expressions).
.PD 0
.P
.PD
If they don\(aqt work for you, just ignore them and declare your types
with \f[CR]type:\f[R] tags.
.RS 2
.IP
.EX
If account\(aqs name contains this case insensitive regular expression | its type is
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-\-
\(haassets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|current)(:|$) | Cash
\(haassets?(:|$) | Asset
\(ha(debts?|liabilit(y|ies))(:|$) | Liability
\(haequity:(trad(e|ing)|conversion)s?(:|$) | Conversion
\(haequity:unreali[sz]ed([\- ](capital[\- ])?gains?)?(:|$) | UnrealisedGain
\(haequity:imbalances?(:|$) | Imbalance
\(haequity(:|$) | Equity
\(ha(income|revenue)s?:(capital[\- ]?)?(gains?|loss(es)?)(:|$) | Gain
\(ha(income|revenue)s?(:|$) | Revenue
\(haexpenses?(:|$) | Expense
.EE
.RE
.IP \(bu 2
As mentioned above, subaccounts will inherit a type from their parent
account.
To be precise, an account\(aqs type is decided by the first of these
that exists:
.RS 2
.IP "1." 3
A \f[CR]type:\f[R] declaration for this account.
.IP "2." 3
A \f[CR]type:\f[R] declaration in the parent accounts above it,
preferring the nearest.
.IP "3." 3
An account type inferred from this account\(aqs name.
.IP "4." 3
An account type inferred from a parent account\(aqs name, preferring the
nearest parent.
.IP "5." 3
Otherwise, it will have no type.
.RE
.IP \(bu 2
Account aliases can disrupt account types.
.SS \f[CR]alias\f[R] directive
(Note: this section is about account aliases, not commodity aliases or
command aliases.)
.PP
\f[CR]alias\f[R] directives are a more general and powerful form of the
account aliases tags described above.
(There is also a runtime variant, defined with the \f[CR]\-\-alias\f[R]
option.)
.PP
Account alias rules rewrite your account names, or parts of them, after
reading the journal (affecting both directives and transactions), before
generating reports.
They do not affect account names being entered via hledger add or
hledger\-web.
.PP
Account aliases can be useful for:
.IP \(bu 2
expanding shorthand account names to their full form, allowing easier
data entry and a less verbose journal
.IP \(bu 2
adapting old journals to your current chart of accounts
.IP \(bu 2
experimenting with new account organisations, like a new hierarchy
.IP \(bu 2
combining two accounts into one, eg to see their sum or difference on
one line
.IP \(bu 2
customising reports
.SS Basic aliases
To set an account alias, use the \f[CR]alias\f[R] directive in your
journal file.
This affects all subsequent journal entries in the current file or its
included files (but note: not sibling or parent files; see directive
scopes).
The spaces around the = are optional:
.IP
.EX
alias OLD = NEW
.EE
.PP
Or, you can use \f[CR]\-\-alias \(aqOLD=NEW\(aq\f[R] on the command
line.
.PP
Or, for a declared account, you can write the alias as an
\f[CR]alias:\f[R] tag on its account directive.
.PP
OLD and NEW are case sensitive full account names.
hledger will replace any occurrence of the old account name with the new
one.
Subaccounts are also affected.
Eg:
.IP
.EX
alias checking = assets:bank:wells fargo:checking
; rewrites \(dqchecking\(dq to \(dqassets:bank:wells fargo:checking\(dq, or \(dqchecking:a\(dq to \(dqassets:bank:wells fargo:checking:a\(dq
.EE
.SS Regex aliases
There is also a more powerful variant that uses a regular expression,
indicated by wrapping the pattern in forward slashes.
(This is the only place where hledger requires forward slashes around a
regular expression.)
.PP
Eg:
.IP
.EX
alias /REGEX/ = REPLACEMENT
.EE
.PP
or:
.IP
.EX
$ hledger \-\-alias \(aq/REGEX/=REPLACEMENT\(aq ...
.EE
.PP
Any part of an account name matched by REGEX will be replaced by
REPLACEMENT.
REGEX is case\-insensitive as usual.
.PP
If you need to match a forward slash, escape it with a backslash, eg
\f[CR]/\(rs/=:\f[R].
.PP
If REGEX contains parenthesised match groups, these can be referenced by
the usual backslash and number in REPLACEMENT:
.IP
.EX
alias /\(ha(.+):bank:([\(ha:]+):(.*)/ = \(rs1:\(rs2 \(rs3
; rewrites \(dqassets:bank:wells fargo:checking\(dq to \(dqassets:wells fargo checking\(dq
.EE
.PP
REPLACEMENT continues to the end of line (or on command line, to end of
option argument), so it can contain trailing whitespace.
.SS \f[CR]\-\-alias\f[R] option
The \f[CR]\-\-alias\f[R] command line option defines an account alias,
using the same syntax as an \f[CR]alias\f[R] directive (basic or regex),
without editing your files.
Eg:
.IP
.EX
$ hledger bal \-\-alias checking=assets:bank:checking
$ hledger bal \-\-alias \(aq/\(haexpenses:(food|dining)/=expenses:food\(aq
.EE
.PP
It can be repeated to define more aliases.
These aliases affect all entries in all files (including CSV, timeclock
and timedot files), wherever the option appears on the command line; and
they are applied after any \f[CR]alias\f[R] directives or
\f[CR]alias:\f[R] tags (see Combining aliases).
They are not cleared by \f[CR]end aliases\f[R].
This makes \f[CR]\-\-alias\f[R] useful for trying out aliases
interactively, or for customising particular reports.
You can also put \f[CR]\-\-alias\f[R] options in a config file.
.SS Combining aliases
You can define as many aliases as you like, using journal directives
and/or command line options.
.PP
Recursive aliases \- where an account name is rewritten by one alias,
then by another alias, and so on \- are allowed.
Each alias sees the effect of previously applied aliases.
.PP
In such cases it can be important to understand which aliases will be
applied and in which order.
For (each account name in) each journal entry, we apply:
.IP "1." 3
\f[CR]alias\f[R] directives preceding the journal entry, most recently
parsed first (ie, reading upward from the journal entry, bottom to top)
.IP "2." 3
then any parent account from \f[CR]apply account\f[R] directives is
prepended
.IP "3." 3
then \f[CR]\-\-alias\f[R] options, in the order they appeared on the
command line (left to right).
.PP
In other words, for (an account name in) a given journal entry:
.IP \(bu 2
the nearest alias declaration before/above the entry is applied first
.IP \(bu 2
the next alias before/above that will be applied next, and so on
.IP \(bu 2
aliases defined after/below the entry do not affect it.
.PP
This gives nearby aliases precedence over distant ones, and helps
provide semantic stability \- aliases will keep working the same way
independent of which files are being read and in which order.
.PP
In case of trouble, adding \f[CR]\-\-debug=6\f[R] to the command line
will show which aliases are being applied when.
.SS Aliases and multiple files
As explained at Directive scopes, \f[CR]alias\f[R] directives (and
\f[CR]alias:\f[R] tags) do not affect parent or sibling files.
Eg in this command,
.IP
.EX
hledger \-f a.aliases \-f b.journal
.EE
.PP
account aliases defined in a.aliases will not affect b.journal.
Including the aliases doesn\(aqt work either:
.IP
.EX
include a.aliases
2023\-01\-01 ; not affected by a.aliases
foo 1
bar
.EE
.PP
This means that account aliases should usually be declared at the start
of your top\-most file, like this:
.IP
.EX
alias foo=Foo
alias bar=Bar
2023\-01\-01 ; affected by aliases above
foo 1
bar
include c.journal ; also affected
.EE
.PP
To affect all files read, whether they are included, or referenced by
\f[CR]\-f\f[R] or the \f[CR]import\f[R] command, use
\f[CR]\-\-alias\f[R] options (which could be in a config file).
Eg here the alias affects both a.journal and b.journal:
.IP
.EX
hledger \-f a.journal \-f b.journal \-\-alias foo=Foo
.EE
.SS \f[CR]end aliases\f[R] directive
This directive clears (forgets) all account aliases from
\f[CR]alias\f[R] directives and account \f[CR]alias:\f[R] tags seen so
far (but not aliases from command line \f[CR]\-\-alias\f[R] options):
.IP
.EX
end aliases
.EE
.SS Aliases can generate bad account names
Be aware that account aliases can produce malformed account names, which
could cause confusing reports or invalid \f[CR]print\f[R] output.
For example, you could erase all account names:
.IP
.EX
2021\-01\-01
a:aa 1
b
.EE
.IP
.EX
$ hledger print \-\-alias \(aq/.*/=\(aq
2021\-01\-01
1
.EE
.PP
The above \f[CR]print\f[R] output is not a valid journal.
Or you could insert an illegal double space, causing \f[CR]print\f[R]
output that would give a different journal when reparsed:
.IP
.EX
2021\-01\-01
old 1
other
.EE
.IP
.EX
$ hledger print \-\-alias old=\(dqnew USD\(dq | hledger \-f\- print
2021\-01\-01
new USD 1
other
.EE
.SS Aliases and account types
If an account with a type declaration (see Declaring accounts > Account
types) is renamed by an alias, normally the account type remains in
effect.
.PP
However, renaming in a way that reshapes the account tree (eg renaming
parent accounts but not their children, or vice versa) could prevent
child accounts from inheriting the account type of their parents.
.PP
Secondly, if an account\(aqs type is being inferred from its name,
renaming it by an alias could prevent or alter that.
.PP
If you are using account aliases and the \f[CR]type:\f[R] query is not
matching accounts as you expect, try troubleshooting with the accounts
command, eg something like:
.IP
.EX
$ hledger accounts \-\-types \-1 \-\-alias assets=bassetts
.EE
.SS \f[CR]assert\f[R] directive
In addition to the point\-in\-time balance assertions in transaction
entries, you can use \f[CR]assert\f[R] directives to declare more
general \f[B]journal assertions\f[R].
These are special queries asserting that certain report results do or do
not exist at specified times.
Like balance assertions, hledger checks these each time it reads the
journal, unless you use \f[CR]\-\-ignore\-assertions\f[R] or
\f[CR]\-I\f[R].
You can declare conditions or goals that you want to be upheld, and
whenever hledger reads the journal, if any rule is broken, it will
report an error.
Think \(dqguard rails for your finances\(dq.
(Note, a rule is only as good as its query, so test your new rules.)
.PP
The syntax is:
.IP
.EX
assert (none|some)[ PERIODEXPR][ QUERY]
.EE
.PP
Ie, the \f[CR]assert\f[R] keyword followed by \f[CR]none\f[R] or
\f[CR]some\f[R], then an optional period expression specifying when to
check the assertion, then a two\-or\-more\-spaces delimiter and a query
specifying which postings or report rows to look for.
The query is written as on the command line, with quotes around terms
containing spaces.
A \f[CR];\f[R] comment can follow.
.PP
A rule with a report interval can be followed by indented
\f[CR]skip\f[R] lines, each naming a date or period whose checks should
be skipped, with an optional comment (useful for recording the reason).
These skip checks, not data: postings in a skipped period still count in
later balances.
As usual, a range\(aqs end date is exclusive.
Eg:
.IP
.EX
assert none daily type:A balance:<0 ; no asset account is ever negative
skip 2026\-03\-04..2026\-03\-08 ; transfer delayed by the bank holiday
skip 2026\-05 ; moving house
.EE
.PP
A check is skipped if a date in a \f[CR]skip\f[R] line is among the
dates it examines.
For a rule with a \f[CR]balance:\f[R] term and no \f[CR]change:\f[R]
term, that is the period\(aqs last day (where its balance is tested);
for other rules, it\(aqs any day in the period.
.PP
Here are some examples.
(Aligning is optional; just remember to put at least two spaces before
each query.):
.IP
.EX
assert none ; no postings exist
assert some ; some postings exist
; journal maintenance
assert some desc:\(aqopening balances\(aq ; the journal has an opening balances entry
assert none assets:oldbank date:2025\- ; nothing is posted to a closed account
assert some assets:checking date:\(aq\-7 days..\(aq ; bank data has been imported/added recently
; income
assert some monthly to this month income:salary ; there\(aqs a salary transaction in each past month
assert none monthly to this month income:salary change:<2000 ; at least this much was earned in each past month
assert none monthly to this month income:salary change:>\-2000 ; a more careful signed test, handling contrabalances & sign typos
assert some monthly to this month desc:invoice any:\(aqreceivable amt:>0\(aq ; an invoice was sent in each past month
assert some monthly to this month desc:\(aqpayment for.*invoice\(aq ; an invoice payment was received in each past month
assert none assets:receivable balance:>15000 ; unpaid invoices are less than this, currently
; assets
assert none daily type:A balance:<0 ; no asset account is ever negative (at end of day), in any commodity
assert none daily assets:savings balance:<+10000 ; savings never drop below this much
assert some assets:savings balance:>=+20000 ; savings hold at least this much, currently
assert some monthly to this month not:tag:clopen assets:investments depth:2 change:>300 ; at least this much was invested in each past month (ignoring closing/opening entries)
; assets and liabilities
assert some taxes type:AL depth:0 balance:>0 ; estimated tax savings exceed estimated tax due, currently
; liabilities
assert some monthly to this month liabilities:card amt:>0 any:\(aqassets amt:<0\(aq ; a credit card payment was made in each past month
assert none monthly liabilities:card balance:<\-3000 ; no month ends with more than this much owed on the credit card
assert none liabilities:card balance:<\-500 ; current credit card balance is less than this
; expenses
assert none expenses:misc amt:>+10 ; no single misc expense is larger than this (in any currency)
assert none monthly expenses:dining change:>+$300 ; no month has more than this much $ dining expense
assert none monthly expenses:dining depth:2 change:>+$300 ; the same, but include subaccounts like expenses:dining:fine
.EE
.PP
Most query terms, like \f[CR]desc:\f[R], \f[CR]acct:\f[R], or
\f[CR]amt:\f[R], select postings.
\f[CR]balance:\f[R] and \f[CR]change:\f[R] terms instead test the
balance or change of the accounts those postings are in.
.SS How assert rules work
Assert rules are checked whenever the journal is read: by every command,
and by hledger\-ui and hledger\-web when they reload (unless disabled
with \f[CR]\-I\f[R]/\f[CR]\-\-ignore\-assertions\f[R], eg while you work
on a failing rule).
This happens after the journal is fully processed (after auto postings,
transaction balancing, balance assertions and lot calculation), so rules
see generated postings and lot subaccounts, and forecast transactions
when \f[CR]\-\-forecast\f[R] is used.
Rules are checked in the order they were read, and the first rule that
fails stops reading, with an error.
.PP
Their scope is the file tree: an assert rule sees all entries in the
main file and its included files, before and after it, but not entries
read by other \f[CR]\-f\f[R] options.
To check some extra rules without adding them to the journal, give them
to the check command as quoted arguments: eg
\f[CR]hledger check \(aqassert none daily type:A balance:<0\(aq\f[R].
.PP
Each rule is checked as if by a balance report,
\f[CR]hledger bal \-E QUERY\f[R], in four steps:
.IP "1." 3
\f[B]Select postings.\f[R] The query\(aqs ordinary terms select and
prepare postings as \f[CR]balance\f[R] would: costs are ignored (amounts
are summed in their original commodities), and \f[CR]depth:\f[R] clips
account names, merging subaccounts into their parent.
\f[CR]date:\f[R] terms don\(aqt select postings; they limit the report
period, like \f[CR]\-b\f[R]/\f[CR]\-e\f[R].
.IP "2." 3
\f[B]Calculate report rows.\f[R] The selected postings are summed by
account.
Each row has the account\(aqs change during the period, and its balance
at the end of the period (including all earlier postings, like
\f[CR]bal \-H\f[R]).
The rows are the accounts with selected postings in the period, plus,
when the query has a \f[CR]balance:\f[R] term, accounts with only
earlier postings (their change is zero but their balance may not be).
.IP "3." 3
\f[B]Filter rows.\f[R] \f[CR]change:\f[R] terms test each row\(aqs
change, and \f[CR]balance:\f[R] terms test its end balance; a query can
have both.
Without these terms every row matches, so the rule is simply about
whether any postings were selected.
.IP "4." 3
\f[B]Test.\f[R] \f[CR]none\f[R] passes if no row matches, and
\f[CR]some\f[R] passes if at least one does.
.PP
These steps are done at one or more checkpoints, in date order:
.IP \(bu 2
With no period expression, there is one checkpoint, covering the whole
journal (or the \f[CR]date:\f[R] terms\(aq span).
So \f[CR]balance:\f[R] tests the balances at the end of the journal, and
\f[CR]change:\f[R] tests the total change.
.IP \(bu 2
With a period expression, each of its periods is a checkpoint, and the
rule must pass at every one.
The periods are those \f[CR]bal\f[R] would show with that report
interval and \f[CR]\-b START \-e END\f[R].
Eg \f[CR]daily\f[R] checks each day\(aqs end balances or changes;
\f[CR]monthly from 2024\f[R] checks each month from 2024 on.
.IP \(bu 2
A period with no rows passes a \f[CR]none\f[R] rule and fails a
\f[CR]some\f[R] rule.
.IP \(bu 2
Relative dates in the period expression and query are resolved from
today\(aqs date, so a rule like
\f[CR]assert some assets:checking date:\(aq\-7 days..\(aq\f[R] can
start failing just because time passes.
.IP \(bu 2
Daily is the smallest checking interval (\f[CR]assert\f[R] does not
check after every transaction).
.PP
So you can check \(dqno asset account is ever negative (at end of
day)\(dq with \f[CR]assert none daily type:A balance:<0\f[R].
Without \f[CR]daily\f[R], only the final balances would be checked.
.PP
When a rule fails, the error shows the rule, every period in which it
failed, and up to 10 of the rows (or postings) which matched in those
periods.
Only the first failing rule is reported; others may be failing too.
.PP
These assertions have a cost: each rule makes reading the journal
slightly slower.
Rules matching few postings cost less, and \f[CR]balance:\f[R] rules
checked daily across many accounts cost more.
.SS Tips for writing assert rules
.IP \(bu 2
\f[B]\f[CB]none\f[B] gives more useful errors.\f[R] When you have a
choice, prefer \f[CR]none\f[R], because when it fails it shows the
offending rows, whereas a failing \f[CR]some\f[R] rule can only say
nothing matched.
.IP \(bu 2
\f[B]For more precise amount tests, add a sign and/or commodity.\f[R] A
plain number, as in \f[CR]balance:>100\f[R], ignores sign, and matches
if any commodity\(aqs amount does.
Often that is enough, but if you want to handle contrabalances or sign
typos, add a sign: \f[CR]balance:>+100\f[R].
And to limit the test to one commodity, add its symbol, as in
\f[CR]balance:<\-$5000\f[R], or add a \f[CR]cur:\f[R] term.
.IP \(bu 2
\f[B]Subaccounts are not included by default.\f[R] Each row\(aqs amount
is the account\(aqs own exclusive change or balance (like \f[CR]=\f[R]
in a balance assertion).
To include subaccount balances, limit the depth: eg
\f[CR]expenses:dining depth:2\f[R] folds \f[CR]expenses:dining\f[R]\(aqs
subaccounts into it.
(To fold just some accounts, use \f[CR]depth:REGEX=N\f[R].)
.IP \(bu 2
\f[B]\f[CB]depth:0\f[B] folds all matched accounts into one row.\f[R]
This lets you test two accounts of opposite sign against each other.
Eg \(dqsavings always cover the credit card debt\(dq is
\f[CR]assert none daily acct:\(aq\(ha(assets:savings|liabilities:card)\(aq depth:0 balance:<0\f[R].
.IP \(bu 2
\f[B]\f[CB]date:\f[B] terms combine with the period expression\(aqs
span.\f[R] Eg
\f[CR]assert none monthly assets date:2026\- balance:<0\f[R] means the
same as \f[CR]assert none monthly from 2026 assets balance:<0\f[R].
\f[CR]to thismonth\f[R] is useful for \(dqevery past month\(dq rules,
excluding the current incomplete month.
.IP \(bu 2
\f[B]Avoid \f[CB]not:date:\f[B] in rules with a \f[CB]balance:\f[B]
term.\f[R] It does not skip that date\(aqs check, it removes that
date\(aqs postings from all later balances.
Use \f[CR]skip\f[R] lines instead.
.IP \(bu 2
\f[B]Account names are matched after account aliases have been
applied\f[R], as in reports.
.SS \f[CR]comment\f[R] directive
A line containing just \f[CR]comment\f[R] causes all following lines to
be ignored, until an end comment directive or file end.
.SS \f[CR]end comment\f[R] directive
A line containing just \f[CR]end comment\f[R] ends the effect of a
preceding comment directive.
.SS \f[CR]commodity\f[R] directive
\f[CR]commodity\f[R] directives declare commodity symbols (for error
checking) and their preferred display style (digit group marks, decimal
digits, and symbol position).
Eg:
.IP
.EX
commodity $1,000.00
commodity 1000,00 EUR
commodity ₹ 1,00,00,000.00
commodity 1000. ; the no\-symbol commodity
.EE
.PP
The sample amount must include a decimal mark (even if there are no
decimal digits after it).
This tells the parser which decimal mark (period or comma) is used for
this commodity in the journal file, which can be useful in case of
ambiguous digit group marks.
This affects subsequent entries in the current file, its included files,
and the rest of any parent files (see directive scopes), and it can be
overridden by a \f[CR]decimal\-mark\f[R] directive.
.SS Commodity directive syntax
In more detail.
A commodity directive is normally the word \f[CR]commodity\f[R] followed
by a sample amount (only its format is significant), and optionally a
comment.
Eg:
.IP
.EX
commodity $1000.00
commodity 1.000,00 EUR
commodity 1 000 000.0000 ; the no\-symbol commodity
.EE
.PP
A commodity directive\(aqs sample amount must always include a decimal
mark (period or comma).
If you don\(aqt want to show any decimal digits, write the decimal mark
at the end:
.IP
.EX
commodity 1000. AAAA ; show AAAA with no decimals
.EE
.PP
Commodity symbols containing spaces, numbers, or punctuation must be
enclosed in double quotes, as usual:
.IP
.EX
commodity 1.0000 \(dqAAAA 2023\(dq
.EE
.PP
Commodity directives normally include a sample amount, but can declare
only a symbol (ie, just function 1 above):
.IP
.EX
commodity $
commodity INR
commodity \(dqAAAA 2023\(dq
commodity \(dq\(dq ; the no\-symbol commodity
.EE
.PP
Commodity directives may also be written with an indented
\f[CR]format\f[R] subdirective, as in Ledger.
The symbol is repeated and must be the same in both places.
Other subdirectives are ignored:
.IP
.EX
; display indian rupees with currency name on the left,
; thousands, lakhs and crores comma\-separated,
; period as decimal point, and two decimal places.
commodity INR
format INR 1,00,00,000.00
other subdirective ; ignored
.EE
.PP
A commodity can be declared more than once, eg in a main file and an
included file, or in several files read with \f[CR]\-f\f[R].
The later declaration will override or add to the earlier one, as
follows: its display style (if it has one) replaces the earlier style,
its tags take precedence over the earlier tags, and its aliases are
added to the earlier aliases.
(\(dqLater\(dq means later in the order hledger reads them: through each
file and its included files, then the next \f[CR]\-f\f[R] file.)
\f[CR]\-\-debug=1\f[R] shows any commodities which files read with
\f[CR]\-f\f[R] declare with different display styles.
.SS Commodity tags
A commodity directive\(aqs comment may contain tags.
These will be inherited by all postings using that commodity in their
main amount, except where the posting already has a value for that tag.
(A posting tag or an account tag overrides a commodity tag.)
Note, these tags will be queryable but won\(aqt be shown in
\f[CR]print\f[R] output, even with \-\-verbose\-tags.
.SS Commodity aliases
An \f[CR]alias:\f[R] tag on a commodity directive declares another
symbol/name for that commodity.
You can add several (quoting any that contain spaces or other special
characters, as usual):
.IP
.EX
commodity USD 1.00 ; alias: $, alias: US$, alias: \(dqus dollars\(dq
.EE
.PP
When hledger reads the journal, amounts written with an alias are
converted to the canonical commodity.
So they combine with it in reports, and a transaction can balance across
them.
This helps when, eg, your bank data, manual entries and downloaded
market prices use different symbols for the same currency.
Declare the symbol you want reports to show, and the others as its
aliases.
.PP
Some details:
.IP \(bu 2
\f[CR]print\f[R] shows amounts as they were written;
\f[CR]print \-x\f[R] shows them converted to the canonical commodity.
.IP \(bu 2
\f[CR]cur:\f[R] queries match the canonical symbol, not the aliases
(with the above declaration, \f[CR]$5\f[R] would be matched by
\f[CR]cur:USD\f[R], and not by \f[CR]cur:\(aq\(rs$\(aq\f[R]).
.IP \(bu 2
An alias can\(aqt have aliases of its own, and the same alias can\(aqt
be declared on two different commodities.
.SS Commodity units
A commodity alias can also specify a quantity.
Amounts written with the alias are divided by this quantity (and their
unit costs and market prices are multiplied by it).
This is useful for expressing differently\-sized units of a commodity.
Eg:
.IP
.EX
commodity 1.00 hrs ; alias: 60 min
commodity $1.00 ; alias: 0.001 K, alias: 0.000001 M
.EE
.PP
(Avoid decimal commas here, which would end the tag\(aqs value; use
\f[CR].\f[R], or exponential notation, \f[CR]alias: 1E\-6 M\f[R].)
.PP
You can report in any of these units, eg with \f[CR]\-X min\f[R] or
\f[CR]\-X M\f[R] (valuation, described later).
.PP
Note, these units keep the symbol placement they were declared with, but
inherit the canonical commodity\(aqs number format and
display/transaction\-balancing precisions.
If you want them to have a different display style, eg more decimals to
make small quantities visible, give them a \f[CR]commodity\f[R]
directive too:
.IP
.EX
commodity $1.00 ; alias: 0.001 K, alias: 0.000001 M
commodity 1.000 K
commodity 1.000000 M
.EE
.PP
When the conversion gives a repeating decimal (like 1/60 hour per
minute), it is stored internally at maximum precision (255 decimals, see
Amount arithmetic).
To keep costs and balance assertions exact, a unit cost on such an
amount is replaced by the exact total cost (\f[CR]10 min \(at $1\f[R]
becomes \f[CR]0.1666... hrs \(at\(at $10\f[R]), and balance assertions
add up the alias amounts before converting them (so three
\f[CR]10 min\f[R] amounts satisfy a \f[CR]= 0.5 hrs\f[R] assertion).
.SS Commodity aliases or market prices?
Both let you convert between symbols.
When should you use one or the other ?
.PP
Use a commodity alias when the symbols mean the same thing in different
names or units (\f[CR]$\f[R] and \f[CR]USD\f[R], \f[CR]min\f[R] and
\f[CR]hrs\f[R]).
The conversion happens always and automatically.
.PP
Use a \f[CR]P\f[R] directive when they are different things with an
exchange rate, even a fixed one.
The conversion happens only when you ask for it.
.SS Commodity alias scope
Commodity aliases (with or without a quantity) work in two ways, with
different scopes:
.IP \(bu 2
When hledger reads the journal, they convert the amounts written with
them, in their own file tree only (before or after the directive).
A file read with another \f[CR]\-f\f[R] option is a separate file tree,
so its amounts are not converted.
To share aliases between journals, put the \f[CR]commodity\f[R]
directives in a file which they all \f[CR]include\f[R] (or which
includes them all).
.IP \(bu 2
With \f[CR]\-X\f[R], they also act as fixed exchange rates in all file
trees, as a last resort when market prices can\(aqt do the conversion
(see Finding market price).
Eg \f[CR]\-X USD\f[R] can convert \f[CR]$\f[R] amounts in another file
tree that didn\(aqt declare that alias.
.SS Commodity error checking
In strict mode (\f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R]) (or when you run
\f[CR]hledger check commodities\f[R]), hledger will report an error if
an undeclared commodity symbol is used (aliases count as declared).
There\(aqs one exception: zero amounts are always allowed to have no
commodity symbol.
.SS \f[CR]decimal\-mark\f[R] directive
You can use a \f[CR]decimal\-mark\f[R] directive to declare
unambiguously which character (period or comma) represents a decimal
mark, for all subsequent amounts in the current file and its included
files (see directive scopes).
This helps when parsing ambiguous numbers (like \f[CR]1.000\f[R] or
\f[CR]1,000\f[R] where you mean one thousand, not one).
It also makes hledger check that numbers use that decimal mark and no
other, which catches some typos and misparsed numbers.
With \f[CR]decimal\-mark ,\f[R], a number like \f[CR]1,000.00\f[R] is
reported as an error; and with \f[CR]decimal\-mark .\f[R], a number like
\f[CR]1.2.34\f[R] is reported as an error, instead of being read as
\f[CR]1234\f[R].
.PP
Eg, at the top of each journal file:
.IP
.EX
decimal\-mark .
.EE
.PP
or
.IP
.EX
decimal\-mark ,
.EE
.PP
This directive only affects parsing, and it takes precedence over
\f[CR]commodity\f[R] directives.
So you can declare preferred decimal marks for display, which may be
different from the decimal mark(s) used in the data files.
(The amounts in \f[CR]commodity\f[R] and \f[CR]D\f[R] directives are
allowed to use a different decimal mark.)
.PP
Without a \f[CR]decimal\-mark\f[R] directive, a \f[CR]commodity\f[R]
directive\(aqs decimal mark is used to interpret that commodity\(aqs
ambiguous numbers, but it is not enforced: numbers like
\f[CR]1.2.34\f[R] or \f[CR]1.000,00\f[R] (when the format is
\f[CR]1,000.00\f[R]) are accepted.
So if you want these checks, use \f[CR]decimal\-mark\f[R].
.SS \f[CR]include\f[R] directive
You can pull in the content of additional files by writing an include
directive, like this:
.IP
.EX
include SOMEFILE
.EE
.PP
This has the same effect as if SOMEFILE\(aqs content was inlined at this
point.
(With any include directives in SOMEFILE processed similarly,
recursively.)
.PP
Only journal files can include other files.
They can include journal, timeclock, timedot, CSV/SSV/TSV, or CSV rules
files.
.PP
When a CSV file is included, its rules file is \f[CR]FILE.rules\f[R]
alongside it, as usual; the \f[CR]\-\-rules\f[R] option is not used
here.
To use a different rules file, or a data file located elsewhere (eg in
your downloads directory), include a rules file which has a source rule
instead.
Transactions generated from included CSV data are treated like inlined
journal entries: they are placed at this point, any account aliases in
effect are applied to them, and their balance assertions are checked
along with the rest of the journal (unlike when reading a CSV file
directly, where balance assertions are ignored).
Other directives which affect journal parsing (like \f[CR]Y\f[R],
\f[CR]D\f[R], \f[CR]decimal\-mark\f[R], \f[CR]apply account\f[R]) do not
affect CSV data.
Note that if you include a CSV file in your main journal, you should not
also import it, or its transactions would be duplicated.
.PP
If the file path begins with a tilde, that means your home directory:
\f[CR]include \(ti/main.journal\f[R].
.PP
If it begins with a slash, it is an absolute path:
\f[CR]include /home/user/main.journal\f[R].
Otherwise it is relative to the including file\(aqs folder:
\f[CR]include ../finances/main.journal\f[R].
.PP
Also, the path may have a file type prefix to force a specific file
format, overriding the file extension(s) (as described in Data formats):
\f[CR]include timedot:notes/2023.md\f[R].
.PP
The path may contain glob patterns to match multiple files.
hledger\(aqs globs are similar to zsh\(aqs: \f[CR]?\f[R] to match any
character; \f[CR][a\-z]\f[R] to match any character in a range;
\f[CR]*\f[R] to match zero or more characters that aren\(aqt a path
separator (like \f[CR]/\f[R]); \f[CR]**\f[R] to match zero or more
subdirectories and/or zero or more characters at the start of a file
name; etc.
For convenience, \f[CR]include\f[R] always excludes the current file.
So, you can do
.IP \(bu 2
\f[CR]include *.journal\f[R] to include all other journal files in the
current directory (excluding dot files)
.IP \(bu 2
\f[CR]include **.journal\f[R] to include all other journal files in this
directory and below (excluding dot files and top\-level dot directories)
.IP \(bu 2
\f[CR]include timelogs/2???.timedot\f[R] to include all timedot files
named like a year number.
.PP
Note \f[CR]*\f[R] and \f[CR]**\f[R] usually won\(aqt match dot files or
dot directories, with one exception: \f[CR]**\f[R] does search
non\-top\-level dot directories.
If this causes problems, make your glob pattern more specific (eg
\f[CR]**.journal\f[R] instead of \f[CR]**\f[R]).
.PP
To see all the files being read, and which file includes each one, run
\f[CR]hledger files \-\-tree\f[R].
.PP
If you are using many, or deeply nested, include files, and have an
error that\(aqs hard to pinpoint: a good troubleshooting command is
\f[CR]hledger files \-\-debug=6\f[R] (or 7).
.SS \f[CR]P\f[R] directive
The \f[CR]P\f[R] directive declares a market price, which is a
conversion rate between two commodities on a certain date.
This allows value reports to convert amounts of one commodity to their
value in another, on or after that date.
These prices are often obtained from a stock exchange, cryptocurrency
exchange, or the foreign exchange market.
.PP
The format is:
.IP
.EX
P DATE COMMODITY1SYMBOL COMMODITY2AMOUNT
.EE
.PP
DATE is a simple date, COMMODITY1SYMBOL is the symbol of the commodity
being priced, and COMMODITY2AMOUNT is the amount (symbol and quantity)
of commodity 2 that one unit of commodity 1 is worth on this date.
Examples:
.IP
.EX
# one euro was worth $1.35 from 2009\-01\-01 onward:
P 2009\-01\-01 € $1.35
# and $1.40 from 2010\-01\-01 onward:
P 2010\-01\-01 € $1.40
.EE
.PP
The \f[CR]\-V\f[R], \f[CR]\-X\f[R] and \f[CR]\-\-value\f[R] flags use
these market prices to show amount values in another commodity.
See Value reporting.
.PP
.SS \f[CR]payee\f[R] directive
\f[CR]payee PAYEE NAME\f[R]
.PP
This directive can be used to declare a limited set of payees which may
appear in transaction descriptions.
The \(dqpayees\(dq check will report an error if any transaction refers
to a payee that has not been declared.
(This is quite a strict check, and not often used.)
.PP
Eg:
.IP
.EX
payee Whole Foods ; a comment
.EE
.PP
To declare the empty payee name, use \f[CR]\(dq\(dq\f[R].
.IP
.EX
payee \(dq\(dq
.EE
.PP
Payees do not support tags.
Any indented subdirectives are ignored.
.SS \f[CR]tag\f[R] directive
\f[CR]tag TAGNAME\f[R]
.PP
This directive can be used to declare a limited set of tag names allowed
in tags.
TAGNAME should be a valid tag name (no spaces).
Eg:
.IP
.EX
tag item\-id
.EE
.PP
Any indented subdirectives are ignored.
.PP
The \(dqtags\(dq check will report an error if any undeclared tag name
is used.
It is quite easy to accidentally create a tag through normal use of
colons in comments; if you want to prevent this, you can declare and
check your tags.
.SS Periodic transactions
The \f[CR]\(ti\f[R] directive declares a \(dqperiodic rule\(dq which
generates temporary extra transactions, usually recurring at some
interval, when hledger is run with the \f[CR]\-\-forecast\f[R] flag.
These \(dqforecast transactions\(dq are useful for forecasting future
activity.
They exist only at report time, when \f[CR]\-\-forecast\f[R] is used;
they are not saved in the journal file.
.PP
Periodic rules also have a second use: with the \f[CR]\-\-budget\f[R]
flag they set budget goals for budgeting.
.PP
Periodic rules can be a little tricky, so before you use them, read this
whole section, or at least the following tips:
.IP "1." 3
Two spaces accidentally added or omitted in the rule will cause you
trouble \- see below.
.IP "2." 3
For troubleshooting, show the generated transactions with
\f[CR]hledger print \-\-forecast tag:generated\f[R] or
\f[CR]hledger register \-\-forecast tag:generated\f[R].
.IP "3." 3
Forecasted transactions will begin only after the last non\-forecasted
transaction\(aqs date.
.IP "4." 3
Forecasted transactions will end 6 months from today, by default.
See below for the exact start/end rules.
.IP "5." 3
Period expressions with report intervals can be tricky; note how they
make start/end date adjustments.
.SS Periodic rule syntax
A periodic transaction rule looks like a normal journal entry, with the
date replaced by a tilde (\f[CR]\(ti\f[R]) followed by a period
expression (mnemonic: \f[CR]\(ti\f[R] looks like a recurring sine
wave.):
.IP
.EX
# every first of month
\(ti monthly
expenses:rent $2000
assets:bank:checking
# every 15th of month in 2023\(aqs second quarter:
\(ti monthly from 2023\-04\-15 to 2023\-06\-16
expenses:utilities $400
assets:bank:checking
.EE
.PP
The period expression is the same syntax used for specifying
multi\-period reports, just interpreted differently; there, it specifies
report periods; here it specifies recurrence dates (the periods\(aq
start dates).
.SS Periodic rules and relative dates
Partial or relative dates (like \f[CR]12/31\f[R], \f[CR]25\f[R],
\f[CR]tomorrow\f[R], \f[CR]last week\f[R], \f[CR]next quarter\f[R]) are
usually not recommended in periodic rules, since the results will change
as time passes.
If used, they will be interpreted relative to, in order of preference:
.IP "1." 3
the first day of the default year specified by a recent \f[CR]Y\f[R]
directive
.IP "2." 3
or the date specified with \f[CR]\-\-today\f[R]
.IP "3." 3
or the date on which you are running the report.
.PP
They will not be affected at all by report period or forecast period
dates.
.SS Two spaces between period expression and description!
If the period expression is followed by a transaction description, these
must be separated by \f[B]two or more spaces\f[R].
This helps hledger know where the period expression ends, so that
descriptions can not accidentally alter their meaning, as in this
example:
.IP
.EX
; 2 or more spaces needed here, so the period is not understood as \(dqevery 2 months in 2023\(dq
; ||
; vv
\(ti every 2 months in 2023, we will review
assets:bank:checking $1500
income:acme inc
.EE
.PP
So,
.IP \(bu 2
Do write two spaces between your period expression and your transaction
description, if any.
.IP \(bu 2
Don\(aqt accidentally write two spaces in the middle of your period
expression.
.SS Auto postings
The \f[CR]=\f[R] directive declares an \(dqauto posting rule\(dq, which
adds extra postings to existing transactions.
(Remember, postings are the account name & amount lines below a
transaction\(aqs date & description.)
.PP
In the journal, an auto posting rule looks quite like a transaction, but
instead of date and description it has \f[CR]=\f[R] (mnemonic:
\(dqmatch\(dq) and a query, like this:
.IP
.EX
= QUERY
ACCOUNT AMOUNT
...
.EE
.PP
Queries are just like command line queries; an account name substring is
most common.
Query terms containing spaces should be enclosed in single or double
quotes.
.PP
Each \f[CR]=\f[R] rule works like this: when hledger is run with the
\f[CR]\-\-auto\f[R] flag, wherever the QUERY matches a posting in the
journal, the rule\(aqs postings are added to that transaction,
immediately below the matched posting.
Note these generated postings are temporary, existing only for the
duration of the report, and only when \f[CR]\-\-auto\f[R] is used; they
are not saved in the journal file by hledger.
.PP
The postings can contain the special string \f[CR]%account\f[R] which
will be expanded to the account name of the matched account.
.PP
Generated postings\(aq amounts can depend on the matched posting\(aqs
amount.
So auto postings can be useful for, eg, adding tax postings with a
standard percentage.
AMOUNT can be:
.IP \(bu 2
a number with no commodity symbol, like \f[CR]2\f[R].
The matched posting\(aqs commodity symbol will be added to this.
.IP \(bu 2
a normal amount with a commodity symbol, like \f[CR]$2\f[R].
This will be used as\-is.
.IP \(bu 2
an asterisk followed by a number, like \f[CR]*2\f[R].
This will multiply the matched posting\(aqs amount (and total price, if
any) by the number.
.IP \(bu 2
an asterisk followed by an amount with commodity symbol, like
\f[CR]*$2\f[R].
This multiplies and also replaces the commodity symbol with this new
one.
.PP
Some examples:
.IP
.EX
; every time I buy food, schedule a dollar donation
= expenses:food
(liabilities:charity) $\-1
; when I buy a gift, also deduct that amount from a budget envelope subaccount
= expenses:gifts
assets:checking:gifts *\-1
assets:checking *1
2017/12/1
expenses:food $10
assets:checking
2017/12/14
expenses:gifts $20
assets:checking
.EE
.IP
.EX
$ hledger print \-\-auto
2017\-12\-01
expenses:food $10
assets:checking
(liabilities:charity) $\-1
2017\-12\-14
expenses:gifts $20
assets:checking
assets:checking:gifts \-$20
assets:checking $20
.EE
.PP
Note that depending fully on generated data such as this has some
drawbacks \- it\(aqs less portable, less future\-proof, less auditable
by others, and less robust (eg your balance assertions will depend on
whether you use or don\(aqt use \f[CR]\-\-auto\f[R]).
An alternative is to use auto postings in \(dqone time\(dq fashion \-
use them to help build a complex journal entry, view it with
\f[CR]hledger print \-\-auto\f[R], and then copy that output into the
journal file to make it permanent.
.SS Auto postings and multiple files
An auto posting rule can affect any transaction in the current file, or
in any parent file or child file.
Note, currently it will not affect sibling files (when multiple
\f[CR]\-f\f[R]/\f[CR]\-\-file\f[R] are used \- see #1212).
.SS Auto postings and dates
A posting date (or secondary date) in the matched posting, or (taking
precedence) a posting date in the auto posting rule itself, will also be
used in the generated posting.
.SS Auto postings and transaction balancing / inferred amounts / balance assertions
Currently, auto postings are added:
.IP \(bu 2
after missing amounts are inferred, and transactions are checked for
balancedness,
.IP \(bu 2
but before balance assertions are checked.
.PP
Note this means that journal entries must be balanced both before and
after auto postings are added.
.PP
This also means that you cannot have more than one auto\-posting with a
missing amount applied to a given transaction, as it will be unable to
infer amounts.
.SS Auto posting tags
Automated postings will have some extra tags:
.IP \(bu 2
\f[CR]generated\-posting:= QUERY\f[R] \- shows this was generated by an
auto posting rule, and the query
.IP \(bu 2
\f[CR]_generated\-posting:= QUERY\f[R] \- a hidden tag, which does not
appear in hledger\(aqs output.
This can be used to match postings generated \(dqjust now\(dq, rather
than generated in the past and saved to the journal.
.PP
Also, any transaction that has been changed by auto posting rules will
have these tags added:
.IP \(bu 2
\f[CR]modified:\f[R] \- this transaction was modified
.IP \(bu 2
\f[CR]_modified:\f[R] \- a hidden tag not appearing in the comment; this
transaction was modified \(dqjust now\(dq.
.SS Auto postings on forecast transactions only
Tip: you can can make auto postings that will apply to forecast
transactions but not recorded transactions, by adding
\f[CR]tag:_generated\-transaction\f[R] to their QUERY.
This can be useful when generating new journal entries to be saved in
the journal.
.SS Other syntax
hledger journal format supports quite a few other features, mainly to
make interoperating with or converting from Ledger easier.
Note some of the features below are powerful and can be useful in
special cases, but in general, features in this section are considered
less important or even not recommended for most users.
Downsides are mentioned to help you decide if you want to use them.
.SS Amount expressions
AKA \(dqinline math\(dq.
\f[I]Since 1.99.6\f[R]
.PP
A posting amount can also be a simple arithmetic expression, which
hledger calculates when reading the journal.
This saves doing sums by hand, and records how an amount was arrived at:
.IP
.EX
2026\-03\-02 groceries, two receipts
assets:checking
expenses:food $50.20 + $16.54 ; $66.74
2026\-03\-05 laptop, plus 5% sales tax
liabilities:card
expenses:equipment $800.00
expenses:tax $800.00 * 0.05 ; $40.00
2026\-03\-07 hardware store, 3 boxes of screws less a $2 coupon
liabilities:card
expenses:supplies 3 * $4.99 \- $2 ; $12.97
.EE
.PP
Downsides: Complicates standard bookkeeping notation; could obscure a
posting\(aqs true amount.
Makes it harder for other apps to read your journal.
.SS Amount expression syntax
.IP \(bu 2
You can use \f[CR]+\f[R], \f[CR]\-\f[R], \f[CR]*\f[R], \f[CR]/\f[R] and
parentheses.
\f[CR]*\f[R] and \f[CR]/\f[R] are done before \f[CR]+\f[R] and
\f[CR]\-\f[R]; otherwise it\(aqs left to right.
A minus sign can also go before parentheses, eg \f[CR]\-($1 + $2)\f[R].
.IP \(bu 2
Spaces around the operators are optional, except that a \f[CR]/\f[R]
right after a commodity symbol needs a space before it:
\f[CR]10 EUR / 4\f[R] works, \f[CR]10 EUR/4\f[R] is an error.
.IP \(bu 2
\f[CR]+\f[R] and \f[CR]\-\f[R] need amounts in the same commodity.
You can write the commodity just once, since a plain number takes the
other side\(aqs commodity: \f[CR]$10 + 5\f[R] is $15.
.IP \(bu 2
\f[CR]*\f[R] and \f[CR]/\f[R] need a plain number on at least one side,
eg \f[CR]$800.00 * 0.05\f[R], \f[CR]3 * $4.99\f[R] or
\f[CR]$100.00 / 3\f[R].
The result is in the other side\(aqs commodity.
So a plain number divided by an amount is in that amount\(aqs commodity,
as in Ledger; this is handy for inverting an exchange rate:
\f[CR]1 / 1.25 EUR\f[R] is 0.80 EUR.
.IP \(bu 2
A cost, lot annotation or balance assertion can follow an expression,
and applies to its result: \f[CR]10 EUR + 5 EUR \(at $1.10\f[R] is 15
EUR, costing $1.10 each.
.IP \(bu 2
A cost can be an expression too, eg \f[CR]1 GBP \(at (1 / 1.14 EUR)\f[R]
or \f[CR]3 AAPL \(at\(at $450 + $5\f[R].
.IP \(bu 2
Expressions can be used only in posting amounts (in journal format, or
in CSV rules) and transacted costs, not in cost basis annotations,
balance assertions, directives, or auto posting rule multipliers
(\f[CR]*AMT\f[R]).
.SS Amount expression rounding
The result of \f[CR]+\f[R] or \f[CR]\-\f[R] is exact, and shows as many
decimal places as the more precise of the two amounts.
.PP
The result of \f[CR]*\f[R] or \f[CR]/\f[R] is rounded, using banker\(aqs
rounding, to the entry\(aqs decimal places for that commodity: the most
decimal places written in that commodity\(aqs amounts in the entry,
including amounts inside expressions or balance assignments, but not
cost amounts, or the plain numbers used with \f[CR]*\f[R] or
\f[CR]/\f[R].
These are the same decimal places hledger uses to check that the entry
balances (see Transaction balancing).
So:
.IP \(bu 2
\f[CR]$100/3\f[R] is $33.33 in an entry that also has
\f[CR]$\-100.00\f[R], but $33 when all of the entry\(aqs dollar amounts
are whole numbers.
.IP \(bu 2
\f[CR]$10 * 0.15\f[R] on its own is $2; write \f[CR]$10.00 * 0.15\f[R]
to get $1.50.
.IP \(bu 2
For more decimal places, write more: \f[CR]$100.0000 / 3\f[R] is
$33.3333.
.IP \(bu 2
In periodic transaction rules and auto posting rules, a result is
rounded to its own decimal places, eg \f[CR]$100/3\f[R] is $33 and
\f[CR]$100.00/3\f[R] is $33.33.
.IP \(bu 2
A result with no commodity gets the default commodity from a
\f[CR]D\f[R] directive, if any, as usual.
It is then like any other plain number after a \f[CR]D\f[R] directive,
whose decimal places count: after \f[CR]D $1,000.00\f[R],
\f[CR]5 / 2\f[R] is $2.50.
.PP
A cost calculated with \f[CR]*\f[R] or \f[CR]/\f[R] is not rounded,
since a rounded rate could be far off (\f[CR]$10 / 1.14\f[R] would be
$9).
hledger keeps it exact, and shows it with all its decimal places, or 8
if it\(aqs a repeating decimal (more if written), eg
\f[CR]1 GBP \(at $10 / 1.14\f[R] prints as
\f[CR]1 GBP \(at $8.77192982\f[R].
.PP
The rounded amount is what hledger stores (see also Where hledger
divides).
So a split that doesn\(aqt divide evenly leaves the entry unbalanced,
and the error message says that such amounts are rounded.
To fix it, leave one amount blank, and hledger will give it the
remainder:
.IP
.EX
2026\-03\-09 dinner with Ana and Raj, split three ways
liabilities:card $\-107.00
assets:receivable:ana ($92.00 + $15.00) / 3 ; $35.67
assets:receivable:raj ($92.00 + $15.00) / 3 ; $35.67
expenses:food ; $35.66
.EE
.SS Amount expressions are not kept
hledger keeps only an expression\(aqs result.
\f[CR]print\f[R] (including \f[CR]\-\-export\f[R], and all its output
formats), other reports and error messages show the result, eg
\f[CR]$66.74\f[R], not \f[CR]$50.20 + $16.54\f[R].
If you need to keep the parts visible, write them in a comment too.
.SS Balance assignments
Ledger\-style balance assignments are also supported.
These are like balance assertions, but with no posting amount on the
left side of the equals sign; instead it is calculated automatically so
as to satisfy the assertion.
This can be a convenience during data entry, eg when setting opening
balances:
.IP
.EX
; starting a new journal, set asset account balances
2016/1/1 opening balances
assets:checking = $409.32
assets:savings = $735.24
assets:cash = $42
equity:opening balances
.EE
.PP
or when adjusting a balance to reality:
.IP
.EX
; no cash left; update balance, record any untracked spending as a generic expense
2016/1/15
assets:cash = $0
expenses:misc
.EE
.PP
The calculated amount depends on the account\(aqs balance in the
commodity at that point (which depends on the previously\-dated postings
of the commodity to that account since the last balance assertion or
assignment).
.PP
Downsides: using balance assignments makes your journal less explicit;
to know the exact amount posted, you have to run hledger or do the
calculations yourself, instead of just reading it.
Also balance assignments\(aq forcing of balances can hide errors.
These things make your financial data less portable, less future\-proof,
and less trustworthy in an audit.
.SS Balance assignments and costs
A cost in a balance assignment will cause the calculated amount to have
that cost attached:
.IP
.EX
2019/1/1
(a) = $1 \(at €2
.EE
.IP
.EX
$ hledger print \-\-explicit
2019\-01\-01
(a) $1 \(at €2 = $1 \(at €2
.EE
.SS Balance assignments and subaccounts
Subaccount\-inclusive balance assignments (\f[CR]=*\f[R] or
\f[CR]==*\f[R]) are also supported.
The calculated amount is posted to the account named, making its balance
including subaccounts equal the assigned balance; the subaccounts\(aq
balances are not changed.
\f[CR]=*\f[R] sets the balance in just the assigned commodity, while
\f[CR]==*\f[R] also clears any other commodities.
.IP
.EX
2026\-01\-01
liabilities:card $\-30
liabilities:loan $\-200
expenses
2026\-01\-15 a windfall pays off all liabilities
liabilities ==* $0
income:windfall
.EE
.IP
.EX
$ hledger print \-\-explicit date:2026\-01\-15
2026\-01\-15 a windfall pays off all liabilities
liabilities $230 ==* $0
income:windfall $\-230
$ hledger bal liabilities
$230 liabilities
$\-30 liabilities:card
$\-200 liabilities:loan
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.SS Balance assignments and multiple files
Balance assignments handle multiple files like balance assertions.
They see balance from other files previously included from the current
file, but not from previous sibling or parent files.
.SS Bracketed posting dates
For setting posting dates and secondary posting dates, Ledger\(aqs
bracketed date syntax is also supported: \f[CR][DATE]\f[R],
\f[CR][DATE=DATE2]\f[R] or \f[CR][=DATE2]\f[R] in posting comments.
hledger will attempt to parse any square\-bracketed sequence of the
\f[CR]0123456789/\-.=\f[R] characters in this way.
With this syntax, DATE infers its year from the transaction and DATE2
infers its year from DATE.
.PP
Downsides: another syntax to learn, redundant with hledger\(aqs
\f[CR]date:\f[R]/\f[CR]date2:\f[R] tags, and confusingly similar to
Ledger\(aqs lot date syntax.
.SS \f[CR]D\f[R] directive
\f[CR]D AMOUNT\f[R]
.PP
This directive sets a default commodity, to be used for any subsequent
commodityless amounts (ie, plain numbers) seen while parsing the
journal.
This affects subsequent entries until the next \f[CR]D\f[R] directive,
or the end of the current file (including its included files; see
directive scopes).
.PP
For compatibility/historical reasons, \f[CR]D\f[R] also acts like a
\f[CR]commodity\f[R] directive (setting the commodity\(aqs decimal mark
for parsing and display style for output).
So its argument is not just a commodity symbol, but a full amount
demonstrating the style.
The amount must include a decimal mark (either period or comma).
Eg:
.IP
.EX
; commodity\-less amounts should be treated as dollars
; (and displayed with the dollar sign on the left, thousands separators and two decimal places)
D $1,000.00
1/1
a 5 ; <\- commodity\-less amount, parsed as $5 and displayed as $5.00
b
.EE
.PP
Interactions with other directives:
.PP
For setting a commodity\(aqs display style, a \f[CR]commodity\f[R]
directive has highest priority, then a \f[CR]D\f[R] directive.
.PP
For detecting a commodity\(aqs decimal mark during parsing,
\f[CR]decimal\-mark\f[R] has highest priority, then
\f[CR]commodity\f[R], then \f[CR]D\f[R].
.PP
For checking commodity symbols with the check command, a
\f[CR]commodity\f[R] directive is required
(\f[CR]hledger check commodities\f[R] ignores \f[CR]D\f[R] directives).
.PP
Downsides: omitting commodity symbols makes your financial data less
explicit, less portable, and less trustworthy in an audit.
It is usually an unsustainable shortcut; sooner or later you will want
to track multiple commodities.
D is overloaded with functions redundant with \f[CR]commodity\f[R] and
\f[CR]decimal\-mark\f[R].
And it works differently from Ledger\(aqs \f[CR]D\f[R].
.SS \f[CR]apply account\f[R] directive
This directive sets a default parent account, which will be prepended to
all accounts in following entries, until an \f[CR]end apply account\f[R]
directive or end of current file.
Eg:
.IP
.EX
apply account home
2010/1/1
food $10
cash
end apply account
.EE
.PP
is equivalent to:
.IP
.EX
2010/01/01
home:food $10
home:cash $\-10
.EE
.PP
(If the parent account name ends with a colon
(\f[CR]apply account home:\f[R]), it is ignored, as in Ledger.)
.PP
\f[CR]account\f[R] directives are also affected, and so is any
\f[CR]include\f[R]d content.
.PP
Account names entered via hledger add or hledger\-web are not affected.
.PP
Account aliases from \f[CR]alias\f[R] directives are applied before the
parent account is prepended (as in Ledger), so they match the account
names as written.
This means a file\(aqs aliases keep working when it is included under
\f[CR]apply account\f[R].
(Before hledger 2, they were applied after.)
\f[CR]\-\-alias\f[R] options are applied after the parent account is
prepended, so they match the full account names.
.PP
Downsides: this can make your financial data less explicit, less
portable, and less trustworthy in an audit.
.SS \f[CR]Y\f[R] directive
\f[CR]Y YEAR\f[R]
.PP
or (deprecated backward\-compatible form):
.PP
\f[CR]year YEAR\f[R]
.PP
The space is optional.
This sets a default year to be used for subsequent dates which don\(aqt
specify a year.
Eg:
.IP
.EX
Y2009 ; set default year to 2009
12/15 ; equivalent to 2009/12/15
expenses 1
assets
year 2010 ; change default year to 2010
2009/1/30 ; specifies the year, not affected
expenses 1
assets
1/31 ; equivalent to 2010/1/31
expenses 1
assets
.EE
.PP
Downsides: omitting the year (from primary transaction dates, at least)
makes your financial data less explicit, less portable, and less
trustworthy in an audit.
Such dates can get separated from their corresponding Y directive, eg
when evaluating a region of the journal in your editor.
A missing Y directive makes reports dependent on today\(aqs date.
.SS \f[CR]apply year\f[R] directive
\f[CR]apply year YEAR\f[R] sets a default year like \f[CR]Y\f[R], but
only until a matching \f[CR]end apply year\f[R] directive (or the end of
the current file).
\f[CR]end apply year\f[R] restores the default year that was in effect
before the matching \f[CR]apply year\f[R].
These blocks can be nested, as in Ledger (which also lets a bare
\f[CR]end\f[R] or \f[CR]end apply\f[R] close them; hledger requires
\f[CR]end apply year\f[R]).
Eg:
.IP
.EX
Y 2009
apply year 2010
1/31 ; 2010\-01\-31
expenses 1
assets
end apply year
2/28 ; 2009\-02\-28
expenses 1
assets
.EE
.PP
An \f[CR]end apply year\f[R] with no matching \f[CR]apply year\f[R] is
an error.
(Before hledger 2, \f[CR]apply year\f[R] worked like \f[CR]Y\f[R], and
\f[CR]end apply year\f[R] was ignored.)
.SS Secondary dates
A secondary date is written after the primary date, following an equals
sign: \f[CR]DATE1=DATE2\f[R].
If the year is omitted, the primary date\(aqs year is assumed.
When running reports, the primary (left side) date is used by default,
but with the \f[CR]\-\-date2\f[R] flag (\f[CR]\-\-aux\-date\f[R]
or\f[CR]\-\-effective\f[R] also work, for Ledger users), the secondary
(right side) date will be used instead.
.PP
The meaning of secondary dates is up to you.
Eg it could be \(dqprimary is the bank\(aqs clearing date, secondary is
the date the transaction was initiated, if different\(dq.
.PP
In practice, this feature usually adds confusion:
.IP \(bu 2
You have to remember the primary and secondary dates\(aq meaning, and
follow that consistently.
.IP \(bu 2
It splits your bookkeeping into two modes, and you have to remember
which mode is appropriate for a given report.
.IP \(bu 2
Usually your balance assertions will work with only one of these modes.
.IP \(bu 2
It makes your financial data more complicated, less portable, and less
clear in an audit.
.IP \(bu 2
It interacts with every feature, creating an ongoing cost for
implementors.
.IP \(bu 2
It distracts new users and supporters.
.IP \(bu 2
Posting dates are simpler and work better.
.PP
So secondary dates are officially deprecated in hledger, remaining only
as a Ledger compatibility aid; we recommend using posting dates instead.
.SS Star comments
Lines beginning with \f[CR]*\f[R] (star/asterisk) are also comment
lines, for Ledger compatibility.
Emacs users can use these as foldable org headings.
(But it\(aqs usually better to use ledger\-mode, and add outshine minor
mode for org\-like folding.)
.SS Valuation expressions
Ledger allows a valuation function or value to be written in double
parentheses after an amount.
hledger ignores these.
.SS Virtual postings
A posting with parentheses around the account name, like
\f[CR](some:account) 10\f[R], is called an \f[I]unbalanced virtual
posting\f[R].
These postings do not participate in transaction balancing.
(And if you write them without an amount, a zero amount is always
inferred.)
These can occasionally be convenient for special circumstances, but they
violate double entry bookkeeping and make your data less portable across
applications, so many people avoid using them at all.
.PP
A posting with brackets around the account name
(\f[CR][some:account]\f[R]) is called a \f[I]balanced virtual
posting\f[R].
The balanced virtual postings in a transaction must add up to zero, just
like ordinary postings, but separately from them.
These are not part of double entry bookkeeping either, but they are at
least balanced.
An example:
.IP
.EX
2022\-01\-01 buy food with cash, update budget envelope subaccounts, & something else
assets:cash $\-10 ; <\- these balance each other
expenses:food $7 ; <\-
expenses:food $3 ; <\-
[assets:checking:budget:food] $\-10 ; <\- and these balance each other
[assets:checking:available] $10 ; <\-
(something:else) $5 ; <\- this is not required to balance
.EE
.PP
Ordinary postings, whose account names are neither parenthesised nor
bracketed, are called \f[I]real postings\f[R].
You can exclude virtual postings from reports with the
\f[CR]\-R/\-\-real\f[R] flag or a \f[CR]real:1\f[R] query.
.SS Other Ledger directives
These other Ledger directives are currently accepted but ignored.
This allows hledger to read more Ledger files, but be aware that
hledger\(aqs reports may differ from Ledger\(aqs if you use these.
.IP
.EX
apply fixed COMM AMT
apply tag TAG
bucket / A ACCT
capture ACCT REGEX
check EXPR
define VAR=EXPR
end apply fixed
end apply tag
end tag
eval / expr EXPR
python
PYTHONCODE
tag NAME
value EXPR
\-\-command\-line\-flags
.EE
.PP
Ledger\(aqs \f[CR]assert EXPR\f[R] directive is not supported:
\f[CR]assert\f[R] is hledger\(aqs assert directive, which has a
different syntax, so a Ledger\-style \f[CR]assert\f[R] line is an error.
.PP
See also https://hledger.org/ledger.html for a detailed hledger/Ledger
syntax comparison.
.SS Ledger virtual costs
In Ledger, \f[CR](\(at) UNITCOST\f[R] and
\f[CR](\(at\(at) TOTALCOST\f[R] are virtual costs, which do not generate
market prices.
In hledger, these are equivalent to \f[CR]\(at\f[R] and
\f[CR]\(at\(at\f[R].
.SS Ledger cost basis
In Ledger, these annotations after an amount help specify or select a
lot\(aqs cost basis: \f[CR]{LOTUNITCOST}\f[R] or
\f[CR]{{LOTTOTALCOST}}\f[R], \f[CR][LOTDATE]\f[R], and/or
\f[CR](LOTNOTE)\f[R].
hledger will read these, as an alternative to its own cost basis syntax.
.PP
We also read Ledger\(aqs fixed price syntax, \f[CR]{=LOTUNITCOST}\f[R]
or \f[CR]{{=LOTTOTALCOST}}\f[R], treating it as equivalent to
\f[CR]{LOTUNITCOST}\f[R] or \f[CR]{{LOTTOTALCOST}}\f[R].
.PP
.SH CSV
hledger can read transactions from CSV (comma\-separated values) files.
More precisely, it can read DSV (delimiter\-separated values), from a
file or standard input.
Comma\-separated, semicolon\-separated and tab\-separated are the most
common variants, and hledger recognises these three automatically from
the file extension.
.PP
(To learn about producing CSV or TSV \f[I]output\f[R], see Output
format.)
.PP
Each CSV file must be described by a corresponding \f[I]rules file\f[R].
This contains rules describing the CSV data (header line, fields layout,
date format etc.), how to construct hledger transactions from it, and
how to categorise transactions based on description or other attributes.
.PP
By default, hledger expects this rules file to be named like the CSV
file, with an extra \f[CR].rules\f[R] extension added, in the same
directory.
Eg when asked to read \f[CR]foo/FILE.csv\f[R], hledger looks for
\f[CR]foo/FILE.csv.rules\f[R].
You can specify a different rules file with the \f[CR]\-\-rules\f[R]
option (for CSV files specified on the command line; not for ones
included by a journal file).
.PP
At minimum, the rules file must identify the date and amount fields, and
often it also specifies the date format and how many header lines there
are.
Here\(aqs a simple CSV file and a rules file for it:
.IP
.EX
Date, Description, Id, Amount
12/11/2019, Foo, 123, 10.23
.EE
.IP
.EX
# basic.csv.rules
skip 1
fields date, description, , amount
date\-format %d/%m/%Y
.EE
.IP
.EX
$ hledger print \-f basic.csv
2019\-11\-12 Foo
expenses:unknown 10.23
income:unknown \-10.23
.EE
.PP
Or you can read the rules file itself, if it has a \f[CR]source\f[R]
rule saying where the data is (eg \f[CR]source ./basic.csv\f[R]):
\f[CR]hledger print \-f basic.csv.rules\f[R].
This is the usual setup for regular importing; see Finding the data.
.PP
There\(aqs an introductory Tutorial: Import CSV data on hledger.org, and
more CSV rules examples below, and a larger collection at
https://github.com/hledgerorg/hledger/tree/main/examples/csv.
.SS CSV rules cheatsheet
The following kinds of rule can appear in the rules file, in any order.
(Blank lines and lines beginning with \f[CR]#\f[R] or \f[CR];\f[R] are
ignored.)
.PP
.TS
tab(@);
lw(24.7n) lw(45.3n).
T{
\f[B]\f[CB]source\f[B]\f[R]
T}@T{
optionally declare which file to read data from
T}
T{
\f[B]\f[CB]archive\f[B]\f[R]
T}@T{
optionally enable an archive of imported files
T}
T{
\f[B]\f[CB]separator\f[B]\f[R]
T}@T{
declare the field separator, instead of relying on file extension
T}
T{
\f[B]\f[CB]encoding\f[B]\f[R]
T}@T{
optionally declare which text encoding the data has
T}
T{
\f[B]\f[CB]skip\f[B]\f[R]
T}@T{
skip header line(s) at start of file, or (inside an if rule) the current
record(s)
T}
T{
\f[B]\f[CB]date\-format\f[B]\f[R]
T}@T{
declare how to parse CSV dates/date\-times
T}
T{
\f[B]\f[CB]timezone\f[B]\f[R]
T}@T{
declare the time zone of ambiguous CSV date\-times
T}
T{
\f[B]\f[CB]decimal\-mark\f[B]\f[R]
T}@T{
declare the decimal mark used in CSV amounts, when ambiguous
T}
T{
\f[B]\f[CB]newest\-first\f[B]\f[R]
T}@T{
improve txn order when: there are multiple records, newest first, all
with the same date
T}
T{
\f[B]\f[CB]intra\-day\-reversed\f[B]\f[R]
T}@T{
improve txn order when: same\-day txns are in opposite order to the
overall file
T}
T{
\f[B]\f[CB]fields\f[B]\f[R]
T}@T{
name CSV fields for easy reference, and optionally assign their values
to hledger fields
T}
T{
\f[B]Field assignment\f[R]
T}@T{
assign a CSV value or interpolated text value to a hledger field
T}
T{
\f[B]\f[CB]balance\-type\f[B]\f[R]
T}@T{
select which type of balance assertions/assignments to generate
T}
T{
\f[B]\f[CB]if\f[B]\f[R]
T}@T{
conditionally assign values to hledger fields, or skip one or more
records
T}
T{
\f[B]\f[CB]ifs\f[B]\f[R]
T}@T{
declare multiple if rules in a compact table format
T}
T{
\f[B]\f[CB]end\f[B]\f[R]
T}@T{
(inside an if rule) skip the current and all remaining records
T}
T{
\f[B]\f[CB]merge\f[B]\f[R]
T}@T{
combine this record with the next one(s), to be converted to a single
transaction
T}
T{
\f[B]\f[CB]include\f[B]\f[R]
T}@T{
inline another CSV rules file
T}
.TE
.PP
Working with CSV tips and How CSV rules are evaluated can be found
below.
.SS Finding the data
You can name a CSV file on the command line, as in
\f[CR]hledger \-f foo.csv CMD\f[R], and hledger will use the rules file
named like it (\f[CR]foo.csv.rules\f[R]).
.PP
Or you can name the rules file, as in
\f[CR]hledger \-f foo.csv.rules CMD\f[R].
The rules file must then have a \f[CR]source\f[R] rule (described
below), saying which data file to read (perhaps in your web browser\(aqs
download directory), or which command to run to get the data.
.PP
The second way is more powerful.
This and the archive rule below, and the default behaviour of the get
and import commands, help remove the busywork of managing CSV downloads.
Ideally, you can periodically
.IP "1." 3
Download new CSVs from your banks (perhaps by just running
\f[CR]hledger get\f[R]).
.IP "2." 3
Import new transactions from all the CSVs specified by rules files in
\f[CR]rules/\f[R], by just running \f[CR]hledger import\f[R].
.PP
Or, do both with one command: \f[CR]hledger import \-g\f[R]
.PP
After import, you can discard the CSV immediately, or leave it where it
is for a while, or archive it automatically (to
\f[CR]data/archive/\f[R]) with the archive rule.
.PP
It\(aqs also possible to include a CSV file or rules file in your
journal, in which case there\(aqs no import step at all; instead, the
whole CSV is reconverted on each run.
.SS \f[CR]source\f[R]
When hledger reads a rules file (\f[CR]\-f foo.csv.rules\f[R]), the
\f[CR]source\f[R] rule says which data file to read (it is ignored if
you name the data file instead, as in \f[CR]\-f foo.csv\f[R]):
.IP
.EX
source ./Checking1.csv
.EE
.PP
If the file does not exist, it is just considered empty, without raising
an error.
.PP
A rules file (and any included rules file) can have only one
\f[CR]source\f[R] rule.
To read several data files, use a rules file for each; they can include
their common rules.
.PP
The file path is resolved this way:
.IP \(bu 2
Absolute paths and \f[CR]\(ti\f[R]\-prefixed paths are used as\-is.
.IP \(bu 2
A path beginning with \f[CR]./\f[R] or \f[CR]../\f[R]
(\f[CR]source ./Checking1.csv\f[R]) is anchored relative to the rules
file\(aqs directory (as in hledger 1).
.IP \(bu 2
Any other relative path (\f[CR]source bank/Checking1.csv\f[R]), or a
bare file name (\f[CR]source Checking1.csv\f[R]), is searched for first
in a \f[CR]data/\f[R] directory next to the main journal file (also used
by the \f[CR]archive\f[R] rule and the \f[CR]get\f[R] command), then in
your \f[CR]\(ti/Downloads\f[R] folder.
.PP
You can use a glob pattern, to avoid specifying the file name exactly:
.IP
.EX
source Checking1*.csv
.EE
.PP
A glob pattern has another benefit: if it matches multiple files,
hledger reads just one of them: the newest, so stale copies are ignored;
or when importing with \f[CR]archive\f[R], the oldest, which is then
archived, so that successive imports process the copies in order.
.SS Data cleaning / data generating commands
After \f[CR]source\f[R]\(aqs file pattern, you can write \f[CR]|\f[R]
(pipe) and a data cleaning command (or command pipeline) (since hledger
1.50).
If hledger\(aqs CSV rules aren\(aqt enough, you can pre\-process the
downloaded data here with a shell command or script, to make it more
suitable for conversion.
The command will be executed by your default shell, in the directory of
the rules file, will receive the data file\(aqs content as standard
input, and should output zero or more lines of
character\-separated\-values, suitable for conversion by the CSV rules.
.PP
Examples:
.IP
.EX
source ./paypal.json | paypalcsv
source data/simplefin.json | simplefincsv \- \(aqchase.*card\(aq
source OfxDownload*.csv | grep \-vE \(aq\(ha(([\(ha,]*,){6}[\(ha,]*|)$\(aq | sort \-t, \-n +2
source History_for_Account_Z20144832*.csv # | grep \-E \(aq\(ha([\(ha,]*,){12}[\(ha,]*$\(aq | sed \-E \-e \(aqs/\(ha //\(aq \-e \(aqs/\(rs.([0\-9]),/.\(rs10,/g\(aq \-e \(aqs/,([0\-9]+),/,\(rs1.00,/g\(aq
.EE
.PP
Or, after \f[CR]source\f[R] you can write \f[CR]|\f[R] and a data
generating command (with no file pattern before the \f[CR]|\f[R]).
This command receives no input, and should output zero or more lines of
character\-separated values, suitable for conversion by the CSV rules.
.PP
Examples:
.IP
.EX
source | paypaljson | paypalcsv
source | paypalcsv data/paypal.json
source | simplefinjson >data/simplefin.json && simplefincsv data/simplefin.json \(aqchase.*card\(aq
source | simplefincsv data/simplefin.json \(aqunify.*checking\(aq
.EE
.PP
(\f[CR]paypal*\f[R] and \f[CR]simplefin*\f[R] scripts are in bin/)
.PP
Whenever hledger runs one of these commands, it will echo the command on
stderr, prefixed by the rules file\(aqs name.
If the command produces error output, but exits successfully, hledger
will show the error output as a warning.
If a data cleaning command fails, hledger will fail and show the error
output in the error message.
If a data generating command fails, hledger will show the error as a
warning and continue, treating this as if no data was found.
.PP
These commands run in an \f[CR]import \-\-dry\-run\f[R] too, since their
output is needed to preview the data.
So they should be safe to run repeatedly: a data cleaning command should
be a pure filter, and a data generating command should not consume or
change anything that the real import will need.
A fetch that isn\(aqt safe to repeat belongs in the get command\(aqs
\f[CR]getdata\f[R] script instead (which \f[CR]get \-\-dry\-run\f[R] and
\f[CR]import \-\-dry\-run \-g\f[R] don\(aqt run), with a file pattern to
read its output.
.SS \f[CR]archive\f[R]
With \f[CR]archive\f[R] added to a rules file, the \f[CR]import\f[R]
command will archive each successfully processed data file or data
command output in an \f[CR]archive/\f[R] subdirectory of the
\f[CR]data/\f[R] directory next to the main journal file.
The archive file name will be based on the rules file and the data
file\(aqs modification date and extension (or for a data\-generating
command, the current date and the \(dq.csv\(dq extension).
The original data file, once archived, will be removed.
.PP
Also, in this mode \f[CR]import\f[R] will prefer the oldest file matched
by the \f[CR]source\f[R] rule\(aqs glob pattern, not the newest.
(So if there are multiple downloads, they will be imported and archived
oldest first.)
.PP
Archiving is optional, but it can be useful for troubleshooting your CSV
rules, regenerating entries with improved rules, checking for variations
in your bank\(aqs CSV, etc.
.SS File Extension
To help hledger choose the CSV file reader and show the right error
messages (and choose the right field separator character by default),
it\(aqs best if CSV/SSV/TSV files are named with a \f[CR].csv\f[R],
\f[CR].ssv\f[R] or \f[CR].tsv\f[R] filename extension.
(More about this at Data formats.)
.PP
When reading files with the \(dqwrong\(dq extension, you can ensure the
CSV reader (and the default field separator) by prefixing the file path
with \f[CR]csv:\f[R], \f[CR]ssv:\f[R] or \f[CR]tsv:\f[R]: Eg:
.IP
.EX
$ hledger \-f ssv:foo.dat print
.EE
.PP
You can also override the default field separator with a separator rule
if needed.
.SS Reading CSV from standard input
You\(aqll need the file format prefix when reading CSV from stdin also,
since hledger assumes journal format by default.
Eg:
.IP
.EX
$ cat foo.dat | hledger \-f ssv:\- print
.EE
.SS Reading multiple CSV files
If you use multiple \f[CR]\-f\f[R] options to read multiple CSV files at
once, hledger will look for a correspondingly\-named rules file for each
CSV file.
But if you specify a rules file with \f[CR]\-\-rules\f[R], that rules
file will be used for all the CSV files.
.PP
Alternatively, a journal file can include CSV files (or rules files).
In this case each CSV file always uses its correspondingly\-named rules
file; \f[CR]\-\-rules\f[R] has no effect.
.SS Reading the data
These tips and rules help hledger read the CSV data correctly: check
that it\(aqs valid, choose its separator, decode its text, skip any
header lines, parse its dates and numbers, and put its records in the
right order.
.SS Valid CSV
Note that hledger will only accept valid CSV conforming to RFC 4180, and
equivalent SSV and TSV formats (like RFC 4180 but with semicolon or tab
as separators).
This means, eg:
.IP \(bu 2
Values may be enclosed in double quotes, or not.
Enclosing in single quotes is not allowed.
(Eg \f[CR]\(aqA\(aq,\(aqB\(aq\f[R] is rejected.)
.IP \(bu 2
When values are enclosed in double quotes, spaces outside the quotes are
not allowed.
(Eg \f[CR]\(dqA\(dq, \(dqB\(dq\f[R] is rejected.)
.IP \(bu 2
When values are not enclosed in quotes, they may not contain double
quotes.
(Eg \f[CR]A\(dqA, B\f[R] is rejected.)
.PP
If your CSV/SSV/TSV is not valid in this sense, you\(aqll need to
transform it before reading with hledger.
Try using sed, or a more permissive CSV parser like python\(aqs csv lib.
.SS \f[CR]separator\f[R]
You can use the \f[CR]separator\f[R] rule to read other kinds of
character\-separated data.
The argument is any single separator character, or the words
\f[CR]tab\f[R] or \f[CR]space\f[R] (case insensitive).
Eg, for comma\-separated values (CSV):
.IP
.EX
separator ,
.EE
.PP
or for semicolon\-separated values (SSV):
.IP
.EX
separator ;
.EE
.PP
or for tab\-separated values (TSV):
.IP
.EX
separator TAB
.EE
.PP
If the input file has a \f[CR].csv\f[R], \f[CR].ssv\f[R] or
\f[CR].tsv\f[R] file extension (or a \f[CR]csv:\f[R], \f[CR]ssv:\f[R],
\f[CR]tsv:\f[R] prefix), the appropriate separator will be inferred
automatically, and you won\(aqt need this rule.
.SS \f[CR]encoding\f[R]
.IP
.EX
encoding ENCODING
.EE
.PP
hledger normally expects non\-ascii text to be using the system
locale\(aqs text encoding.
If you need to read CSV files which have some other encoding, you can do
it by adding \f[CR]encoding ENCODING\f[R] to your CSV rules.
Eg: \f[CR]encoding iso\-8859\-1\f[R].
.PP
The supported encodings are: \f[CR]ascii\f[R], \f[CR]utf\-8\f[R],
\f[CR]utf\-16\f[R], \f[CR]utf\-32\f[R], \f[CR]iso\-8859\-1\f[R] to
\f[CR]iso\-8859\-11\f[R] and \f[CR]iso\-8859\-13\f[R] to
\f[CR]iso\-8859\-16\f[R], \f[CR]cp1250\f[R] to \f[CR]cp1258\f[R],
\f[CR]koi8\-r\f[R], \f[CR]koi8\-u\f[R], \f[CR]gb18030\f[R],
\f[CR]macintosh\f[R], \f[CR]jis\-x\-0201\f[R], \f[CR]jis\-x\-0208\f[R],
\f[CR]iso\-2022\-jp\f[R], \f[CR]shift\-jis\f[R], \f[CR]cp437\f[R],
\f[CR]cp737\f[R], \f[CR]cp775\f[R], \f[CR]cp850\f[R], \f[CR]cp852\f[R],
\f[CR]cp855\f[R], \f[CR]cp857\f[R], \f[CR]cp860\f[R] to
\f[CR]cp866\f[R], \f[CR]cp869\f[R], \f[CR]cp874\f[R], and
\f[CR]cp932\f[R].
.SS \f[CR]skip\f[R]
.IP
.EX
skip N
.EE
.PP
The word \f[CR]skip\f[R] followed by a number (or no number, meaning 1)
tells hledger to ignore this many non\-empty lines at the start of the
input data.
You\(aqll need this whenever your CSV data contains header lines.
Note, empty and blank lines are skipped automatically, so you don\(aqt
need to count those.
.PP
\f[CR]skip\f[R] has a second meaning: it can be used inside an
\f[CR]if\f[R] rule (described below), to skip one or more records
whenever the condition is true.
Records skipped in this way are ignored, except they are still required
to be valid CSV.
.SS \f[CR]date\-format\f[R]
.IP
.EX
date\-format DATEFMT
.EE
.PP
This is a helper for the \f[CR]date\f[R] (and \f[CR]date2\f[R]) fields.
If your CSV dates are not formatted like \f[CR]YYYY\-MM\-DD\f[R],
\f[CR]YYYY/MM/DD\f[R] or \f[CR]YYYY.MM.DD\f[R], you\(aqll need to add a
date\-format rule describing them with a strptime\-style date parsing
pattern \- see
https://hackage.haskell.org/package/time/docs/Data\-Time\-Format.html#v:formatTime.
The pattern must parse the CSV date value completely.
Some examples:
.IP
.EX
# MM/DD/YY
date\-format %m/%d/%y
.EE
.IP
.EX
# D/M/YYYY
# The \- makes leading zeros optional.
date\-format %\-d/%\-m/%Y
.EE
.IP
.EX
# YYYY\-Mmm\-DD
date\-format %Y\-%h\-%d
.EE
.IP
.EX
# M/D/YYYY HH:MM AM some other junk
# Note the time and junk must be fully parsed, though only the date is used.
date\-format %\-m/%\-d/%Y %l:%M %p some other junk
.EE
.PP
Note currently there is no locale awareness for things like
\f[CR]%b\f[R], and setting LC_TIME won\(aqt help.
.SS \f[CR]timezone\f[R]
.IP
.EX
timezone TIMEZONE
.EE
.PP
When CSV contains date\-times that are implicitly in some time zone
other than yours, but containing no explicit time zone information, you
can use this rule to declare the CSV\(aqs native time zone, which helps
prevent off\-by\-one dates.
.PP
When the CSV date\-times do contain time zone information, you don\(aqt
need this rule; instead, use \f[CR]%Z\f[R] in \f[CR]date\-format\f[R]
(or \f[CR]%z\f[R], \f[CR]%EZ\f[R], \f[CR]%Ez\f[R]; see the formatTime
link above).
.PP
In either of these cases, hledger will do a time\-zone\-aware
conversion, localising the CSV date\-times to your current system time
zone.
If you prefer to localise to some other time zone, eg for
reproducibility, you can (on unix at least) set the output timezone with
the TZ environment variable, eg:
.IP
.EX
$ TZ=\-1000 hledger print \-f foo.csv # or TZ=\-1000 hledger import foo.csv
.EE
.PP
\f[CR]timezone\f[R] currently does not understand timezone names, except
\(dqUTC\(dq, \(dqGMT\(dq, \(dqEST\(dq, \(dqEDT\(dq, \(dqCST\(dq,
\(dqCDT\(dq, \(dqMST\(dq, \(dqMDT\(dq, \(dqPST\(dq, or \(dqPDT\(dq.
For others, use numeric format: +HHMM or \-HHMM.
.SS \f[CR]decimal\-mark\f[R]
.IP
.EX
decimal\-mark .
.EE
.PP
or:
.IP
.EX
decimal\-mark ,
.EE
.PP
hledger automatically accepts either period or comma as a decimal mark
when parsing numbers (cf Amounts).
However if any numbers in the CSV contain digit group marks, such as
thousand\-separating commas, you should declare the decimal mark
explicitly with this rule, to avoid misparsed numbers.
Like the \f[CR]decimal\-mark\f[R] directive, this also makes hledger
report numbers using a different decimal mark, or repeating the declared
one (like \f[CR]1.2.34\f[R]), as errors.
This applies to amounts from the CSV fields and to amounts written in
the rules.
.SS \f[CR]newest\-first\f[R]
hledger tries to ensure that the generated transactions will be ordered
chronologically, including same\-day transactions.
Usually it can auto\-detect how the CSV records are ordered.
But if it encounters CSV where all records are on the same date, it
assumes that the records are oldest first.
If in fact the CSV\(aqs records are normally newest first, like:
.IP
.EX
2022\-10\-01, txn 3...
2022\-10\-01, txn 2...
2022\-10\-01, txn 1...
.EE
.PP
you can add the \f[CR]newest\-first\f[R] rule to help hledger generate
the transactions in correct order.
.IP
.EX
# same\-day CSV records are newest first
newest\-first
.EE
.SS \f[CR]intra\-day\-reversed\f[R]
If CSV records within a single day are ordered opposite to the overall
record order, you can add the \f[CR]intra\-day\-reversed\f[R] rule to
improve the order of journal entries.
Eg, here the overall record order is newest first, but same\-day records
are oldest first:
.IP
.EX
2022\-10\-02, txn 3...
2022\-10\-02, txn 4...
2022\-10\-01, txn 1...
2022\-10\-01, txn 2...
.EE
.IP
.EX
# transactions within each day are reversed with respect to the overall date order
intra\-day\-reversed
.EE
.PP
.SS CSV fields and hledger fields
The main task of CSV rules is to convert \f[B]CSV fields\f[R] to
\f[B]hledger fields\f[R].
It\(aqs important to know which is which, when you are creating rules:
.IP "1." 3
CSV fields
.RS 4
.IP \(bu 2
are the parts of the records (lines) in your CSV data
.IP \(bu 2
are referenced by their position or assigned name, with a \f[CR]%\f[R]
prefix (eg \f[CR]%1\f[R] or \f[CR]%date\f[R])
.IP \(bu 2
are read\-only.
.RE
.IP "2." 3
hledger fields
.RS 4
.IP \(bu 2
are the parts of a hledger journal entry (see hledger fields) (eg
\f[CR]date\f[R], \f[CR]description\f[R], \f[CR]account1\f[R],
\f[CR]amount1\f[R])
.IP \(bu 2
are assigned to by rules, to construct a journal entry
.IP \(bu 2
can be referenced by their name, without a \f[CR]%\f[R] prefix, inside a
\f[CR]%{...}\f[R] expression (eg \f[CR]%{description}\f[R]; see
Referencing other fields).
.RE
.PP
CSV rules can\(aqt make new fields; you can\(aqt define your own
variables in a rules file.
(But you could add new CSV fields to the data before running rules, with
a preprocessing script.)
.PP
It\(aqs ok for a CSV field and a hledger field to have the same name; in
a \f[CR]fields\f[R] list, this causes the CSV field\(aqs value to be
assigned to the hledger field (\(dqfield name punning\(dq).
hledger knows which kind of field is meant from the context: in field
values and matchers, \f[CR]%NAME\f[R] is a CSV field, and a bare
\f[CR]HLEDGERFIELDNAME\f[R] inside \f[CR]%{...}\f[R] is a hledger field.
Some examples:
.IP
.EX
# set the journal entry\(aqs date to the value of CSV field 1
date %1
.EE
.IP
.EX
# name the CSV fields, and use the first as the entry\(aqs date
fields date, bankamt
# test the value of the CSV date field
if %date 2026
...
.EE
.IP
.EX
# add a tag to the hledger comment field, keeping any comment assigned before
comment %{join(\(dq, \(dq, comment, \(dqimported:\(dq)}
.EE
.PP
.SS \f[CR]fields\f[R]
.IP
.EX
fields FIELDNAME1, FIELDNAME2, ...
.EE
.PP
A \f[CR]fields\f[R] list (the word \f[CR]fields\f[R] followed by
comma\-separated field names) is optional, but convenient.
It does two things:
.IP "1." 3
It names the CSV field in each column.
This can be convenient if you are referencing them in other rules, so
you can say \f[CR]%SomeField\f[R] instead of remembering \f[CR]%13\f[R].
.IP "2." 3
Whenever you use one of the special hledger field names (described
below), it assigns the CSV value in this position to that hledger field.
This is the quickest way to populate hledger\(aqs fields and build a
transaction.
.PP
Here\(aqs an example that says \(dquse the 1st, 2nd and 4th fields as
the transaction\(aqs date, description and amount; name the last two
fields for later reference; and ignore the others\(dq:
.IP
.EX
fields date, description, , amount, , , somefield, anotherfield
.EE
.PP
In \f[CR]fields\f[R], the names are always separated by commas; this is
unrelated to the CSV file\(aqs separator.
Also:
.IP \(bu 2
There must be least two items in the list (at least one comma).
.IP \(bu 2
Field names may not contain spaces.
Spaces before/after field names are optional.
.IP \(bu 2
Field names may contain \f[CR]_\f[R] (underscore) or \f[CR]\-\f[R]
(hyphen).
.IP \(bu 2
Fields you don\(aqt care about can be given a dummy name or an empty
name.
.PP
If the CSV contains column headings, it\(aqs convenient to use these for
your field names, suitably modified (eg lower\-cased with spaces
replaced by underscores).
.PP
Sometimes you may want to alter a CSV field name to avoid assigning to a
hledger field with the same name.
Eg you could call the CSV\(aqs \(dqbalance\(dq field \f[CR]balance_\f[R]
to avoid directly setting hledger\(aqs \f[CR]balance\f[R] field (and
generating a balance assertion).
.SS Field assignment
.IP
.EX
HLEDGERFIELD FIELDVALUE
.EE
.PP
Field assignments are the more flexible way to assign CSV values to
hledger fields.
They can be used instead of or in addition to a \f[CR]fields\f[R] list
(see above).
.PP
To assign a value to a hledger field, write the field name (any of the
standard hledger field/pseudo\-field names, defined below), a space,
followed by a text value on the same line.
This text value may interpolate CSV fields, referenced either by their
1\-based position in the CSV record (\f[CR]%N\f[R]) or by the name they
were given by \f[CR]fields\f[R] (\f[CR]%CSVFIELD\f[R]), and regular
expression match groups (\f[CR]\(rsN\f[R]), and can transform them with
functions (\f[CR]%{upper(%CSVFIELD)}\f[R]) or use other hledger
fields\(aq values (\f[CR]%{description}\f[R]; see Referencing other
fields).
You can also write \f[CR]%(CSVFIELD)\f[R] to delimit the field name from
adjacent text (eg \f[CR]%(field)suffix\f[R]).
When CSV records have been combined by a \f[CR]merge\f[R] rule, a
\f[CR]_ROWNUM\f[R] suffix (eg \f[CR]%amt_2\f[R], \f[CR]%4_2\f[R])
references the later rows\(aq fields.
Interpolation strips outer whitespace (so a CSV value like
\f[CR]\(dq 1 \(dq\f[R] becomes \f[CR]1\f[R] when interpolated) (#1051).
.PP
Some examples:
.IP
.EX
# set the amount to the 4th CSV field, with \(dq USD\(dq appended
amount %4 USD
# combine three fields to make a comment, containing note: and date: tags
comment note: %somefield \- %anotherfield, date: %1
# use parenthesised form when the field name would run into adjacent text
account1 assets:%(type)checking
.EE
.SS Functions
\f[I]Since 1.99.6; experimental\f[R]
.PP
To transform a value while interpolating it, write a \f[CR]%{...}\f[R]
expression calling one of the built\-in functions below.
Eg:
.IP
.EX
# upper\-case the description
description %{upper(%desc)}
# use the category in lower case, or \(dqmisc\(dq if it\(aqs empty
account2 expenses:%{lower(default(%category, \(dqmisc\(dq))}
# remove a reference number from the description
description %{replace(%desc, \(dq *ref#[0\-9]+\(dq, \(dq\(dq)}
# put the date\(aqs year and month in a tag
comment month:%{substr(%date, 1, 7)}
# show the last four digits of the card number
comment card:%{substr(%card, \-4)}
.EE
.PP
Function arguments can be CSV field references (\f[CR]%summary\f[R] or
\f[CR]%3\f[R]), hledger field names (\f[CR]comment\f[R]), match group
references (\f[CR]\(rs1\f[R]), double\-quoted text
(\f[CR]\(dqmisc\(dq\f[R]), numbers, or other function calls.
Use \f[CR]\(rs\(dq\f[R] for a double quote inside double\-quoted text.
Each expression\(aqs result has outer whitespace removed, like other
interpolated values.
.PP
.TS
tab(@);
lw(18.8n) lw(51.2n).
T{
function
T}@T{
result
T}
_
T{
\f[CR]upper(TEXT)\f[R]
T}@T{
TEXT in upper case
T}
T{
\f[CR]lower(TEXT)\f[R]
T}@T{
TEXT in lower case
T}
T{
\f[CR]capitalize(TEXT)\f[R]
T}@T{
TEXT with each word\(aqs first letter in upper case and the rest in
lower case (\f[CR]capitalise\f[R] also works)
T}
T{
\f[CR]trim(TEXT)\f[R]
T}@T{
TEXT without outer whitespace
T}
T{
\f[CR]negate(AMOUNT)\f[R]
T}@T{
AMOUNT with its sign flipped, eg \f[CR]5\f[R] \-> \f[CR]\-5\f[R],
\f[CR]\-5\f[R] or \f[CR](5)\f[R] \-> \f[CR]5\f[R]
T}
T{
\f[CR]abs(AMOUNT)\f[R]
T}@T{
AMOUNT without a minus sign, eg \f[CR]\-5\f[R] or \f[CR](5)\f[R] \->
\f[CR]5\f[R]
T}
T{
\f[CR]concat(TEXT, ...)\f[R]
T}@T{
all the arguments joined together
T}
T{
\f[CR]join(SEP, TEXT, ...)\f[R]
T}@T{
the TEXTs that aren\(aqt empty, joined with SEP between them
T}
T{
\f[CR]default(TEXT, ...)\f[R]
T}@T{
the first argument that\(aqs not empty
T}
T{
\f[CR]replace(TEXT, REGEX, REPL)\f[R]
T}@T{
TEXT with each match of REGEX replaced by REPL
T}
T{
\f[CR]substr(TEXT, START, LENGTH)\f[R]
T}@T{
LENGTH characters of TEXT, starting at position START (1 is the first,
\-1 the last); LENGTH is optional
T}
.TE
.PP
For \f[CR]replace\f[R], REGEX must be double\-quoted text, and is a
case\-insensitive regular expression.
REPL can use \f[CR]\(rs1\f[R], \f[CR]\(rs2\f[R] etc.
to insert REGEX\(aqs match groups.
(Unquoted \f[CR]\(rs1\f[R] etc.
outside double quotes refer to the match groups of an enclosing
\f[CR]if\f[R] rule instead.)
For \f[CR]substr\f[R], START and LENGTH must be numbers.
A negative START counts from the end, so eg
\f[CR]substr(%card, \-4)\f[R] gives the last four characters.
Positions before the start or after the end of TEXT are treated as the
start or end.
.PP
For \f[CR]negate\f[R] and \f[CR]abs\f[R], AMOUNT is a number, optionally
with a commodity symbol before or after it, and optionally with a sign:
\f[CR]\-\f[R] or \f[CR]+\f[R] before it, or parentheses meaning negative
around it.
The sign can be before or after a commodity symbol written in front of
the number.
Eg these are all negative amounts: \f[CR]\-5\f[R], \f[CR](5)\f[R],
\f[CR]\-$5\f[R], \f[CR]$\-5\f[R], \f[CR]$(5)\f[R], \f[CR]USD \-5\f[R],
\f[CR]\-5 USD\f[R], \f[CR](5 USD)\f[R].
The number itself isn\(aqt parsed, so its decimal mark and digit group
marks don\(aqt matter.
\f[CR]negate\f[R] converts \f[CR]5\f[R] to \f[CR]\-5\f[R] and
\f[CR]$\-1,000.50\f[R] to \f[CR]$1,000.50\f[R], and \f[CR]abs\f[R]
converts any of the above to the unsigned form.
A sign after the number (\f[CR]5\-\f[R]), or parentheses around just the
number when the symbol comes after it (\f[CR](5) USD\f[R]), are not
supported.
.PP
\f[CR]join\f[R] is useful for combining parts which may be empty,
without stray separators.
Eg \f[CR]comment %{join(\(dq, \(dq, %note, %ref)}\f[R].
.PP
Mistakes in an expression, like an unknown function or the wrong number
of arguments, are reported when the rules file is read.
Text beginning with \f[CR]%{\f[R] is always taken as an expression.
.SS Referencing other fields
To use a hledger field\(aqs value, write its name (without \f[CR]%\f[R])
inside a \f[CR]%{...}\f[R] expression.
\f[CR]%NAME\f[R] always means a CSV field, even when a hledger field has
the same name:
.IP
.EX
# name the third CSV field \(dqamount1\(dq
fields date, description, amount1
# set hledger\(aqs amount1 to the CSV amount1 field, followed by USD
amount1 %amount1 USD
# the CSV amount1 field, eg \(dq5\(dq
comment %amount1
# hledger\(aqs amount1 field, eg \(dq5 USD\(dq
comment1 %{amount1}
.EE
.PP
When there are multiple field assignments to the same hledger field,
only the last one takes effect (though it can include the earlier value,
see below).
Here, comment\(aqs value will be B, or C if \(dqsomething\(dq is
matched, but never A:
.IP
.EX
comment A
comment B
if something
comment C
.EE
.PP
In an assignment to the same field, a hledger field\(aqs name gives the
field\(aqs value from its previous assignment, so you can add to it.
This is handy for appending to a comment:
.IP
.EX
fields date, description, comment, amount
if refund
# add a refund tag
comment %{comment}, refund:
# or, avoiding a redundant separator when comment is empty:
#comment %{join(\(dq, \(dq, comment, \(dqrefund:\(dq)}
.EE
.PP
\(dqPrevious assignment\(dq here means the one before this one, in this
order: top\-level assignments (including those made by
\f[CR]fields\f[R]), then assignments in matched \f[CR]if\f[R] rules,
each in the order written.
(So a top\-level assignment comes before any \f[CR]if\f[R] rule\(aqs,
even if written after it.)
.PP
In an assignment to a different field, a hledger field\(aqs name gives
that field\(aqs final value, wherever it is assigned.
Eg here, comment is set to the final value of the hledger description:
.IP
.EX
comment %{description}
.EE
.PP
When interpolating a hledger field, the value is the text assigned to
the field by these rules, before further processing by hledger.
Eg \f[CR]%{amount1}\f[R] is the amount text before any sign
simplification, and \f[CR]%{account2}\f[R] is empty if account2 isn\(aqt
assigned (not \f[CR]expenses:unknown\f[R]).
.PP
.SS hledger fields
Here are all the hledger fields you can assign to.
They correspond to parts of a journal entry, or in some cases they are
pseudo\-fields which have a special effect.
You can also interpolate their values in \f[CR]%{...}\f[R] expressions,
except for the \f[CR]\-in\f[R]/\f[CR]\-out\f[R] amount fields.
.SS date field
Assigning to \f[CR]date\f[R] sets the transaction date.
This is required.
If the CSV dates aren\(aqt like \f[CR]YYYY\-MM\-DD\f[R], see
\f[CR]date\-format\f[R] (and \f[CR]timezone\f[R]).
.SS date2 field
\f[CR]date2\f[R] sets the transaction\(aqs secondary date, if any.
.SS status field
\f[CR]status\f[R] sets the transaction\(aqs status, if any.
.SS code field
\f[CR]code\f[R] sets the transaction\(aqs code, if any.
.PP
Journal format can\(aqt represent a right parenthesis in a code (when
reparsed, it would end the code early).
So any right parentheses here will be replaced with \f[CR]]\f[R], with a
warning.
.SS description field
\f[CR]description\f[R] sets the transaction\(aqs description, if any.
.PP
Journal format can\(aqt represent a semicolon in a description (when
reparsed, it would start a comment, truncating the description).
So any semicolons here will be replaced with \f[CR].,\f[R] (a semicolon
on its side), and a warning is printed.
.SS comment field
\f[CR]comment\f[R] sets the transaction\(aqs comment, if any.
.PP
\f[CR]commentN\f[R], where N is a number, sets the Nth posting\(aqs
comment.
.PP
You can assign multi\-line comments by writing literal \f[CR]\(rsn\f[R]
in the code.
A comment starting with \f[CR]\(rsn\f[R] will begin on a new line.
.PP
Comments can contain tags, as usual.
.PP
Posting comments can also contain a posting date.
A secondary date, or a year\-less date, will be ignored.
.SS account field
Assigning to \f[CR]accountN\f[R], where N is 1 to 99, sets the account
name of the Nth posting, and causes that posting to be generated.
.PP
Most often there are two postings, so you\(aqll want to set
\f[CR]account1\f[R] and \f[CR]account2\f[R].
Typically \f[CR]account1\f[R] is associated with the CSV file, and is
set once with a top\-level assignment, while \f[CR]account2\f[R] is set
based on each transaction\(aqs description, in \f[CR]if\f[R] rules.
.PP
If a posting\(aqs account name is left unset but its amount is set, the
account name will be set to \f[CR]expenses:unknown\f[R] or
\f[CR]income:unknown\f[R] (depending on the amount\(aqs sign).
.SS amount field
There are several ways to set posting amounts from CSV, useful in
different situations.
.IP "1." 3
\f[B]\f[CB]amount\f[B]\f[R] is the oldest and simplest.
Assigning to this sets the amount of the first and second postings.
In the second posting, the amount will be negated; also, if it has a
cost attached, it will be converted to cost.
.IP "2." 3
\f[B]\f[CB]amount\-in\f[B]\f[R] and \f[B]\f[CB]amount\-out\f[B]\f[R]
work exactly like the above, but should be used when the CSV has two
amount fields (such as \(dqDebit\(dq and \(dqCredit\(dq, or
\(dqInflow\(dq and \(dqOutflow\(dq).
Whichever field has a non\-zero value will be used as the amount of the
first and second postings.
Here are some tips to avoid confusion:
.RS 4
.IP \(bu 2
It\(aqs not \(dqamount\-in for posting 1 and amount\-out for posting
2\(dq, it is \(dqextract a single amount from the amount\-in or
amount\-out field, and use that for posting 1 and (negated) for posting
2\(dq.
.IP \(bu 2
Don\(aqt use both \f[CR]amount\f[R] and
\f[CR]amount\-in\f[R]/\f[CR]amount\-out\f[R] in the same rules file;
choose based on whether the amount is in a single CSV field or spread
across two fields.
.IP \(bu 2
In each record, at most one of the two CSV fields should contain a
non\-zero amount; the other field must contain a zero or nothing.
.IP \(bu 2
hledger assumes both CSV fields contain unsigned numbers, and it
automatically negates the amount\-out values.
.IP \(bu 2
If the data doesn\(aqt fit these requirements, you\(aqll probably need
an if rule (see Setting amounts).
.RE
.IP "3." 3
\f[B]\f[CB]amountN\f[B]\f[R] (where N is a number from 1 to 99) sets the
amount of only a single posting: the Nth posting in the transaction.
You\(aqll usually need at least two such assignments to make a balanced
transaction.
You can also generate more than two postings, to represent more complex
transactions.
The posting numbers don\(aqt have to be consecutive; with if rules,
higher posting numbers can be useful to ensure a certain order of
postings.
.IP "4." 3
\f[B]\f[CB]amountN\-in\f[B]\f[R] and \f[B]\f[CB]amountN\-out\f[B]\f[R]
work exactly like the above, but should be used when the CSV has two
amount fields.
This is analogous to \f[CR]amount\-in\f[R] and \f[CR]amount\-out\f[R],
and those tips also apply here.
.IP "5." 3
Remember that \f[CR]fields\f[R] can also do assignments.
So if you name a CSV field \(dqamount\(dq in \f[CR]fields\f[R], that
counts as assigning to \f[CR]amount\f[R].
(If you don\(aqt want that, call it something else there, like
\(dqamount_\(dq.)
.IP "6." 3
The above don\(aqt handle every situation; if you need more flexibility,
use an \f[CR]if\f[R] rule to set amounts conditionally.
See Setting amounts below for more on this and on amount\-setting
generally.
.PP
If the CSV numbers have digit group marks (like \f[CR]1,000.00\f[R]),
see \f[CR]decimal\-mark\f[R].
.PP
An amount value can be an amount expression, eg
\f[CR]amount1 %price + %fee\f[R] (see Amount signs for how this
interacts with sign handling).
.SS Setting amounts
Which amount fields to use depends on how the CSV shows amounts:
.IP "1." 3
\f[B]If the amount is in a single CSV field:\f[R]
.PD 0
.P
.PD
.RS 4
.IP "a." 3
\f[B]If its sign indicates direction of flow:\f[R]
.PD 0
.P
.PD
Assign it to \f[CR]amountN\f[R], to set the Nth posting\(aqs amount.
N is usually 1 or 2 but can go up to 99.
.IP "b." 3
\f[B]If another field indicates direction of flow:\f[R]
.PD 0
.P
.PD
Use one or more \f[CR]if\f[R] rules to set the appropriate amount sign.
Eg:
.IP
.EX
# assume a withdrawal unless Type contains \(dqdeposit\(dq:
amount1 \-%Amount
if %Type deposit
amount1 %Amount
.EE
.RE
.IP "2." 3
\f[B]If the amount is in two CSV fields (such as Debit and Credit, or In
and Out):\f[R]
.PD 0
.P
.PD
.RS 4
.IP "a." 3
\f[B]If both fields are unsigned:\f[R]
.PD 0
.P
.PD
Assign one field to \f[CR]amountN\-in\f[R] and the other to
\f[CR]amountN\-out\f[R].
hledger will automatically negate the \(dqout\(dq field, and will use
whichever field value is non\-zero as posting N\(aqs amount.
.IP "b." 3
\f[B]If either field is signed:\f[R]
.PD 0
.P
.PD
You will probably need to override hledger\(aqs sign for one or the
other field, as in the following example:
.IP
.EX
# Negate the \-out value, but only if it is not empty:
fields date, description, amount1\-in, amount1\-out
if %amount1\-out [1\-9]
amount1\-out \-%amount1\-out
.EE
.PP
c.
\f[B]If both fields can contain a non\-zero value (or both can be
empty):\f[R]
.PD 0
.P
.PD
The \-in/\-out rules normally choose the value which is
non\-zero/non\-empty.
Some value pairs can be ambiguous, such as \f[CR]1\f[R] and
\f[CR]none\f[R].
For such cases, use \f[CR]if\f[R] rules to help select the amount.
Eg, to handle the above you could select the value containing non\-zero
digits:
\f[CR]rules fields date, description, in, out if %in [1\-9] amount1 %in if %out [1\-9] amount1 %out\f[R]
.RE
.IP "3." 3
\f[B]If you want posting 2\(aqs amount converted to cost:\f[R]
.PD 0
.P
.PD
Use the unnumbered \f[CR]amount\f[R] (or \f[CR]amount\-in\f[R] and
\f[CR]amount\-out\f[R]) syntax.
.IP "4." 3
\f[B]If the CSV has only balance amounts, not transaction amounts:\f[R]
.PD 0
.P
.PD
Assign to \f[CR]balanceN\f[R], to set a balance assignment on the Nth
posting, causing the posting\(aqs amount to be calculated automatically.
\f[CR]balance\f[R] with no number is equivalent to \f[CR]balance1\f[R].
In this situation hledger is more likely to guess the wrong default
account name, so you may need to set that explicitly.
.SS Amount signs
There is some special handling making it easier to parse and to reverse
amount signs.
(This only works for whole amounts, not for cost amounts such as COST in
\f[CR]amount1 AMT \(at COST\f[R]):
.IP \(bu 2
\f[B]If an amount value begins with a plus sign:\f[R]
.PD 0
.P
.PD
that will be removed: \f[CR]+AMT\f[R] becomes \f[CR]AMT\f[R]
.IP \(bu 2
\f[B]If an amount value is parenthesised:\f[R]
.PD 0
.P
.PD
it will be de\-parenthesised and sign\-flipped: \f[CR](AMT)\f[R] becomes
\f[CR]\-AMT\f[R]
.IP \(bu 2
\f[B]If an amount value has two minus signs (or two sets of parentheses,
or a minus sign and parentheses):\f[R]
.PD 0
.P
.PD
they cancel out and will be removed: \f[CR]\-\-AMT\f[R] or
\f[CR]\-(AMT)\f[R] becomes \f[CR]AMT\f[R]
.IP \(bu 2
\f[B]If an amount value contains just a sign (or just a set of
parentheses):\f[R]
.PD 0
.P
.PD
that is removed, making it an empty value.
\f[CR]\(dq+\(dq\f[R] or \f[CR]\(dq\-\(dq\f[R] or \f[CR]\(dq()\(dq\f[R]
becomes \f[CR]\(dq\(dq\f[R].
.PP
These rules don\(aqt apply to a value containing an arithmetic operator
(\f[CR]*\f[R], \f[CR]/\f[R], or a \f[CR]+\f[R] or \f[CR]\-\f[R] which is
not a leading sign or an exponent sign as in \f[CR]1e\-5\f[R]), which is
read as an amount expression instead.
In an expression, parentheses group rather than negate:
\f[CR]\-(%price + %fee)\f[R] is minus the sum.
.PP
To set an amount to its absolute value, ie discard its sign, use the
\f[CR]abs\f[R] function, eg \f[CR]amount1 %{abs(%amt)}\f[R].
.SS Amount decimal places
When you are reading CSV data, eg with a command like
\f[CR]hledger \-f foo.csv print\f[R], hledger will infer each
commodity\(aqs decimal precision (and other commodity display styles)
from the amounts \- much as when reading a journal file without
\f[CR]commodity\f[R] directives (see the link).
.PP
Note, the commodity styles are not inferred from the numbers in the
original CSV data; rather, they are inferred from the amounts generated
by the CSV rules.
.PP
When you are importing CSV data with the \f[CR]import\f[R] command, eg
\f[CR]hledger import foo.csv\f[R], there\(aqs another step:
\f[CR]import\f[R] tries to make the new entries conform to the
journal\(aqs existing styles.
So for each commodity \- let\(aqs say it\(aqs EUR \- \f[CR]import\f[R]
will choose:
.IP "1." 3
the style declared for EUR by a \f[CR]commodity\f[R] directive in the
journal
.IP "2." 3
otherwise, the style inferred from EUR amounts in the journal
.IP "3." 3
otherwise, the style inferred from EUR amounts generated by the CSV
rules.
.PP
TLDR: if \f[CR]import\f[R] is not generating the precisions or styles
you want, add a \f[CR]commodity\f[R] directive to specify them.
.SS currency field
\f[CR]currency\f[R] sets a default commodity symbol, to be used for any
posting (or balance) amounts which don\(aqt have one.
You can use this if the CSV amounts do not have a currency symbol, eg if
it is in a separate column.
(You can also set the symbol within an amount assignment, like
\f[CR]amount %amt USD\f[R], but sometimes it\(aqs more convenient to set
it this way.)
The value can be:
.IP \(bu 2
a commodity symbol, like \f[CR]USD\f[R] or \f[CR]$\f[R] or
\f[CR]\(dqSome Fund\(dq\f[R]; this is placed on the left of the number,
with no space (\f[CR]USD5\f[R]).
.IP \(bu 2
or a dummy amount with that symbol, like \f[CR]1 USD\f[R] or
\f[CR]USD 1\f[R] or \f[CR]1USD\f[R], showing the symbol\(aqs position
and spacing to use.
(The amount\(aqs number style, if any, like \f[CR]1.000,00 EUR\f[R], is
also used as a default display style for that commodity.)
.PP
Note the symbol\(aqs placement and display style don\(aqt matter much
when using \f[CR]import\f[R], since that command applies the
journal\(aqs existing commodity styles to the new entries (see Amount
decimal places).
.PP
\f[CR]currencyN\f[R] does the same for just the Nth posting\(aqs amount.
.SS Setting currency/commodity
If the currency/commodity symbol is included in the CSV\(aqs amount
field(s):
.IP
.EX
2023\-01\-01,foo,$123.00
.EE
.PP
you don\(aqt have to do anything special for the commodity symbol, it
will be assigned as part of the amount.
Eg:
.IP
.EX
fields date,description,amount
.EE
.IP
.EX
2023\-01\-01 foo
expenses:unknown $123.00
income:unknown $\-123.00
.EE
.PP
If the currency is provided as a separate CSV field:
.IP
.EX
2023\-01\-01,foo,USD,123.00
.EE
.PP
You can name that field \f[CR]currency\f[R]; this is a special rule,
which sets the commodity of every amount in the transaction which
doesn\(aqt have one (placing the symbol on the left, with no separating
space):
.IP
.EX
fields date,description,currency,amount
.EE
.IP
.EX
2023\-01\-01 foo
expenses:unknown USD123.00
income:unknown USD\-123.00
.EE
.PP
To put the symbol on the right, separated by a space, give the
\f[CR]currency\f[R] rule a dummy amount showing that:
.IP
.EX
fields date,description,cur,amt
currency 1 %cur
amount %amt
.EE
.IP
.EX
2023\-01\-01 foo
expenses:unknown 123.00 USD
income:unknown \-123.00 USD
.EE
.PP
Or, you can use a field assignment to construct the amount yourself:
\f[CR]amount %amt %cur\f[R].
.SS balance field
\f[CR]balanceN\f[R] sets a balance assertion amount (or if the posting
amount is left empty, a balance assignment) on posting N.
.PP
\f[CR]balance\f[R] is a compatibility spelling for hledger <1.17; it is
equivalent to \f[CR]balance1\f[R].
.PP
You can adjust the type of assertion/assignment with the
\f[CR]balance\-type\f[R] rule (see below).
If the CSV has only balances, not transaction amounts, see Setting
amounts.
.SS \f[CR]balance\-type\f[R]
Balance assertions generated by assigning to balanceN are of the simple
\f[CR]=\f[R] type by default, which is a single\-commodity,
subaccount\-excluding assertion.
You may find the subaccount\-including variants more useful, eg if you
have created some virtual subaccounts of checking to help with
budgeting.
You can select a different type of assertion with the
\f[CR]balance\-type\f[R] rule:
.IP
.EX
# balance assertions will consider all commodities and all subaccounts
balance\-type ==*
.EE
.PP
Here are the balance assertion types for quick reference:
.IP
.EX
= single commodity, exclude subaccounts
=* single commodity, include subaccounts
== multi commodity, exclude subaccounts
==* multi commodity, include subaccounts
.EE
.SS \f[CR]if\f[R]
Rules can be applied conditionally, depending on patterns in the CSV
data.
This is how you can categorise transactions, selecting an appropriate
account based on their description (eg).
.PP
An \f[CR]if\f[R] rule is the word \f[CR]if\f[R], followed by one or more
\(dqmatcher\(dq expressions starting on the same line or the next line,
followed by one or more indented rules.
Eg,
.IP
.EX
if MATCHER
RULE
.EE
.PP
or
.IP
.EX
if
MATCHER
MATCHER
MATCHER
RULE
RULE
.EE
.PP
Comment lines can appear anywhere within an \f[CR]if\f[R] rule, and
blank lines can also appear among the indented rules; these do not end
the rule.
(One exception: a matcher on the same line as \f[CR]if\f[R] can begin
with a comment character (eg \f[CR]if #groceries\f[R] matches records
containing \(dq#groceries\(dq); but on the lines below \f[CR]if\f[R],
such a line would be read as a comment.
There, escape the comment character with a backslash, eg
\f[CR]\(rs#groceries\f[R].)
.PP
If any of the matchers succeeds, all of the indented rules will be
applied.
The rules are usually field assignments, but the following special rules
may also be used within an \f[CR]if\f[R] rule:
.IP \(bu 2
\f[CR]skip\f[R] \- skips the matched CSV record (generating no
transaction from it) (described above).
.IP \(bu 2
\f[CR]end\f[R] \- skips the rest of the current CSV file (described
below).
.IP \(bu 2
\f[CR]merge\f[R] \- combines the matched CSV record and the next
record(s) into one record (described below).
.PP
Some examples:
.IP
.EX
# if the record contains \(dqgroceries\(dq, set account2 to \(dqexpenses:groceries\(dq
if groceries
account2 expenses:groceries
.EE
.IP
.EX
# if the record contains any of these phrases, set account2 and a transaction comment as shown
if
monthly service fee
atm transaction fee
banking thru software
account2 expenses:business:banking
comment XXX deductible ? check it
.EE
.SS Matchers
There are two kinds of matcher:
.IP "1." 3
A whole record matcher is simplest: it is just a word, single\-line text
fragment, or other regular expression, which hledger will try to match
case\-insensitively anywhere within the CSV record.
.PD 0
.P
.PD
Eg: \f[CR]whole foods\f[R].
.IP "2." 3
A field matcher has a percent\-prefixed CSV field number or name before
the pattern.
.PD 0
.P
.PD
Eg: \f[CR]%3 whole foods\f[R] or \f[CR]%description whole foods\f[R].
.PD 0
.P
.PD
hledger will try to match the pattern just within the named CSV field.
(In records combined by a \f[CR]merge\f[R] rule, a \f[CR]_ROWNUM\f[R]
suffix selects a later row\(aqs field, eg \f[CR]%description_2\f[R].)
.PP
When using these, there\(aqs two things to be aware of:
.IP "1." 3
Whole record matchers don\(aqt see the exact original record; they see a
reconstruction of it, in which values are comma\-separated, and quotes
enclosing values and whitespace outside those quotes are removed.
.PD 0
.P
.PD
Eg when reading an SSV record like:
\f[CR]2023\-01\-01 ; \(dqAcme, Inc. \(dq ; 1,000\f[R]
.PD 0
.P
.PD
the whole record matcher sees instead:
\f[CR]2023\-01\-01,Acme, Inc. ,1,000\f[R]
.IP "2." 3
Field matchers expect either a CSV field number, or a CSV field name
declared with \f[CR]fields\f[R].
Anything else will cause it to match against the empty string, and
probably fail silently (this makes it easier to reuse common rules with
different CSV files).
Don\(aqt use a hledger field name here (see CSV fields and hledger
fields).
.PP
You can also prefix a matcher line with \f[CR]!\f[R] to negate it (at
the start of the line; you can\(aqt negate individual terms within the
line).
Eg \f[CR]! whole foods\f[R], \f[CR]! %3 whole foods\f[R],
\f[CR]!%description whole foods\f[R] will match if \(dqwhole foods\(dq
is NOT present.
.PP
The pattern is, as usual in hledger, a POSIX extended regular expression
that also supports GNU word boundaries (\f[CR]\(rsb\f[R],
\f[CR]\(rsB\f[R], \f[CR]\(rs<\f[R], \f[CR]\(rs>\f[R]) and nothing else.
For more details and tips, see Regular expressions in CSV rules below.
.SS Multiple matchers
When an \f[CR]if\f[R] rule has multiple matchers, each on its own line,
.IP \(bu 2
By default they are OR\(aqd (any of them can match).
.IP \(bu 2
Matcher lines beginning with \f[CR]&\f[R] (or \f[CR]&&\f[R]) are
AND\(aqed with the matcher above (all in the AND\(aqed group must
match).
.IP \(bu 2
Matcher lines beginning with \f[CR]& !\f[R] (or \f[CR]&& !\f[R]) are
first negated and then AND\(aqed with the matcher above.
.PP
You can also combine multiple matchers on the same line separated by
\f[CR]&&\f[R] (AND) or \f[CR]&& !\f[R] (AND NOT).
Eg \f[CR]%description amazon && %date 2025\-01\-01\f[R] will match only
when the description field contains \(dqamazon\(dq and the date field
contains \(dq2025\-01\-01\(dq.
.SS Match groups
Matchers can define match groups: parenthesised portions of the regular
expression which are available for reference in field assignments.
Groups are enclosed in regular parentheses (\f[CR](\f[R] and
\f[CR])\f[R]) and can be nested.
Each group is available in field assignments using the token
\f[CR]\(rsN\f[R], where N is an index into the match groups for this
\f[CR]if\f[R] rule (e.g.
\f[CR]\(rs1\f[R], \f[CR]\(rs2\f[R], etc.).
.PP
Example: Warp credit card payment postings to the beginning of the
billing period (Month start), to match how they are presented in
statements, using posting dates:
.IP
.EX
if %date (....\-..)\-..
comment2 date:\(rs1\-01
.EE
.PP
Another example: Read the expense account from the CSV field, but throw
away a prefix:
.IP
.EX
if %account1 liabilities:family:(expenses:.*)
account1 \(rs1
.EE
.SS Regular expressions in CSV rules
Regular expressions in \f[CR]if\f[R] conditions (AKA matchers) are POSIX
extended regular expressions, that also support GNU word boundaries
(\f[CR]\(rsb\f[R], \f[CR]\(rsB\f[R], \f[CR]\(rs<\f[R],
\f[CR]\(rs>\f[R]), and nothing else.
(For more detail, see Regular expressions.)
.PP
Here are some examples that might be useful in CSV rules:
.IP \(bu 2
Is field \(dqfoo\(dq truly empty ?
\f[CR]if %foo \(ha$\f[R]
.IP \(bu 2
Is it empty or containing only whitespace ?
\f[CR]if %foo \(ha *$\f[R]
.IP \(bu 2
Is it non\-empty ?
\f[CR]if %foo .\f[R]
.IP \(bu 2
Does it contain non\-whitespace ?
\f[CR]if %foo [\(ha ]\f[R]
.PP
Testing the value of numeric fields is a little harder.
You can\(aqt use hledger queries like \f[CR]amt:0\f[R] or
\f[CR]amt:>10\f[R] in CSV rules.
But you can often achieve the same thing with a regular expression.
.PP
Note the content and layout of number fields in CSV varies, and can
change over time (eg if you switch data providers).
So numeric regexps are always somewhat specific to your particular CSV
data; and it\(aqs a good idea to make them defensive and robust if you
can.
.PP
Here are some examples:
.IP \(bu 2
Does foo contain a non\-zero number ?
\f[CR]if %foo [1\-9]\f[R]
.IP \(bu 2
Is it negative ?
\f[CR]if %foo \-\f[R]
.IP \(bu 2
Is it non\-negative ?
\f[CR]if ! %foo \-\f[R]
.IP \(bu 2
Is it >= 10 ?
\f[CR]if %foo [1\-9][0\-9]+\(rs.\f[R] (assuming a decimal period and no
leading zeros)
.IP \(bu 2
Is it >= 10 and < 20 ?
\f[CR]if %foo \(rsb1[0\-9]\(rs.\f[R]
.PP
.SS \f[CR]ifs\f[R]
An \(dqifs table\(dq is a more compact way to write many if rules.
.IP \(bu 2
The first line begins with \f[CR]ifs\f[R], then one or more hledger
field names, all separated by a delimiter character (any punctuation
character, your choice) plus optional whitespace.
(An older form is also supported for backward compatibility:
\f[CR]if\f[R] followed by the delimiter with no space between them.)
.IP \(bu 2
The following lines begin with a matcher, then values to assign to each
of those hledger fields.
.IP \(bu 2
Comment lines, beginning with \f[CR];\f[R] or \f[CR]#\f[R] (optionally
indented), are also allowed.
.IP \(bu 2
A blank line (or the end of the file) ends the table.
.PP
Eg:
.IP
.EX
ifs | HLEDGERFIELD1 | HLEDGERFIELD2 | ...
MATCHER | VALUE | VALUE | ...
MATCHER | VALUE | VALUE | ...
MATCHER | VALUE | VALUE | ...
<empty line>
.EE
.PP
This means: for each line in turn, if the matcher matches the current
CSV record, assign all of the non\-blank values on that line, without
their surrounding whitespace, to the corresponding hledger fields.
All of the lines are processed, so later lines may override earlier
ones.
Except for the blank/whitespace handling, it\(aqs equivalent to writing
these if rules:
.IP
.EX
if MATCHER
HLEDGERFIELD1 VALUE
HLEDGERFIELD2 VALUE
...
if MATCHER
HLEDGERFIELD1 VALUE
HLEDGERFIELD2 VALUE
...
if MATCHER
HLEDGERFIELD1 VALUE
HLEDGERFIELD2 VALUE
...
.EE
.PP
Because every matching row is applied in order, the last one that
matches wins.
To supply a default, set the field before the table (or put a catch\-all
matcher such as \f[CR].*\f[R] as the first row); later, more\-specific
rows will override it when they match.
.IP
.EX
account2 expenses:unknown
ifs | account2
WHOLE FOODS | expenses:food
WHOLE FOODS.*organic | expenses:food:organic
.EE
.PP
In this example a transaction whose description contains \(dqWHOLE FOODS
organic\(dq matches both WHOLE FOODS rows; the last assignment is the
one that remains.
.PP
The \f[CR]skip\f[R], \f[CR]end\f[R] and \f[CR]merge\f[R] actions can
also be table columns.
Write a number in the cell on lines where the action should happen, and
leave it blank on other lines.
For \f[CR]skip\f[R] and \f[CR]merge\f[R] the number is how many records
to skip or merge (1 or more); for \f[CR]end\f[R], write 1 (any
non\-blank value will end).
Eg:
.IP
.EX
ifs | account2 | skip
atm withdrawal fee | expenses:banking |
transfer to savings | | 1
.EE
.PP
The delimiter must appear the same number of times in each line of the
table, and it must not appear in the field names, matchers, or values
used in the table (though inside \f[CR]%{...}\f[R] expressions is ok).
You cannot escape it with a backslash.
.PP
Note, the delimiter in an ifs table is unrelated to the one used in the
data file (consider avoiding \f[CR],\f[R] or \f[CR];\f[R], because they
look confusing).
.PP
In fact, it\(aqs hard to find a delimiter character that never clashes
with anything, so the flexibility can be useful.
Some examples:
.IP
.EX
# | as delimiter; can use a leading !, can\(aqt use regex | operator
ifs | account2 | comment
! %amount [0\-9][0\-9]+\(rs. | expenses:misc |
%desc amazon | expenses:shopping |
%desc amzn | expenses:shopping |
%amount [0\-9]{4,} | | TODO: large amount, check it
.EE
.IP
.EX
# ! as delimiter; can\(aqt use leading !, can use regex |
ifs ! account2
%desc amazon|amzn ! expenses:shopping
.EE
.IP
.EX
# \(ga as delimiter; can use both leading ! and regex |
ifs \(ga account2
! %amount [0\-9][0\-9]+\(rs. \(ga expenses:misc
%desc amazon|amzn \(ga expenses:shopping
.EE
.SS \f[CR]end\f[R]
The word \f[CR]end\f[R], used inside an \f[CR]if\f[R] or \f[CR]ifs\f[R]
rule, tells hledger to skip the current record and remaining records in
the current CSV file, whenever the condition is true.
Eg:
.IP
.EX
# if an empty record is seen (assuming five fields), ignore the rest of the CSV file
if ,,,,
end
.EE
.SS \f[CR]merge\f[R]
.IP
.EX
if MATCHER
merge N
.EE
.PP
Some banks and brokers export a single transaction as multiple CSV
records \- eg a currency conversion or stock trade, with each side of
the trade on its own row.
The \f[CR]merge\f[R] rule combines such related records, so that they
can generate a single journal transaction.
.PP
When a record matches an \f[CR]if\f[R] rule containing
\f[CR]merge N\f[R] (the word \f[CR]merge\f[R] followed by a number, or
no number, meaning 1), the next N records are joined onto the matched
record, forming a group of rows.
Conversion then proceeds as usual, with the whole group generating one
transaction.
.PP
Fields of the later rows are referenced by adding a \f[CR]_ROWNUM\f[R]
suffix (row number 2 or greater) to the usual field name or number:
\f[CR]%amt_2\f[R] or \f[CR]%4_2\f[R] is row 2\(aqs \f[CR]amt\f[R]/fourth
field.
Unsuffixed references (\f[CR]%amt\f[R], \f[CR]%4\f[R]) always mean the
first row, so the same \f[CR]fields\f[R] list describes every row.
A reference to a row that isn\(aqt there (eg in an unmerged record) just
has an empty value.
And if you have declared a field name that looks like
\f[CR]NAME_ROWNUM\f[R], it keeps its declared meaning; the suffix
interpretation is only a fallback.
.PP
For example, to convert this two\-row currency conversion:
.IP
.EX
2026\-09\-01,PAYMENT,coffee,\-3.50,USD
2026\-09\-02,CONVERT,converted USD to EUR,\-100.00,USD
2026\-09\-02,CONVERT,converted USD to EUR,90.00,EUR
.EE
.IP
.EX
fields date, type, desc, amt, cur
description %desc
account1 assets:bank:%cur
amount1 %amt %cur
# a conversion\(aqs second row holds the amount received; make it posting 2
if %type CONVERT
merge
account2 assets:bank:%cur_2
amount2 %amt_2 %cur_2
if %type PAYMENT
account2 expenses:unknown
.EE
.IP
.EX
$ hledger print \-f conversion.csv
2026\-09\-01 coffee
assets:bank:USD \-3.50 USD
expenses:unknown
2026\-09\-02 converted USD to EUR
assets:bank:USD \-100.00 USD
assets:bank:EUR 90.00 EUR
.EE
.PP
Things to note:
.IP \(bu 2
\f[CR]merge\f[R] can also be used as a top\-level rule
(unconditionally), useful for files where every transaction is exactly
N+1 rows.
.IP \(bu 2
\f[CR]skip\f[R] and \f[CR]end\f[R] rules are applied before row merging
\- skipped records don\(aqt count toward a merge group.
.IP \(bu 2
The rows of a group must be consecutive in the file (ignoring skipped
records), and the merging record must be the first of them.
.IP \(bu 2
Matchers which (if successful) will trigger a \f[CR]merge\f[R] rule, can
only usefully reference the first row\(aqs fields \- the other row
fields will be empty at this stage.
.IP \(bu 2
But once a \f[CR]merge\f[R] rule has been evaluated, later \f[CR]if\f[R]
rules can see the whole group; eg a whole\-record matcher will see all
of its rows combined as one, and field matchers can use
\f[CR]%FIELD_ROWNUM\f[R] references.
.IP \(bu 2
If fewer than N records remain in the file, just those are merged.
.SS \f[CR]include\f[R]
.IP
.EX
include RULESFILE
.EE
.PP
This includes the contents of another CSV rules file at this point.
\f[CR]RULESFILE\f[R] is an absolute file path or a path relative to the
current file\(aqs directory.
This can be useful for sharing common rules between several rules files,
eg:
.IP
.EX
# someaccount.csv.rules
## someaccount\-specific rules
fields date,description,amount
account1 assets:someaccount
account2 expenses:misc
## common rules
include categorisation.rules
.EE
.PP
Since included rules are effectively inlined, and since for most rules
the last declaration wins, you can override an included file\(aqs rules
by writing rules after the \f[CR]include\f[R] line.
.SS Working with CSV
Some tips for creating rules and importing CSV data regularly:
.SS CSV rules examples
For real\-world rules files for many banks, brokers, exchanges and apps,
see the hledger CSV rules library in the hledger repo.
These aren\(aqt necessarily maintained, and may need adapting, but they
are a good source of ideas and examples.
.SS Rapid feedback
It\(aqs a good idea to get rapid feedback while creating/troubleshooting
CSV rules.
Here\(aqs a good way, using entr from eradman.com/entrproject:
.IP
.EX
$ ls foo.csv* | entr bash \-c \(aqecho \-\-\-\-; hledger \-f foo.csv print desc:SOMEDESC\(aq
.EE
.PP
A desc: query (eg) is used to select just one, or a few, transactions of
interest.
\(dqbash \-c\(dq is used to run multiple commands, so we can echo a
separator each time the command re\-runs, making it easier to read the
output.
.SS Well factored rules
Some things that can help reduce duplication and complexity in rules
files:
.IP \(bu 2
Extracting common rules usable with multiple CSV files into a
\f[CR]common.rules\f[R], and adding \f[CR]include common.rules\f[R] to
each CSV\(aqs rules file.
.IP \(bu 2
Splitting \f[CR]if\f[R] rules into smaller \f[CR]if\f[R] rules,
extracting the frequently used parts.
.SS Deduplicating, importing
When you download a CSV file periodically, eg to get your latest bank
transactions, the new file may overlap with the old one, containing some
of the same records.
.PP
The import command will (a) detect the new transactions, and (b) append
just those transactions to your main journal.
It is idempotent, so you don\(aqt have to remember how many times you
ran it or with which version of the CSV.
(It keeps state in a hidden \f[CR].latest.FILE.csv\f[R] file.)
This is the easiest way to import CSV data.
Eg:
.IP
.EX
# download the latest CSV files, then run this command.
# Note, no \-f flags needed here.
$ hledger import *.csv [\-\-dry]
.EE
.PP
This method works for most CSV files.
(Where records have a stable chronological order, and new records appear
only at the new end.)
.PP
A number of other tools and workflows, hledger\-specific and otherwise,
exist for converting, deduplicating, classifying and managing CSV data.
See:
.IP \(bu 2
https://hledger.org/workflows.html#comparing\-csv\-workflows
.IP \(bu 2
https://hledger.org/doc.html#setups\-and\-workflows
.IP \(bu 2
https://plaintextaccounting.org \-> data import/conversion
.SS Valid transactions
After reading a CSV file, hledger post\-processes and validates the
generated journal entries as it would for a journal file \- balancing
them, applying balance assignments, and canonicalising amount styles.
Any errors at this stage will be reported in the usual way, displaying
the problem entry.
.PP
There is one exception: balance assertions, if you have generated them,
will not be checked, since normally these will work only when the CSV
data is part of the main journal.
If you do need to check balance assertions generated from CSV right
away, pipe into another hledger:
.IP
.EX
$ hledger \-f file.csv print | hledger \-f\- print
.EE
.SS How CSV rules are evaluated
Here\(aqs how to think of CSV rules being evaluated.
If you get a confusing error while reading a CSV file, it may help to
try to understand which of these steps is failing:
.IP "1." 3
Any included rules files are inlined, from top to bottom, depth first
(scanning each included file for further includes, recursively, before
proceeding).
.IP "2." 3
Top level rules (\f[CR]date\-format\f[R], \f[CR]fields\f[R],
\f[CR]newest\-first\f[R], \f[CR]skip\f[R] etc) are read, top to bottom.
\(dqTop level rules\(dq means non\-conditional rules.
If a rule occurs more than once, the last one wins; except for the
\f[CR]skip\f[R] rule, where the first one wins, and the
\f[CR]source\f[R] rule, which may occur only once.
A rule written after an \f[CR]include\f[R] would override the same rule
in the included file.
.IP "3." 3
The CSV file is read as text.
Any non\-ascii characters will be decoded using the text encoding
specified by the \f[CR]encoding\f[R] rule, otherwise the system
locale\(aqs text encoding.
.IP "4." 3
Any top\-level skip or end rule is applied.
\f[CR]skip [N]\f[R] immediately skips the current or next N CSV records;
\f[CR]end\f[R] immediately skips all remaining CSV records (not normally
used at top level).
.IP "5." 3
Now any remaining CSV records are processed.
For each CSV record, in file order:
.RS 4
.IP \(bu 2
Is there a conditional skip/end rule that applies for this record ?
Search the \f[CR]if\f[R] rules, from top to bottom, for a succeeding one
containing a \f[CR]skip\f[R] or \f[CR]end\f[R] rule.
If found, skip the specified number of CSV records, then continue at 5.
.PD 0
.P
.PD
Otherwise...
.IP \(bu 2
Is there a \f[CR]merge\f[R] rule that applies for this record (top level
or conditional) ?
If so, join the next N CSV records onto this record, making one combined
record.
.IP \(bu 2
Do some basic validation on this CSV record (eg, check that it has at
least two fields).
.IP \(bu 2
For each hledger field (\f[CR]date\f[R], \f[CR]description\f[R],
\f[CR]account1\f[R], etc.):
.RS 2
.IP "1." 3
Get the field\(aqs assigned value, first searching top level
assignments, made directly or by the \f[CR]fields\f[R] rule, then
assignments made inside succeeding \f[CR]if\f[R] rules.
If there are more than one, the last one wins (though it can include the
previous one\(aqs value with \f[CR]%{FIELDNAME}\f[R]).
.IP "2." 3
Compute the field\(aqs actual value (as text), by interpolating any
%CSVFIELD references and %{...} expressions within the assigned value
(which may use other hledger fields\(aq values, computing them first);
or by choosing a default value if there was no assignment.
.RE
.IP \(bu 2
Generate a hledger transaction from the hledger field values, parsing
them if needed (eg from text to an amount).
.RE
.PP
This is all done by the CSV reader, one of several readers hledger can
use to read transactions from an input file.
When all input files have been read successfully, their transactions are
passed to whichever hledger command the user specified.
.PP
.SH Timeclock
hledger can read time logs in the timeclock time logging format of
timeclock.el.
As with Ledger, hledger\(aqs timeclock format is a subset/variant of
timeclock.el\(aqs.
.PP
hledger\(aqs timeclock format was updated in hledger 1.43 and 1.50.
If your old time logs are rejected, you should adapt them to modern
hledger; for now, you can restore the pre\-1.43 behaviour with the
\f[CR]\-\-old\-timeclock\f[R] flag.
.PP
Here is the timeclock format (in hledger 1.50+):
.IP
.EX
# Comment lines like these, and blank lines, are ignored:
# comment line
; comment line
* comment line
# Lines beginning with b, h, or capital O are also ignored, for compatibility:
b SIMPLEDATE HH:MM[:SS][+\-ZZZZ][ TEXT]
h SIMPLEDATE HH:MM[:SS][+\-ZZZZ][ TEXT]
O SIMPLEDATE HH:MM[:SS][+\-ZZZZ][ TEXT]
# Lines beginning with i or o are are clock\-in / clock\-out entries:
i SIMPLEDATE HH:MM[:SS][+\-ZZZZ] ACCOUNT[ DESCRIPTION][;COMMENT]]
o SIMPLEDATE HH:MM[:SS][+\-ZZZZ][ ACCOUNT][;COMMENT]
.EE
.PP
The date is a hledger simple date (YYYY\-MM\-DD or similar).
The time parts must use two digits.
The seconds are optional.
A + or \- four\-digit time zone is accepted for compatibility, but
currently ignored; times are always interpreted as a local time.
.PP
In clock\-in entries (\f[CR]i\f[R]), the account name is required.
A transaction description, separated from the account name by 2+ spaces,
is optional.
A transaction comment, beginning with \f[CR];\f[R], is also optional.
(Indented following comment lines are also allowed, as in journal
format.)
.PP
Clock\-out entries (\f[CR]o\f[R]) have no description, but can have a
comment if you wish.
A clock\-in and clock\-out pair form a \(dqtransaction\(dq posting some
number of hours to an account \- also known as a session.
Eg:
.IP
.EX
i 2015/03/30 09:00:00 session1
o 2015/03/30 10:00:00
.EE
.IP
.EX
$ hledger \-f a.timeclock print
2015\-03\-30 * 09:00\-10:00
(session1) 1.00h
.EE
.PP
Clock\-ins and clock\-outs are matched by their account/session name.
If a clock\-out does not specify a name, the most recent unclosed
clock\-in is closed.
You can have multiple sessions active simultaneously.
Entries are processed in the order they are parsed.
Sessions spanning more than one day are automatically split at day
boundaries.
.PP
Eg, the following time log:
.IP
.EX
i 2015/03/30 09:00:00 some account optional description after 2 spaces ; optional comment, tags:
o 2015/03/30 09:20:00
i 2015/03/31 22:21:45 another:account
o 2015/04/01 02:00:34
i 2015/04/02 12:00:00 another:account ; this demonstrates multiple sessions being clocked in
i 2015/04/02 13:00:00 some account
o 2015/04/02 14:00:00
o 2015/04/02 15:00:00 another:account
.EE
.PP
generates these transactions:
.IP
.EX
$ hledger \-f t.timeclock print
2015\-03\-30 * optional description after 2 spaces ; optional comment, tags:
(some account) 0.33333333h
2015\-03\-31 * 22:21\-23:59
(another:account) 1.6375h
2015\-04\-01 * 00:00\-02:00
(another:account) 2.00944444h
2015\-04\-02 * 12:00\-15:00 ; this demonstrates multiple sessions being clocked in
(another:account) 3.00h
2015\-04\-02 * 13:00\-14:00
(some account) 1.00h
.EE
.PP
Here is a sample.timeclock to download and some queries to try:
.IP
.EX
$ hledger \-f sample.timeclock balance # current time balances
$ hledger \-f sample.timeclock register \-p 2009/3 # sessions in march 2009
$ hledger \-f sample.timeclock register \-p weekly \-\-depth 1 \-\-empty # time summary by week
.EE
.PP
To generate time logs, ie to clock in and clock out, you could:
.IP \(bu 2
use these shell aliases at the command line:
.RS 2
.IP
.EX
alias ti=\(aqecho i \(gadate \(dq+%Y\-%m\-%d %H:%M:%S\(dq\(ga $* >>$TIMELOG\(aq
alias to=\(aqecho o \(gadate \(dq+%Y\-%m\-%d %H:%M:%S\(dq\(ga >>$TIMELOG\(aq
.EE
.RE
.IP \(bu 2
or Emacs\(aqs built\-in timeclock.el, or the extended timeclock\-x.el,
and perhaps the extras in ledgerutils.el
.IP \(bu 2
or use the old \f[CR]ti\f[R] and \f[CR]to\f[R] scripts in the ledger 2.x
repository.
These rely on a \(dqtimeclock\(dq executable which I think is just the
ledger 2 executable renamed.
.PP
.SH Timedot
\f[CR]timedot\f[R] format is hledger\(aqs human\-friendly time logging
format.
Compared to \f[CR]timeclock\f[R] format, it is more convenient for
quick, approximate, and retroactive time logging, and more
human\-readable (you can see at a glance where time was spent).
A quick example:
.IP
.EX
2023\-05\-01
hom:errands .... .... ; two hours; the space is ignored
fos:hledger:timedot .. ; half an hour
per:admin:finance ; no time spent yet
.EE
.PP
hledger reads this as a transaction on this day with three (unbalanced)
postings, where each dot represents 0.25 (of an hour, we usually
assume).
.IP
.EX
$ hledger \-f a.timedot print # .timedot file extension (or timedot: prefix) is required
2023\-05\-01 *
(hom:errands) 2.00 ; two hours; the space is ignored
(fos:hledger:timedot) 0.50 ; half an hour
(per:admin:finance) 0.00 ; no time spent yet
.EE
.PP
A timedot file specifies a series of transactions, usually one per day.
(Unlike in a journal file, these \(dqtransactions\(dq don\(aqt need to
balance; time logs use \(dqsingle entry accounting\(dq.)
.PP
Each transaction begins with a \f[B]date line\f[R]: a line whose first
word looks like a simple date, ie three groups of digits separated by
\f[CR]\-\f[R], \f[CR]/\f[R], or \f[CR].\f[R] (if these cannot be parsed
as a valid date, an error is raised).
After the date, on the same line, there can optionally be a transaction
description, and after \f[CR];\f[R], a transaction comment (possibly
containing tags).
.PP
After the date line are zero or more \f[B]posting lines\f[R].
A timedot posting line begins with a hledger\-style account name,
optionally indented.
After the account name there are \f[B]two or more spaces\f[R] and then a
\f[B]timedot amount\f[R].
(Or nothing, which is equivalent to a zero amount.)
.PP
Timedot amounts can be written in several ways:
.IP \(bu 2
One or more \f[B]dots\f[R] (\f[CR].\f[R])
.PD 0
.P
.PD
Each dot represents a quarter hour.
(There\(aqs no commodity symbol, but usually we assume hours.)
Spaces can optionally be used for aligning or grouping dots, eg
\f[CR].... .... ..\f[R] is easy to read as 2.5 hours.
.IP \(bu 2
A \f[B]bare number\f[R] (integer or decimal)
.PD 0
.P
.PD
This can be more precise or more convenient, eg for large durations.
.IP \(bu 2
A \f[B]number followed by a time unit\f[R] (\f[CR]s\f[R], \f[CR]m\f[R],
\f[CR]h\f[R], \f[CR]d\f[R], \f[CR]w\f[R], \f[CR]mo\f[R], or
\f[CR]y\f[R])
.PD 0
.P
.PD
representing seconds, minutes, hours, days, weeks, months or years,
which will be converted to hours using these ratios: 60s = 1m, 60m = 1h,
24h = 1d, 7d = 1w, 30d = 1mo, 365d = 1y.
This allows use of more convenient time units.
.IP \(bu 2
One or more \f[B]timedot letters\f[R]
.PD 0
.P
.PD
These work like dots, except they also generate a posting tag
\f[CR]t:\f[R] (short for \(dqtype\(dq) with the letter as its value, and
a separate posting for each of the letter values.
This adds a second dimension of categorisation \- in addition to account
name, you\(aqll have the \f[CR]t\f[R] tag\(aqs value, which can be shown
in reports with \f[CR]\-\-pivot t\f[R], \f[CR]\-\-pivot acct:t\f[R],
etc.
.PP
Posting lines can end with a hledger\-style posting comment (text after
\f[CR];\f[R]), optionally containing tags.
.PP
Lines beginning with \f[CR]#\f[R] or \f[CR];\f[R] are \f[B]comment
lines\f[R], and ignored.
Blank lines are also ignored.
.PP
There is some additional support for users of Emacs org mode:
.IP \(bu 2
Before the first date line, lines beginning with \f[CR]*\f[R] are also
treated as comments, and ignored.
This allows top\-level org headings in a timedot file.
.IP \(bu 2
From the first date line onward, org heading prefixes (one or more
\f[CR]*\f[R]\(aqs followed by a space) are ignored, with the rest of the
line being parsed normally.
This allows timedot date or posting lines to also be org headings.
.PP
Timedot files don\(aqt support directives like journal files.
So a common pattern is to have a main journal file that contains any
needed directives, and then includes the timedot file
(\f[CR]include time.timedot\f[R]).
.SS Timedot examples
Numbers:
.IP
.EX
2016/2/3
inc:client1 4
fos:hledger 3h
biz:research 60m
.EE
.PP
Dots:
.IP
.EX
# on this day, 6h was spent on client work, 1.5h on haskell FOSS work, etc.
2016/2/1
inc:client1 .... .... .... .... .... ....
fos:haskell .... ..
biz:research .
2016/2/2
inc:client1 .... ....
biz:research .
.EE
.IP
.EX
$ hledger \-f a.timedot print date:2016/2/2
2016\-02\-02 *
(inc:client1) 2.00
(biz:research) 0.25
.EE
.IP
.EX
$ hledger \-f a.timedot bal \-\-daily
Balance changes in 2016\-02\-01..2016\-02\-02:
|| 2016\-02\-01 2016\-02\-02
==============++========================
biz:research || 0.25 0.25
fos:haskell || 1.50 0
inc:client1 || 6.00 2.00
\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 7.75 2.25
.EE
.PP
Letters:
.IP
.EX
# Activity types:
# c cleanup/catchup/repair
# e enhancement
# s support
# l learning/research
2023\-11\-01
work:adm ccecces
.EE
.IP
.EX
$ hledger \-f a.timedot print
2023\-11\-01 *
(work:adm) 1.00 ; t:c
(work:adm) 0.50 ; t:e
(work:adm) 0.25 ; t:s
.EE
.IP
.EX
$ hledger \-f a.timedot bal
1.75 work:adm
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
1.75
.EE
.IP
.EX
$ hledger \-f a.timedot bal \-\-pivot t
1.00 c
0.50 e
0.25 s
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
1.75
.EE
.PP
Org:
.IP
.EX
* 2023 Work Diary
** Q1
*** 2023\-02\-28
**** DONE
yoga ....
**** BEGUN
hom:chores
cleaning ...
water plants
outdoor \- one full watering can
indoor \- light watering
**** TODO
adm:planning:trip
*** LATER
.EE
.PP
Using \f[CR].\f[R] as account name separator:
.IP
.EX
2016/2/4
fos.hledger.timedot 4h
fos.ledger ..
.EE
.IP
.EX
$ hledger \-f a.timedot \-\-alias \(aq/\(rs./=:\(aq bal \-t
4.50 fos
4.00 hledger:timedot
0.50 ledger
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
4.50
.EE
.SH PART 4: CONCEPTS
.SH Time periods
.SS Report start & end date
Most hledger reports will by default show the full time period
represented by the journal.
The report start date will be the earliest transaction or posting date,
and the report end date will be the latest transaction, posting, or
market price date.
.PP
Often you will want to see a shorter period, such as the current month.
You can specify a start and/or end date with the
\f[CR]\-b/\-\-begin\f[R], \f[CR]\-e/\-\-end\f[R], or
\f[CR]\-p/\-\-period\f[R] options, or a \f[CR]date:\f[R] query argument,
described below.
All of these accept the smart date syntax, also described below.
.PP
End dates are exclusive; specify the day after the last day you want to
see in the report.
.PP
When dates are specified by multiple options, the last (right\-most)
option wins.
And when \f[CR]date:\f[R] queries and date options are combined, the
report period will be their intersection.
.PP
Examples:
.TP
\f[CR]\-b 2016/3/17\f[R]
beginning on St.
Patrick\(cqs day 2016
.TP
\f[CR]\-e 12/1\f[R]
ending at the start of December 1st in the current year
.TP
\f[CR]\-p \(aqthis month\(aq\f[R]
during the current month
.TP
\f[CR]\-p thismonth\f[R]
same as above, spaces are optional
.TP
\f[CR]\-b 2023\f[R]
beginning on the first day of 2023
.TP
\f[CR]date:2023..\f[R] or \f[CR]date:2023\-\f[R]
same as above
.PP
\f[CR]\-b 2024 \-e 2025 \-p \(aq2000 to 2030\(aq date:2020\-01 date:2020\f[R]
:
.PD 0
.P
.PD
during January 2020 (the smallest common period, with the \-p overriding
\-b and \-e)
.SS Smart dates
In hledger\(aqs user interfaces (though not in the journal file), you
can optionally use \(dqsmart date\(dq syntax.
Smart dates can be written with english words, can be relative, and can
have parts omitted.
Missing parts are inferred as 1, when needed.
Smart dates can be interpreted as dates or periods depending on the
context.
.PP
Examples:
.PP
\f[CR]2004\-01\-01\f[R], \f[CR]2004/10/1\f[R], \f[CR]2004.9.1\f[R],
\f[CR]20240504\f[R], \f[CR]2024Q1\f[R] :
.PD 0
.P
.PD
Exact dates.
The year must have at least four digits, the month must be 1\-12, the
day must be 1\-31, the separator can be \f[CR]\-\f[R] or \f[CR]/\f[R] or
\f[CR].\f[R] or nothing.
The q can be upper or lower case and the quarter number must be 1\-4.
.TP
\f[CR]2004\-10\f[R]
start of month
.TP
\f[CR]2004q3\f[R]
start of third quarter of 2004
.TP
\f[CR]q3\f[R]
start of third quarter of current year
.TP
\f[CR]2004\f[R]
start of year
.TP
\f[CR]10/1\f[R] or \f[CR]oct\f[R] or \f[CR]october\f[R]
October 1st in current year
.TP
\f[CR]21\f[R]
21st day in current month
.TP
\f[CR]yesterday, today, tomorrow\f[R]
\-1, 0, 1 days from today
.TP
\f[CR]last/this/next day/week/month/quarter/year\f[R]
\-1, 0, 1 periods from the current period
.TP
\f[CR]last/this/next tuesday\f[R]
the previous occurrence of the named day, or the next occurrence after
today
.TP
\f[CR]last/this/next february\f[R]
the previous occurrence of 1st of the named month, or the next
occurrence after the current month
.TP
\f[CR]in n days/weeks/months/quarters/years\f[R]
n periods from the current period
.TP
\f[CR]n days/weeks/months/quarters/years ahead\f[R]
n periods from the current period
.TP
\f[CR]n days/weeks/months/quarters/years ago\f[R]
\-n periods from the current period
.TP
\f[CR]20181201\f[R]
8 digit YYYYMMDD with valid year month and day
.TP
\f[CR]201812\f[R]
6 digit YYYYMM with valid year and month
.PP
Dates with no separators are allowed but might give surprising results
if mistyped:
.IP \(bu 2
\f[CR]20181301\f[R] (YYYYMMDD with an invalid month) is parsed as an
eight\-digit year
.IP \(bu 2
\f[CR]20181232\f[R] (YYYYMMDD with an invalid day) gives a parse error
.IP \(bu 2
\f[CR]201801012\f[R] (a valid YYYYMMDD followed by additional digits)
gives a parse error
.PP
The meaning of relative dates depends on today\(aqs date.
If you need to test or reproduce old reports, you can use the
\f[CR]\-\-today\f[R] option to override that.
(Except for periodic transaction rules, which are not affected by
\f[CR]\-\-today\f[R].)
.SS Report intervals
A report interval can be specified so that reports like register,
balance or activity become multi\-period, showing each subperiod as a
separate row or column.
.PP
The following standard intervals can be enabled with command\-line
flags:
.IP \(bu 2
\f[CR]\-D/\-\-daily\f[R]
.IP \(bu 2
\f[CR]\-W/\-\-weekly\f[R]
.IP \(bu 2
\f[CR]\-M/\-\-monthly\f[R]
.IP \(bu 2
\f[CR]\-Q/\-\-quarterly\f[R]
.IP \(bu 2
\f[CR]\-Y/\-\-yearly\f[R]
.PP
More complex intervals can be specified using \f[CR]\-p/\-\-period\f[R],
described below.
.SS Date adjustments
.SS Start date adjustment
If you let hledger infer a report\(aqs start date, it will adjust the
date to the previous natural boundary of the report interval, for
convenient periodic reports.
(If you don\(aqt want that, specify a start date.)
.PP
For example, if the journal\(aqs first transaction is on january 10th,
.IP \(bu 2
\f[CR]hledger register\f[R] (no report interval) will start the report
on january 10th.
.IP \(bu 2
\f[CR]hledger register \-\-monthly\f[R] will start the report on the
previous month boundary, january 1st.
.IP \(bu 2
\f[CR]hledger register \-\-monthly \-\-begin 1/5\f[R] will start the
report on january 5th [1].
.PP
The start date of transactions generated by periodic transaction rules
is chosen separately; see Forecast period, in detail.
.SS End date adjustment
A report\(aqs end date is always adjusted to include a whole number of
intervals, so that the last subperiod has the same length as the others.
.PP
For example, if the journal\(aqs last transaction is on february 20th,
.IP \(bu 2
\f[CR]hledger register\f[R] will end the report on february 20th.
.IP \(bu 2
\f[CR]hledger register \-\-monthly\f[R] will end the report at the end
of february.
.IP \(bu 2
\f[CR]hledger register \-\-monthly \-\-end 2/14\f[R] also will end the
report at the end of february (overriding the requested end date).
.IP \(bu 2
\f[CR]hledger register \-\-monthly \-\-begin 1/5 \-\-end 2/14\f[R] will
end the report on march 4th.
.SS Period expressions
The \f[CR]\-p/\-\-period\f[R] option specifies a period expression,
which is a compact way of expressing a start date, end date, and/or
report interval.
.PP
Here\(aqs a period expression with a start and end date (specifying the
first quarter of 2009):
.PP
.TS
tab(@);
l.
T{
\f[CR]\-p \(dqfrom 2009/1/1 to 2009/4/1\(dq\f[R]
T}
.TE
.PP
Several keywords like \(dqfrom\(dq and \(dqto\(dq are supported for
readability; these are optional.
\(dqto\(dq can also be written as \(dq..\(dq or \(dq\-\(dq.
(Except that a lone day number, directly after a \(dq\-\(dq with no
spaces, is not accepted; eg \f[CR]2026\-13\f[R] is more likely a
mistyped date than \(dq2026 to the 13th of this month\(dq, so it\(aqs an
error.
To mean the latter, write \f[CR]2026..13\f[R].)
The spaces are also optional, as long as you don\(aqt run two dates
together.
So the following are equivalent to the above:
.PP
.TS
tab(@);
l.
T{
\f[CR]\-p \(dq2009/1/1 2009/4/1\(dq\f[R]
T}
T{
\f[CR]\-p2009/1/1to2009/4/1\f[R]
T}
T{
\f[CR]\-p2009/1/1..2009/4/1\f[R]
T}
.TE
.PP
Dates are smart dates, so if the current year is 2009, these are also
equivalent to the above:
.PP
.TS
tab(@);
l.
T{
\f[CR]\-p \(dq1/1 4/1\(dq\f[R]
T}
T{
\f[CR]\-p \(dqjan\-apr\(dq\f[R]
T}
T{
\f[CR]\-p \(dqthis year to 4/1\(dq\f[R]
T}
.TE
.PP
If you specify only one date, the missing start or end date will be the
earliest or latest transaction date in the journal:
.PP
.TS
tab(@);
l l.
T{
\f[CR]\-p \(dqfrom 2009/1/1\(dq\f[R]
T}@T{
everything after january 1, 2009
T}
T{
\f[CR]\-p \(dqsince 2009/1\(dq\f[R]
T}@T{
the same, since is a synonym
T}
T{
\f[CR]\-p \(dqfrom 2009\(dq\f[R]
T}@T{
the same
T}
T{
\f[CR]\-p \(dqto 2009\(dq\f[R]
T}@T{
everything before january 1, 2009
T}
.TE
.PP
You can also specify a period by writing a single partial or full date:
.PP
.TS
tab(@);
lw(14.5n) lw(55.5n).
T{
\f[CR]\-p \(dq2009\(dq\f[R]
T}@T{
the year 2009; equivalent to \(lq2009/1/1 to 2010/1/1\(rq
T}
T{
\f[CR]\-p \(dq2009/1\(dq\f[R]
T}@T{
the month of january 2009; equivalent to \(lq2009/1/1 to 2009/2/1\(rq
T}
T{
\f[CR]\-p \(dq2009/1/1\(dq\f[R]
T}@T{
the first day of 2009; equivalent to \(lq2009/1/1 to 2009/1/2\(rq
T}
.TE
.PP
or by using the \(dqQ\(dq quarter\-year syntax (case insensitive):
.PP
.TS
tab(@);
lw(15.3n) lw(54.7n).
T{
\f[CR]\-p \(dq2009Q1\(dq\f[R]
T}@T{
first quarter of 2009, equivalent to \(lq2009/1/1 to 2009/4/1\(rq
T}
T{
\f[CR]\-p \(dqq4\(dq\f[R]
T}@T{
fourth quarter of the current year
T}
.TE
.SS Period expressions with a report interval
A period expression can also begin with a report interval, separated
from the start/end dates (if any) by a space or the word \f[CR]in\f[R]:
.PP
.TS
tab(@);
l.
T{
\f[CR]\-p \(dqweekly from 2009/1/1 to 2009/4/1\(dq\f[R]
T}
T{
\f[CR]\-p \(dqmonthly in 2008\(dq\f[R]
T}
T{
\f[CR]\-p \(dqquarterly\(dq\f[R]
T}
.TE
.SS More complex report intervals
Some more complex intervals can be specified within period expressions,
such as:
.IP \(bu 2
\f[CR]biweekly\f[R] (every two weeks)
.IP \(bu 2
\f[CR]fortnightly\f[R]
.IP \(bu 2
\f[CR]bimonthly\f[R] (every two months)
.IP \(bu 2
\f[CR]every day|week|month|quarter|year\f[R]
.IP \(bu 2
\f[CR]every N days|weeks|months|quarters|years\f[R]
.PP
Weekly on a custom day:
.IP \(bu 2
\f[CR]every Nth day of week\f[R] (\f[CR]th\f[R], \f[CR]nd\f[R],
\f[CR]rd\f[R], or \f[CR]st\f[R] are all accepted after the number)
.IP \(bu 2
\f[CR]every WEEKDAYNAME\f[R] (full or three\-letter english weekday
name, case insensitive)
.PP
Monthly on a custom day:
.IP \(bu 2
\f[CR]every Nth day [of month]\f[R] (\f[CR]31st day\f[R] will be
adjusted to each month\(aqs last day)
.IP \(bu 2
\f[CR]every Nth WEEKDAYNAME [of month]\f[R]
.PP
Yearly on a custom month and day:
.IP \(bu 2
\f[CR]every MM/DD [of year]\f[R] (month number and day of month number)
.IP \(bu 2
\f[CR]every MONTHNAME DDth [of year]\f[R] (full or three\-letter english
month name, case insensitive, and day of month number)
.IP \(bu 2
\f[CR]every DDth MONTHNAME [of year]\f[R] (equivalent to the above)
.PP
Examples:
.PP
.TS
tab(@);
lw(26.8n) lw(43.2n).
T{
\f[CR]\-p \(dqbimonthly from 2008\(dq\f[R]
T}@T{
T}
T{
\f[CR]\-p \(dqevery 2 weeks\(dq\f[R]
T}@T{
T}
T{
\f[CR]\-p \(dqevery 5 months from 2009/03\(dq\f[R]
T}@T{
T}
T{
\f[CR]\-p \(dqevery 2nd day of week\(dq\f[R]
T}@T{
periods will go from Tue to Tue
T}
T{
\f[CR]\-p \(dqevery Tue\(dq\f[R]
T}@T{
same
T}
T{
\f[CR]\-p \(dqevery 15th day\(dq\f[R]
T}@T{
period boundaries will be on 15th of each month
T}
T{
\f[CR]\-p \(dqevery 2nd Monday\(dq\f[R]
T}@T{
period boundaries will be on second Monday of each month
T}
T{
\f[CR]\-p \(dqevery 11/05\(dq\f[R]
T}@T{
yearly periods with boundaries on 5th of November
T}
T{
\f[CR]\-p \(dqevery 5th November\(dq\f[R]
T}@T{
same
T}
T{
\f[CR]\-p \(dqevery Nov 5th\(dq\f[R]
T}@T{
same
T}
.TE
.PP
Show historical balances at end of the 15th day of each month (N is an
end date, exclusive as always):
.IP
.EX
$ hledger balance \-H \-p \(dqevery 16th day\(dq
.EE
.PP
Group postings from the start of wednesday to end of the following
tuesday (N is both (inclusive) start date and (exclusive) end date):
.IP
.EX
$ hledger register checking \-p \(dqevery 3rd day of week\(dq
.EE
.SS Multiple weekday intervals
This special form is also supported:
.IP \(bu 2
\f[CR]every WEEKDAYNAME,WEEKDAYNAME,...\f[R] (full or three\-letter
english weekday names, case insensitive)
.PP
Also, \f[CR]weekday\f[R] and \f[CR]weekendday\f[R] are shorthand for
\f[CR]mon,tue,wed,thu,fri\f[R] and \f[CR]sat,sun\f[R].
.PP
This is mainly intended for use with \f[CR]\-\-forecast\f[R], to
generate periodic transactions on arbitrary days of the week.
It may be less useful with \f[CR]\-p\f[R], since it divides each week
into subperiods of unequal length, which is unusual.
(Related: #1632)
.PP
Examples:
.PP
.TS
tab(@);
lw(17.8n) lw(52.2n).
T{
\f[CR]\-p \(dqevery mon,wed,fri\(dq\f[R]
T}@T{
dates will be Mon, Wed, Fri; periods will be Mon\-Tue, Wed\-Thu,
Fri\-Sun
T}
T{
\f[CR]\-p \(dqevery weekday\(dq\f[R]
T}@T{
dates will be Mon, Tue, Wed, Thu, Fri; periods will be Mon, Tue, Wed,
Thu, Fri\-Sun
T}
T{
\f[CR]\-p \(dqevery weekendday\(dq\f[R]
T}@T{
dates will be Sat, Sun; periods will be Sat, Sun\-Fri
T}
.TE
.SH Queries
Many hledger commands accept query arguments, which restrict their scope
and let you report on a precise subset of your data.
Here\(aqs a quick overview of hledger\(aqs queries:
.IP \(bu 2
By default, a query argument is treated as a case\-insensitive substring
pattern for matching account names.
Eg:
.RS 2
.PP
\f[CR]dining groceries\f[R]
.PD 0
.P
.PD
\f[CR]car:fuel\f[R]
.PD 0
.P
.PD
.RE
.IP \(bu 2
Patterns containing spaces or other special characters must be enclosed
in single or double quotes:
.RS 2
.PP
\f[CR]\(aqpersonal care\(aq\f[R]
.PD 0
.P
.PD
.RE
.IP \(bu 2
Patterns are actually regular expressions, so you can add regexp
metacharacters for more precision (or you may need to backslash\-escape
certain characters; see \(dqRegular expressions\(dq above):
.RS 2
.PP
\f[CR]\(aq\(haexpenses\(rsb\(aq\f[R]
.PD 0
.P
.PD
\f[CR]\(aqfood$\(aq\f[R]
.PD 0
.P
.PD
\f[CR]\(aqfuel|repair\(aq\f[R]
.PD 0
.P
.PD
\f[CR]\(aqaccounts (payable|receivable)\(aq\f[R]
.PD 0
.P
.PD
.RE
.IP \(bu 2
To match something other than the account name, you can add a query type
prefix, such as:
.RS 2
.PP
\f[CR]date:202312\-\f[R]
.PD 0
.P
.PD
\f[CR]status:\f[R]
.PD 0
.P
.PD
\f[CR]desc:amazon\f[R]
.PD 0
.P
.PD
\f[CR]cur:USD\f[R]
.PD 0
.P
.PD
\f[CR]cur:\(rs\(rs$\f[R]
.PD 0
.P
.PD
\f[CR]amt:\(aq>0\(aq\f[R]
.PD 0
.P
.PD
\f[CR]change:\(aq>100\(aq\f[R], \f[CR]balance:\(aq<0\(aq\f[R] (match
report rows or entries by their change or balance, see below)
.PD 0
.P
.PD
\f[CR]acct:groceries\f[R] (but \f[CR]acct:\f[R] is the default, so we
usually don\(aqt bother writing it)
.PD 0
.P
.PD
.RE
.IP \(bu 2
To match in any field, or by date, use the \f[CR]find:\f[R] query type,
or \f[CR]::\f[R] for short:
.RS 2
.PP
\f[CR]::amazon\f[R]
.PD 0
.P
.PD
\f[CR]::2024\f[R]
.PD 0
.P
.PD
\f[CR]::amazon ::2024\f[R] (both must match)
.PD 0
.P
.PD
.RE
.IP \(bu 2
To negate a query, add a \f[CR]not:\f[R] prefix:
.RS 2
.PP
\f[CR]not:status:\(aq*\(aq\f[R]
.PD 0
.P
.PD
\f[CR]not:desc:\(aqopening|closing\(aq\f[R]
.PD 0
.P
.PD
\f[CR]not:cur:USD\f[R]
.PD 0
.P
.PD
.RE
.IP \(bu 2
Multiple query terms can be combined, as space\-separated queries Eg:
\f[CR]hledger print date:2022 desc:amazon desc:amzn\f[R] (show
transactions dated in 2022 whose description contains \(dqamazon\(dq or
\(dqamzn\(dq).
.PD 0
.P
.PD
.IP \(bu 2
Or more flexibly as boolean queries.
Eg:
\f[CR]hledger print expr:\(aqdate:2022 and (desc:amazon or desc:amzn) and not date:202210\(aq\f[R]
.PD 0
.P
.PD
.PP
All hledger commands use the same query language, but different commands
may interpret the query in different ways.
Here\(aqs the gist of it (see PART 2: COMMANDS above for the commands):
.IP \(bu 2
Transaction\-oriented commands (\f[CR]print\f[R], \f[CR]aregister\f[R],
\f[CR]close\f[R], \f[CR]import\f[R], \f[CR]descriptions\f[R]..)
try to match transactions (including the transaction\(aqs postings).
.IP \(bu 2
Posting\-oriented commands (\f[CR]register\f[R], \f[CR]balance\f[R],
\f[CR]balancesheet\f[R], \f[CR]incomestatement\f[R],
\f[CR]accounts\f[R]..)
try to match postings.
Postings inherit their transaction\(aqs attributes for querying
purposes, so transaction fields like date or description can still be
referenced in a posting query.
.IP \(bu 2
A few commands match in more specific ways.
(Eg \f[CR]aregister\f[R], which has a special first argument.)
.SS Query types
Here are the query types available.
.PP
In the ones which take a regular expression, an empty one (eg
\f[CR]desc:\f[R] or \f[CR]::\f[R]) matches anything.
(Except in \f[CR]cur:\f[R], which must match the whole symbol, so an
empty \f[CR]cur:\f[R] matches amounts with no commodity symbol.)
.SS acct: query
\f[B]\f[CB]acct:REGEX\f[B]\f[R], or just \f[B]\f[CB]REGEX\f[B]\f[R]
.PD 0
.P
.PD
Match account names containing this case insensitive regular expression.
.PD 0
.P
.PD
This is the default query type, so we usually don\(aqt bother writing
the \(dqacct:\(dq prefix.
.SS amt: query
\f[B]\f[CB]amt:N, amt:\(aq<N\(aq, amt:\(aq<=N\(aq, amt:\(aq>N\(aq, amt:\(aq>=N\(aq\f[B]\f[R],
optionally with a commodity symbol, eg \f[CR]amt:\(aq>$100\(aq\f[R] or
\f[CR]amt:\(aq>100 EUR\(aq\f[R]
.PD 0
.P
.PD
Match postings with an amount equal to, less than, or greater than N.
\f[CR]amt:\f[R] needs quotes to hide the less than/greater than sign
from the command line shell.
.PP
The comparison has two modes: if N is preceded by a + or \- sign (or is
0), the two signed numbers are compared.
Otherwise, the absolute magnitudes are compared, ignoring sign.
.PP
If N has a commodity symbol (before or after the number, quoted with
\f[CR]\(dq\f[R] if needed), only amounts in that commodity are compared;
a posting with none doesn\(aqt match.
Otherwise, amounts in any commodity are compared.
A posting whose amount has several commodities matches if any one of
them does.
.PP
Keep in mind that \f[CR]amt:\f[R] matches posting amounts, not account
balances.
To match accounts, or periods, by their change or balance, use
\f[CR]change:\f[R] or \f[CR]balance:\f[R].
.SS balance: and change: queries
\f[B]\f[CB]change:N, change:\(aq<N\(aq, change:\(aq<=N\(aq, change:\(aq>N\(aq, change:\(aq>=N\(aq\f[B]\f[R],
\f[B]\f[CB]balance:N, balance:\(aq<N\(aq, balance:\(aq<=N\(aq, balance:\(aq>N\(aq, balance:\(aq>=N\(aq\f[B]\f[R],
optionally with a commodity symbol, eg \f[CR]change:\(aq>$100\(aq\f[R]
or \f[CR]balance:\(aq<0 EUR\(aq\f[R]
.PD 0
.P
.PD
Match report rows (or entries) by their summed amounts:
\f[CR]change:\f[R] by the row\(aqs change, the sum of its postings;
\f[CR]balance:\f[R] by the row\(aqs balance, the sum of all its postings
up to the end of its period.
Unlike \f[CR]amt:\f[R], which tests each posting before postings are
added up, these test the amounts a report shows after adding them up.
Eg:
.IP
.EX
$ hledger bal expenses change:\(aq>100\(aq # expense accounts which changed by more than 100
$ hledger bal assets balance:\(aq<0\(aq # asset accounts with a negative balance
$ hledger reg gifts \-M change:\(aq>100\(aq # months with more than 100 in gift expenses
$ hledger areg checking balance:\(aq<0\(aq # the transactions after which checking was overdrawn
$ hledger print not:change:0 # entries with a tolerated imbalance or unbalanced virtual postings
.EE
.PP
The comparison works as with \f[CR]amt:\f[R]: signed if N has a + or \-
sign (or is 0), otherwise by absolute magnitude.
Like \f[CR]amt:\f[R], these test amounts\(aq real signs, not the signs
they are displayed with (after \f[CR]\-\-invert\f[R], or the sign
normalisation in \f[CR]balancesheet\f[R], \f[CR]incomestatement\f[R]
etc.); so \f[CR]incomestatement change:\(aq<\-1000\(aq\f[R] finds the
large revenues.
If N has a commodity symbol, only that commodity\(aqs part of the amount
is compared, and an amount with none of it doesn\(aqt match.
An amount with several commodities matches if any one of them does.
.PP
\f[CR]balance:\f[R] always means the actual balance, from the start of
the journal (or of the postings matched by the other query terms),
whether or not the report is a historical (\f[CR]\-H\f[R]) one.
So the amounts a report shows are not always the ones tested;
\f[CR]\-H\f[R] shows balances.
A date span (\f[CR]date:2026\f[R], \f[CR]\-p\f[R],
\f[CR]\-b\f[R]/\f[CR]\-e\f[R]) sets the report period and does not limit
the balance, as with \f[CR]\-H\f[R].
But query terms which exclude postings also exclude them from the
balance; this includes \f[CR]not:date:\f[R] and date terms combined with
OR.
.PP
What is tested depends on the kind of item being matched:
.IP \(bu 2
In balance reports (\f[CR]balance\f[R], \f[CR]balancesheet\f[R],
\f[CR]incomestatement\f[R], etc.), each account\(aqs own change over the
report period, or its own balance at the end of the report period, as
shown in list mode (without or with \f[CR]\-H\f[R]).
In a multi\-period report, the change is the row\(aqs Total column, and
the balance is the last column\(aqs (with \f[CR]\-H\f[R]).
Accounts which don\(aqt match are left out, as if excluded by an account
query.
So in tree mode, a parent account is shown if it has matching
subaccounts, with a balance including just those; and the report\(aqs
totals and percentages include just the matching accounts.
To test parent accounts\(aq subaccount\-inclusive amounts instead, limit
the depth, eg \f[CR]bal \-1 change:\(aq>100\(aq\f[R].
An account matched by \f[CR]balance:\f[R] is shown even if it had no
postings in the report period.
.IP \(bu 2
In budget reports (\f[CR]balance \-\-budget\f[R]), rows are hidden if
their actual change or balance (including subaccounts) doesn\(aqt match.
The other rows, and the totals, are unchanged, since budget goals are
often set on parent accounts.
.IP \(bu 2
In \f[CR]register\f[R], \f[CR]change:\f[R] tests each posting\(aqs
amount, or with a report interval, each period\(aqs amount;
\f[CR]balance:\f[R] tests the running total after it (the actual
balance, even without \f[CR]\-H\f[R]).
.IP \(bu 2
In \f[CR]aregister\f[R], \f[CR]change:\f[R] tests each transaction\(aqs
change to the account; \f[CR]balance:\f[R] tests the account\(aqs
balance after it.
.IP \(bu 2
In \f[CR]print\f[R] (and \f[CR]descriptions\f[R], \f[CR]notes\f[R] and
\f[CR]codes\f[R]), both test each entry\(aqs sum of postings (an entry
has no balance), converted to cost as in transaction balancing,
including any unbalanced virtual postings.
Since an entry\(aqs real postings must balance, this will be zero, or a
small tolerated imbalance, plus the amount of any unbalanced virtual
postings.
(To find large transactions, use \f[CR]amt:\f[R] instead, eg
\f[CR]print amt:\(aq>1000\(aq\f[R].)
.IP \(bu 2
In \f[CR]holdings\f[R], each line (one commodity in one account) has two
amounts, its units and its market value.
\f[CR]balance:\f[R] tests the units, or with a commodity symbol,
whichever of them is in that commodity (so
\f[CR]balance:\(aq>$1000\(aq\f[R] tests the value).
\f[CR]change:\f[R] likewise tests the change in units during the report
period, or its value.
Unlike in other reports, \f[CR]\-V\f[R]/\f[CR]\-X\f[R] don\(aqt change
which amount is tested; to test the value, write its commodity symbol.
With \f[CR]\-B\f[R], the cost is tested instead of the value (eg
\f[CR]holdings \-B balance:\(aq>$1000\(aq\f[R]).
The totals cover just the lines shown, but Weight is still relative to
all the holdings.
.IP \(bu 2
Other commands ignore these terms.
.PP
In registers, hidden rows still count in the running total or balance,
which is the account\(aqs real one.
(Unlike \f[CR]amt:\f[R], which excludes the postings themselves, so they
don\(aqt count.)
.PP
\f[CR]change:\f[R] and \f[CR]balance:\f[R] can be combined with other
query terms only by AND, and negated with \f[CR]not:\f[R].
They can\(aqt be used inside OR, a negated group, \f[CR]any:\f[R] or
\f[CR]all:\f[R].
As with other query terms which aren\(aqt OR\(aqd, multiple terms must
all match, so \f[CR]change:\(aq>100\(aq change:\(aq<500\(aq\f[R] selects
a range, and \f[CR]change:\(aq>100\(aq balance:\(aq<0\(aq\f[R] requires
both.
.SS code: query
\f[B]\f[CB]code:REGEX\f[B]\f[R]
.PD 0
.P
.PD
Match by transaction code (eg check number).
.SS cur: query
\f[B]\f[CB]cur:FULLREGEX\f[B]\f[R]
.PD 0
.P
.PD
Match postings or transactions including any amounts whose
currency/commodity symbol is fully matched by REGEX.
(Contrary to hledger\(aqs usual infix matching.
To do infix matching, write \f[CR].*REGEX.*\f[R].)
.PP
To match special characters which are regex\-significant, escape them
with \f[CR]\(rs\f[R].
And at the command line, characters which are shell\-significant need
one more level of escaping \- eg to match the dollar sign, write
\f[CR]cur:\(rs\(rs$\f[R] or \f[CR]cur:\(aq\(rs$\(aq\f[R].
.PP
Amounts written with a commodity alias have been converted to the
commodity, so \f[CR]cur:\f[R] matches them by the commodity\(aqs symbol,
not the alias.
.PD 0
.P
.PD
.SS desc: query
\f[B]\f[CB]desc:REGEX\f[B]\f[R]
.PD 0
.P
.PD
Match transaction descriptions.
.SS date: query
\f[B]\f[CB]date:PERIODEXPR\f[B]\f[R]
.PD 0
.P
.PD
Match dates (or with the \f[CR]\-\-date2\f[R] flag, secondary dates)
within the specified period.
PERIODEXPR is a period expression.
Examples:
.PD 0
.P
.PD
\f[CR]date:2016\f[R], \f[CR]date:thismonth\f[R],
\f[CR]date:2/1\-2/15\f[R], \f[CR]date:2021\-07\-27..nextquarter\f[R].
.PP
PERIODEXPR may include a report interval (since 1.52).
On the command line, this is equivalent to specifying a report interval
with a command line option.
In other contexts (hledger\-ui, hledger\-web), the report interval may
be ignored.
.SS date2: query
\f[B]\f[CB]date2:PERIODEXPR\f[B]\f[R]
.PD 0
.P
.PD
If you use secondary dates: this matches secondary dates within the
specified period.
It is not affected by the \f[CR]\-\-date2\f[R] flag.
A report interval in PERIODEXPR will be ignored.
.SS depth: query
\f[B]\f[CB]depth:[REGEXP=]N\f[B]\f[R]
.PD 0
.P
.PD
Match (or display, depending on command) accounts at or above this
depth, optionally only for accounts matching a provided regular
expression.
See Depth for detailed rules.
.SS find: query
\f[B]\f[CB]find:REGEX\f[B]\f[R], or \f[B]\f[CB]::REGEX\f[B]\f[R]
.PD 0
.P
.PD
Match if any text field contains this case insensitive regular
expression: the account name, the amount (as it would be displayed), the
comment, the transaction\(aqs description, code and comment, or the name
or value of any tag.
Tags include hidden tags and tags inherited from account and commodity
declarations, so a match may come from a tag not shown in
\f[CR]print\f[R] output.
Eg \f[CR]::dispose\f[R] finds lot disposals, which have a hidden
\f[CR]ptype: dispose\f[R] tag.
To see why something matched, \f[CR]print \-\-verbose\-tags\f[R] shows
the hidden tags; for inherited tags, check the account or commodity
directive.
Or, if REGEX is also a valid period expression, match if the date is
within that period.
So \f[CR]::amazon\f[R] finds \(dqamazon\(dq anywhere, and
\f[CR]::2024\f[R] finds \(dq2024\(dq in any field or a date in 2024.
Unlike \f[CR]date:\f[R], this does not set the report period.
.PP
Multiple \f[CR]find:\f[R] terms must all match, like the words of a
search.
Eg \f[CR]::amazon ::2024\f[R] shows things matching both.
(In a transaction\-oriented command like \f[CR]print\f[R], the terms may
be matched by different postings.)
To match alternatives, use a regular expression:
\f[CR]::\(aqamazon|amzn\(aq\f[R].
.SS note: query
\f[B]\f[CB]note:REGEX\f[B]\f[R]
.PD 0
.P
.PD
Match transaction notes (the part of the description right of
\f[CR]|\f[R], or the whole description if there\(aqs no \f[CR]|\f[R]).
.SS payee: query
\f[B]\f[CB]payee:REGEX\f[B]\f[R]
.PD 0
.P
.PD
Match transaction payee/payer names (the part of the description left of
\f[CR]|\f[R], or the whole description if there\(aqs no \f[CR]|\f[R]).
.SS real: query
\f[B]\f[CB]real:, real:0\f[B]\f[R]
.PD 0
.P
.PD
Match real or virtual postings respectively.
.SS status: query
\f[B]\f[CB]status:, status:!, status:*\f[B]\f[R]
.PD 0
.P
.PD
Match unmarked, pending, or cleared transactions respectively.
.SS type: query
\f[B]\f[CB]type:TYPECODES\f[B]\f[R]
.PD 0
.P
.PD
Match by account type (see Declaring accounts > Account types).
\f[CR]TYPECODES\f[R] is one or more of the single\-letter account type
codes \f[CR]ALERXCVGUM\f[R], case insensitive.
Note \f[CR]type:A\f[R], \f[CR]type:E\f[R], and \f[CR]type:R\f[R] will
also match their respective subtypes \f[CR]C\f[R] (Cash), \f[CR]V\f[R]
(Conversion), \f[CR]U\f[R] (UnrealisedGain) and \f[CR]M\f[R]
(Imbalance), and \f[CR]G\f[R] (Gain).
Certain kinds of account alias can disrupt account types, see Rewriting
accounts > Aliases and account types.
.SS tag: query
\f[B]\f[CB]tag:NAMEREGEX[=VALREGEX]\f[B]\f[R]
.PD 0
.P
.PD
Match by tag name, and optionally also by tag value.
Note:
.IP \(bu 2
Both regular expressions do infix matching.
If you need a complete match, use \f[CR]\(ha\f[R] and \f[CR]$\f[R].
.PD 0
.P
.PD
Eg: \f[CR]tag:\(aq\(hafullname$\(aq\f[R],
\f[CR]tag:\(aq\(hafullname$=\(hafullvalue$\f[R]
.IP \(bu 2
To match values, ignoring names, do \f[CR]tag:=VALREGEX\f[R]
.IP \(bu 2
With an empty NAMEREGEX, \f[CR]tag:\f[R] matches anything which has a
tag, and \f[CR]not:tag:\f[R] matches anything which has none.
.IP \(bu 2
With an empty VALREGEX, \f[CR]tag:NAMEREGEX=\f[R] matches that tag with
any value.
.IP \(bu 2
Accounts also inherit the tags of their parent accounts.
.IP \(bu 2
Postings also inherit the tags of their account and their transaction .
.IP \(bu 2
Transactions also acquire the tags of their postings.
.SS Negative queries
.SS not: query
\f[B]\f[CB]not:QUERY\f[B]\f[R]
.PD 0
.P
.PD
You can prepend \f[B]\f[CB]not:\f[B]\f[R] to a query to negate the
match.
.PD 0
.P
.PD
Eg: \f[CR]not:equity\f[R], \f[CR]not:desc:apple\f[R]
.PD 0
.P
.PD
(Also, a trick: \f[CR]not:not:...\f[R] can sometimes solve query
problems conveniently.)
.SS Space\-separated queries
When given multiple space\-separated query terms, most commands select
things which match:
.IP \(bu 2
any of the description terms AND
.IP \(bu 2
any of the account terms AND
.IP \(bu 2
any of the status terms AND
.IP \(bu 2
all the other terms.
.PP
The print command is a little different, showing transactions which:
.IP \(bu 2
match any of the description terms AND
.IP \(bu 2
have any postings matching any of the positive account terms AND
.IP \(bu 2
have no postings matching any of the negative account terms AND
.IP \(bu 2
match all the other terms.
.SS Boolean queries
For more complex needs, you can combine query terms with \f[CR]NOT\f[R],
\f[CR]AND\f[R], \f[CR]OR\f[R] operators (case insensitive) and
parentheses, writing the whole expression in quotes with one of three
prefixes: \f[CR]expr:\f[R], \f[CR]any:\f[R] or \f[CR]all:\f[R].
Eg, to show transactions involving both cash and expense accounts:
.IP
.EX
hledger print expr:\(aqcash AND expenses\(aq
.EE
.PP
The prefix and the quotes are required.
Two more things to know:
.IP \(bu 2
\f[CR]date:\f[R] queries may not be used inside an OR expression (it
could produce a report with disjoint or unclear report periods).
.IP \(bu 2
Space\-separated terms can also appear inside a boolean query, combining
as described in space\-separated queries; but it\(aqs probably clearer
to avoid mixing the two styles.
.SS expr: query
\f[B]\f[CB]expr:\(aqQUERYEXPR\(aq\f[B]\f[R]
.PD 0
.P
.PD
The general purpose boolean query.
It can match transactions, postings, accounts, etc.
depending on context.
Eg, \f[CR]expr:\(aqdate:lastmonth AND NOT (food OR rent)\(aq\f[R]
matches things dated in the last month, without food or rent in the
account name.
.PP
With transaction\-oriented commands like \f[CR]print\f[R],
posting\-oriented terms like \f[CR]acct:\f[R] and \f[CR]amt:\f[R] match
a transaction if they match any of its postings.
So, \f[CR]hledger print expr:\(aqcash AND amt:>0\(aq\f[R] shows
transactions which have at least one cash posting and at least one
positive\-amount posting (these are not necessarily the same posting).
.SS any: query
\f[B]\f[CB]any:\(aqQUERYEXPR\(aq\f[B]\f[R]
.PD 0
.P
.PD
Matches a transaction, if at least one of its postings is matched by
QUERYEXPR.
So, \f[CR]hledger print any:\(aqcash AND amt:>0\(aq\f[R] shows
transactions which have at least one posting that both involves a cash
account and has a positive amount.
.PP
Unlike \f[CR]expr:\f[R], \f[CR]any:\f[R] always considers whole
transactions.
So, \f[CR]hledger balance expenses any:cash\f[R] shows expenses from
transactions involving cash, and
\f[CR]hledger balance expenses not:any:cash\f[R] shows expenses from
transactions not involving cash.
.PP
A query containing only \f[CR]any:\f[R] (or \f[CR]all:\f[R]) terms
selects entire transactions, so its balance report will be
zero\-balanced, showing where the money in those transactions came from
and went to.
For the same reason, such a query combined with \f[CR]register\f[R]\(aqs
\f[CR]\-\-related\f[R] flag shows nothing: every posting is matched, so
there are no unmatched related postings left to show.
.SS all: query
\f[B]\f[CB]all:\(aqQUERYEXPR\(aq\f[B]\f[R]
.PD 0
.P
.PD
Matches a transaction, if it has at least one posting and all of its
postings are matched by QUERYEXPR.
So, \f[CR]hledger print all:\(aqcash OR checking\(aq\f[R] shows
transactions touching only cash and/or checking accounts.
.PP
Like \f[CR]any:\f[R], \f[CR]all:\f[R] always considers whole
transactions.
So, \f[CR]hledger register all:\(aqcash OR checking\(aq\f[R] shows the
postings of transactions touching only cash and/or checking accounts \-
eg, transfers between those two.
By contrast, \f[CR]hledger register expr:\(aqcash OR checking\(aq\f[R]
tests each posting on its own, so it could also show, say, the cash
posting of a grocery purchase.
.SS Queries and command options
Some queries can also be expressed as command\-line options:
\f[CR]depth:2\f[R] is equivalent to \f[CR]\-\-depth 2\f[R],
\f[CR]date:2023\f[R] is equivalent to \f[CR]\-p 2023\f[R], etc.
When you mix command options and query arguments, generally the
resulting query is their intersection.
.SS Queries and account aliases
When account names are rewritten by account aliases, queries see only
the new account names.
Eg with \f[CR]alias checking = assets:bank:checking\f[R],
\f[CR]acct:bank\f[R] matches the rewritten postings, but
\f[CR]acct:\(hachecking\f[R] does not.
.SS Queries and valuation
When amounts are converted to other commodities in cost or value
reports, \f[CR]cur:\f[R] and \f[CR]amt:\f[R] match the old commodity
symbol and the old amount quantity, not the new ones.
\f[CR]change:\f[R] and \f[CR]balance:\f[R] match the converted amounts,
except in \f[CR]print\f[R] (see balance: and change: queries).
(With \f[CR]\-B\f[R] and no \f[CR]\-\-lots\f[R], a sale from several
lots may be left out by \f[CR]cur:\f[R] or \f[CR]amt:\f[R], since it is
matched as converted to cost; add \f[CR]\-\-lots\f[R] to match it as
written.)
.SH Depth
With the \f[CR]\-\-depth NUM\f[R] option (short form, usually preferred:
\f[CR]\-NUM\f[R]), reports will show accounts only to the specified
depth, hiding deeper subaccounts.
Use this when you want a summary with less detail.
This flag has the same effect as a \f[CR]depth:\f[R] query argument.
So all of these are equivalent: \f[CR]depth:2\f[R],
\f[CR]\-\-depth=2\f[R], \f[CR]\-2\f[R].
.PP
You can also provide custom depths for specific accounts, by providing a
\f[CR]REGEX=NUM\f[R] argument instead of just \f[CR]NUM\f[R].
For example, \f[CR]\-\-depth assets=2\f[R] (or
\f[CR]depth:assets=2\f[R]) will collapse accounts matching the regular
expression \(dqassets\(dq to depth 2.
So \f[CR]assets:bank:savings\f[R] would be collapsed to
\f[CR]assets:bank\f[R], but \f[CR]liabilities:bank:credit card\f[R]
would not be affected.
.PP
If REGEX contains spaces or other special characters, enclose it in
quotes in the usual way.
Eg: \f[CR]\-\-depth \(aqcredit card=2\(aq\f[R]
.SS Combining depth options
If a command line contains multiple general depth options, the last one
wins.
(Useful for overriding a depth specified by scripts.)
.PP
Or a command may contain a combination of general and custom depth
options.
In this case, the most specifically (deepest) matching option wins.
Some examples:
.IP \(bu 2
\f[CR]\-\-depth assets=3 \-\-depth expenses=2 \-\-depth 1\f[R] would
collapse accounts containing \(dqassets\(dq to depth 3, accounts
containing \(dqexpenses\(dq to depth 2, and all other accounts to depth
1.
.IP \(bu 2
\f[CR]\-\-depth assets=1 \-\-depth savings=2\f[R] would collapse
\f[CR]assets:bank:savings\f[R] to depth 2 (not depth 1; because
\(dqsavings\(dq matches a deeper part of the account name than
\(dqassets\(dq).
.PP
Note currently, to override a custom depth option
\f[CR]\-\-depth REGEX=NUM\f[R] with a later option, the later option
must use the same REGEX.
.SH Pivoting
Normally, hledger groups amounts and displays their totals by account
(name).
With \f[CR]\-\-pivot PIVOTEXPR\f[R], some other field\(aqs (or multiple
fields\(aq) value is used as a synthetic account name, causing different
grouping and display.
PIVOTEXPR can be
.IP \(bu 2
any of these standard transaction or posting fields (their value is
substituted): \f[CR]status\f[R], \f[CR]code\f[R],
\f[CR]desc\f[R]/\f[CR]description\f[R], \f[CR]payee\f[R],
\f[CR]note\f[R], \f[CR]acct\f[R]/\f[CR]account\f[R],
\f[CR]comm\f[R]/\f[CR]cur\f[R], \f[CR]amt\f[R], \f[CR]cost\f[R]
.IP \(bu 2
or a tag name
.IP \(bu 2
or any combination of these, colon\-separated.
.PP
Some special cases:
.IP \(bu 2
Colons appearing in PIVOTEXPR or in a pivoted tag value will generate
account hierarchy.
.IP \(bu 2
When pivoting a posting that has multiple values for a tag, the tag\(aqs
first value will be used as the pivoted value.
.IP \(bu 2
When a posting has multiple commodities, the pivoted value of
\(dqcomm\(dq/\(dqcur\(dq will be \(dq\(dq.
Also when an unrecognised tag name or field is provided, its pivoted
value will be \(dq\(dq.
(If this causes confusing output, consider excluding those postings from
the report.)
.PP
Examples:
.IP
.EX
2016/02/16 Yearly Dues Payment
assets:bank account 2 EUR
income:dues \-2 EUR ; member: John Doe, kind: Lifetime
.EE
.PP
Normal balance report showing account names:
.IP
.EX
$ hledger balance
2 EUR assets:bank account
\-2 EUR income:dues
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
Pivoted balance report, using member: tag values instead:
.IP
.EX
$ hledger balance \-\-pivot member
2 EUR
\-2 EUR John Doe
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
One way to show only amounts with a member: value (using a query):
.IP
.EX
$ hledger balance \-\-pivot member tag:member=.
\-2 EUR John Doe
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
\-2 EUR
.EE
.PP
Another way (the acct: query matches against the pivoted \(dqaccount
name\(dq):
.IP
.EX
$ hledger balance \-\-pivot member acct:.
\-2 EUR John Doe
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
\-2 EUR
.EE
.PP
Hierarchical reports can be generated with multiple pivot values:
.IP
.EX
$ hledger balance Income:Dues \-\-pivot kind:member
\-2 EUR Lifetime:John Doe
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
\-2 EUR
.EE
.SH Report titles
Some reports (\f[CR]aregister\f[R], \f[CR]balance\f[R] (multi\-period),
\f[CR]balancesheet\f[R], \f[CR]balancesheetequity\f[R],
\f[CR]cashflow\f[R], \f[CR]holdings\f[R], \f[CR]incomestatement\f[R])
are displayed with a title by default, and others are not.
For most reports you can set a title with
\f[CR]\-\-title=\(aqSome Text\(aq\f[R], or suppress the title with
\f[CR]\-\-title=\f[R].
Titles are shown in text and HTML output (and in some commands\(aq
CSV/TSV output).
In HTML output the title is an
\f[CR]<h3 class=\(dqreport\-title\(dq>\f[R] element, which you can style
with a \f[CR]hledger.css\f[R] file.
.PP
Compound reports, like those just mentioned, also have subreport
headings, like Assets and Liabilities in the balance sheet.
You can customise these with
\f[CR]\-\-subreport\-titles=HEADING1|HEADING2..\f[R], or suppress them
with \f[CR]\-\-subreport\-titles=\f[R].
.PP
In both \f[CR]\-\-title\f[R] and \f[CR]\-\-subreport\-titles\f[R], you
can use \f[CR]\(rsn\f[R] to generate a newline.
.PP
In multi\-period reports each period has a heading describing its date
range or end date.
When date ranges correspond to natural period boundaries, they are
described compactly by default.
Eg: \f[CR]2026\f[R], \f[CR]Q1\f[R], \f[CR]Jan\f[R], \f[CR]W02\f[R].
(Month names follow the \f[CR]\-\-lang\f[R] option.)
You can disable these compact descriptions by using
\f[CR]\-\-period\-titles=dates\f[R]; then periods will always be
described as \f[CR]STARTDATE..ENDDATE\f[R].
.SH Languages
hledger\(aqs output is in English by default.
Report titles, section headings, column headings, month names and
similar structural text can be shown in another language with the
\f[CR]\-\-lang\f[R] option (which can also be set in a config file),
when a translation catalog for that language is available.
(This is hledger\(aqs localization support; it covers the language of
hledger\(aqs own text, not number or date formats, which come from the
journal, as described below.)
.IP \(bu 2
\f[CR]\-\-lang=LANG\f[R] selects a language by its tag, like
\f[CR]de\f[R] or \f[CR]pt\-BR\f[R].
An unavailable language is an error.
.IP \(bu 2
\f[CR]\-\-lang=auto\f[R] selects the language from the environment (the
LANGUAGE, LC_ALL, LC_MESSAGES and LANG variables, see Environment),
falling back to English.
.IP \(bu 2
\f[CR]\-\-lang=en\f[R], or no \f[CR]\-\-lang\f[R] option, selects
English.
.PP
To always get German output, for example, put it in your config
file\(aqs general options:
.IP
.EX
# \(ti/.config/hledger/hledger.conf
\-\-lang de
.EE
.PP
Currently Brazilian Portuguese (\f[CR]pt\-BR\f[R]), French
(\f[CR]fr\f[R]), German (\f[CR]de\f[R]), Hawaiian (\f[CR]haw\f[R]),
Irish (\f[CR]ga\f[R]), Italian (\f[CR]it\f[R]), Japanese
(\f[CR]ja\f[R]), Russian (\f[CR]ru\f[R]), Simplified Chinese
(\f[CR]zh\f[R], also selected by \f[CR]zh_CN\f[R] or
\f[CR]zh\-Hans\f[R]), Spanish (\f[CR]es\f[R]) and Ukrainian
(\f[CR]uk\f[R]) catalogs are built in.
Catalogs are gettext PO files, which the usual translation tools can
edit.
hledger also looks for catalogs in the \f[CR]locale\f[R] subdirectory of
its config directory (\f[CR]\(ti/.config/hledger/locale/LANG.po\f[R] on
unix, \f[CR]%APPDATA%\(rshledger\(rslocale\(rsLANG.po\f[R] on windows),
and merges a catalog found there over the built\-in catalog for the same
language, if any.
So a translator can work on a new language with a released hledger, and
a user can adjust terminology to taste.
\f[CR]hledger \-\-write\-lang=LANG\f[R] puts a catalog there to start
from: a copy of the built\-in catalog for that language, or for a new
language, an untranslated one.
(It won\(aqt overwrite a catalog that is already there.)
Contributed catalogs are welcome, and no programming is needed: see
Translating hledger in the developer docs.
.PP
Only hledger\(aqs own structural text is translated.
Your data (account names, descriptions, amounts) is never changed; dates
keep their ISO format, and numbers keep the display styles declared for
each commodity.
Error messages, journal\-format output, and the column headings of CSV,
TSV and JSON output stay in English, since they are commonly read by
other programs.
Report titles, however, are translated wherever they appear, as they
would be with \f[CR]\-\-title\f[R]; and an explicit \f[CR]\-\-title\f[R]
or \f[CR]\-\-subreport\-titles\f[R] is always used as given,
untranslated.
.SH Amount arithmetic
.PP
hledger uses decimal (Decimal) numbers for accounting arithmetic:
amounts, balances, costs, prices, valuation and gains.
Floating point (Double) numbers are used for inherently approximate
statistics like \f[CR]stats\f[R] txns/s, \f[CR]prices \-\-summary\f[R]
coverage, \f[CR]roi\f[R] and \f[CR]holdings\f[R] rates of return, and
debug timings, where they are a better fit.
.PP
Unlike the usual floating point numbers, which are binary and
fixed\-size, and so frequently rounded, decimal numbers are base ten, so
amounts like 0.1 are stored exactly, and they can have up to 255 decimal
places (and any number of digits in the integer part).
Addition, subtraction and multiplication are exact (as long as the
result needs no more than 255 decimal places).
Division can produce a non\-terminating decimal (like 1/3 = 0.333...);
hledger rounds these to 255 decimal places.
The error is less than 10\(ha\-250, too small to affect transaction
balancing or reports at normal display precisions.
When hledger shows such a rounded amount in full, eg in \f[CR]print\f[R]
output, it shows 8 decimal places.
.SS Where hledger divides
Non\-terminating decimals can arise only where hledger divides.
(Journal amounts are written as finite decimals, and amount expressions
round their results, except in costs.)
Here\(aqs when that happens:
.PP
.TS
tab(@);
lw(26.2n) lw(12.2n) lw(31.5n).
T{
When
T}@T{
What is divided
T}@T{
Visible effect
T}
_
T{
Dividing in an amount expression (\f[CR]$100.00 / 3\f[R])
T}@T{
amount / number
T}@T{
None: the result is rounded to the entry\(aqs decimal places for that
commodity when the journal is read, so it is exactly what
\f[CR]print\f[R] shows.
A split that doesn\(aqt divide evenly makes the transaction unbalanced,
unless one amount is left blank.
T}
T{
Dividing in a cost expression (\f[CR]\(at 1 / 1.14 EUR\f[R])
T}@T{
amount / number, or number / amount
T}@T{
None in calculations: the cost is kept exact.
\f[CR]print\f[R] shows a repeating decimal with 8 decimal places (more
if written), so text copied from it is slightly rounded.
T}
T{
Converting a lot\(aqs total cost (\f[CR]\(at\(at\f[R]) or total cost
basis (\f[CR]{{ }}\f[R]) to a unit cost
T}@T{
total cost / quantity
T}@T{
None in calculations: gains use the unrounded unit cost.
Lot names and \f[CR]print\f[R] show it with up to 8 decimal places (more
if the cost commodity\(aqs display style has more), so text copied from
them is slightly rounded; see Cost basis precision.
T}
T{
Inferring market prices from costs, with
\f[CR]\-\-infer\-market\-prices\f[R]
T}@T{
total cost / quantity
T}@T{
None
T}
T{
Using a reverse market price
T}@T{
1 / price
T}@T{
None
T}
T{
Averaging lot costs, with the AVERAGE cost basis methods or in holdings
T}@T{
total cost / total quantity
T}@T{
None
T}
T{
Inferring costs from equity conversion postings
T}@T{
one amount / the other
T}@T{
None
T}
T{
Inferring a unit cost for several postings in one commodity, in an
implicit conversion
T}@T{
total / quantity
T}@T{
None in calculations.
\f[CR]print \-x\f[R] shows it with 8 decimal places (more if the
commodities\(aq decimal places add up to more), so text copied from it
is slightly rounded.
T}
T{
Converting amounts written with a commodity alias that has a quantity
T}@T{
amount / alias quantity
T}@T{
None in calculations: unit costs are replaced by exact total costs, and
balance assertions convert the alias amounts\(aq total (so three
\f[CR]10 min\f[R] amounts satisfy a \f[CR]= 0.5 h\f[R] assertion).
\f[CR]print \-x\f[R] shows converted amounts with all their decimal
places (8 for a repeating decimal).
T}
T{
Calculating averages (eg \f[CR]\-A\f[R]) and percentages (eg
\f[CR]\-%\f[R]) in reports
T}@T{
total / count, part / total
T}@T{
None: these are displayed rounded
T}
T{
Converting times to hours in timeclock entries, and timedot durations
written in minutes or seconds (\f[CR]10m\f[R])
T}@T{
time / hour length
T}@T{
Negligible: each is rounded at the 255th decimal place, so eg three
\f[CR]10m\f[R] timedot entries total 0.50 hours, as displayed.
But that total isn\(aqt exactly 0.5, so a balance assertion of
\f[CR]0.5\f[R] hours on it would fail.
Reports show durations with 2 decimal places; \f[CR]print\f[R] shows a
repeating decimal with 8 (\f[CR]0.16666667\f[R]).
T}
T{
Calculating rates of return: roi\(aqs IRR and TWR, and holdings\(aq XIRR
column
T}@T{
various
T}@T{
Rates are approximate (calculated with floating point numbers; IRR and
XIRR by iteration)
T}
.TE
.SH Transaction balancing
A transaction\(aqs postings must add up to zero.
When they are all in one commodity, this is simple: the sum must be
exactly zero.
But when a transaction converts between commodities using a cost, the
cost is often rounded (by you, or by your bank or broker), and requiring
an exact zero would reject many correct\-looking entries.
So, like Ledger and Beancount, hledger allows a small tolerance.
.SS How balancing is checked
For each commodity in a journal entry, hledger:
.IP "1." 3
adds up the posting amounts in that commodity, after converting any
amounts that have a cost to the cost\(aqs commodity (exactly; see Amount
arithmetic)
.IP "2." 3
finds the entry\(aqs \f[I]balancing precision\f[R] for that commodity:
the most decimal places used by that commodity\(aqs amounts in the
entry, not counting cost amounts
.IP "3." 3
considers the entry balanced if the sum rounds to zero at that
precision.
In other words, the imbalance can be at most half a unit in the last
decimal place: 0.005 for amounts with 2 decimal places, 0.5 for amounts
with no decimal places.
.PP
Eg:
.IP
.EX
2024\-01\-30 currency exchange
assets:usd \-19110.17 USD \(at 0.869050 CHF
assets:chf 16607.69 CHF
.EE
.PP
The first posting converts to \-16607.6932385 CHF, so the sum in CHF is
\-0.0032385 CHF.
The balancing precision for CHF is 2 (from 16607.69 CHF; the cost amount
0.869050 CHF doesn\(aqt count).
\-0.0032385 rounded to 2 decimal places is zero, so this entry is
accepted.
.PP
To make hledger check an entry more strictly, write its amounts with
more decimal places.
Eg if the second amount above is written as 16607.690 CHF, the balancing
precision becomes 3 and the entry is rejected.
.SS Where imbalances come from
.IP \(bu 2
Rounded unit costs (\f[CR]\(at\f[R]).
The exact rate may have infinitely many decimal places (above, the exact
rate is 16607.69 / 19110.17 = 0.86904983053...), or just more than your
bank or broker shows you.
This is the most common cause.
.IP \(bu 2
Total costs (\f[CR]\(at\(at\f[R]) that don\(aqt quite match the other
amounts.
Eg this entry is accepted, because the balancing precision for $ is 0
(because $100 was written with no decimals):
.RS 2
.IP
.EX
2026\-01\-01
assets:stock \-3 AAPL \(at\(at $100.40
assets:cash $100
.EE
.RE
.SS Accumulated imbalances
Accepted imbalances are not corrected; they stay in the data, and add
up.
So reports which convert amounts at cost, like \f[CR]balance \-B\f[R] or
\f[CR]balancesheetequity \-B\f[R], may show a small non\-zero total
where you would expect zero.
Eg after three of the currency exchange entries above,
\f[CR]hledger bal \-B\f[R] shows a total of \-0.01 CHF.
Typically this is a few cents, but each entry can contribute up to half
a unit in its last decimal place.
.PP
(Without cost conversion, these imbalances aren\(aqt directly visible.
And with \f[CR]\-\-infer\-equity\f[R], each commodity balances exactly,
and the imbalances become part of the conversion rates.)
.PP
To see an accumulated imbalance more precisely, increase the display
precision with \f[CR]\-c\f[R].
Eg:
.IP
.EX
$ hledger bal \-B \-c \(aqCHF 1.000000000\(aq
.EE
.PP
And to see which entries contribute to it, use a register report:
\f[CR]hledger reg \-B \-c \(aqCHF 1.000000000\(aq\f[R].
Or, show the imbalances explicitly, as described next.
.SS Showing imbalances
With the \f[CR]\-\-infer\-imbalance\f[R] flag, hledger shows entry
imbalances explicitly, by generating postings to an imbalance account
(\f[CR]equity:imbalance\f[R] by default) which make the entry balance
exactly (as if you had added an amountless posting to that account).
Eg:
.IP
.EX
$ hledger print \-\-infer\-imbalance
2024\-01\-30 currency exchange
assets:usd \-19110.17 USD \(at 0.869050 CHF
assets:chf 16607.69 CHF
equity:imbalance 0.0032385 CHF
.EE
.PP
This doesn\(aqt change which entries are accepted.
But totals at cost are now exactly zero, and the accumulated imbalance
appears as the balance of \f[CR]equity:imbalance\f[R].
Eg after three of the currency exchange entries:
.IP
.EX
$ hledger bal \-B \-\-infer\-imbalance
49823.07 CHF assets:chf
\-49823.08 CHF assets:usd
0.01 CHF equity:imbalance
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
The imbalance postings\(aq amounts are usually smaller than the display
precision, so to see them individually, increase the display precision.
Eg:
.IP
.EX
$ hledger areg equity:imbalance \-\-infer\-imbalance \-c \(aqCHF 1.0000000\(aq
Transactions in equity:imbalance and subaccounts:
2024\-01\-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0032385
2024\-01\-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0064770
2024\-01\-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0097155
.EE
.PP
Some notes:
.IP \(bu 2
The imbalance postings have a hidden \f[CR]_imbalance\-posting\f[R] tag
(shown by \f[CR]\-\-verbose\-tags\f[R]), so they can also be matched
with \f[CR]tag:imbalance\-posting\f[R].
.IP \(bu 2
To use a different account, declare it with the
\f[CR]M\f[R]/\f[CR]Imbalance\f[R] account type (the first one declared
is used, if there are several).
Imbalance accounts, including \f[CR]equity:imbalance\f[R], can be
matched with \f[CR]type:M\f[R].
.IP \(bu 2
With \f[CR]\-\-infer\-equity\f[R] as well, the generated equity
conversion postings use the exact cost amounts, so every commodity
balances exactly.
.IP \(bu 2
No imbalance posting is generated if its amount would display as zero
(at 8 decimal places, for a repeating decimal).
This ignores the tiny leftovers of hledger\(aqs own division (see Amount
arithmetic).
.IP \(bu 2
The imbalance account need not be declared, even in strict mode.
.IP \(bu 2
To list the entries with an imbalance, without generating postings, you
can use \f[CR]hledger print not:change:0\f[R] (see change: query).
(This also lists entries with unbalanced virtual postings;
\f[CR]not:change:0 change:\(aq<1\(aq\f[R] would list only the small
imbalances.)
.IP \(bu 2
If you use this flag with \f[CR]import\f[R], the imbalance postings will
be added to your journal too.
.SS Avoiding imbalances
You can avoid imbalances by writing exact entries.
Any of these will do:
.IP \(bu 2
Use a total cost (\f[CR]\(at\(at\f[R]) instead of a unit cost
(\f[CR]\(at\f[R]) when the unit cost would be rounded.
Total costs are converted exactly.
Eg \f[CR]\-19110.17 USD \(at\(at 16607.69 CHF\f[R].
.IP \(bu 2
Write the unit cost with enough decimal places to be exact, when
possible.
.IP \(bu 2
Add a posting to absorb the imbalance, eg to an
\f[CR]expenses:rounding\f[R] account.
If you leave its amount blank, hledger will calculate it exactly.
.SS Transaction balancing before 1.50
hledger versions before 1.50 used the commodity\(aqs display precision
as the balancing precision, instead of the precision in the entry.
This masked larger imbalances, and made balancing depend on display
settings (see issue #2402).
So some journal entries (or CSV rules) that worked with hledger <1.50
are now rejected with an \(dqunbalanced transaction\(dq error.
If you hit this, you can:
.IP \(bu 2
restore the old behaviour, by adding
\f[CR]\-\-txn\-tolerance=display\f[R] (formerly
\f[CR]\-\-txn\-balancing=old\f[R]) to the command or to your
\f[CR]\(ti/.hledger.conf\f[R] file.
This lets you keep using old journals unchanged.
.IP \(bu 2
or fix the problem entries (recommended), in one of these ways:
.RS 2
.IP "1." 3
make cost amounts more precise (add more or better decimal digits)
.IP "2." 3
or make non\-cost amounts less precise (remove unnecessary decimal
digits that are raising the precision)
.IP "3." 3
or add a posting to absorb the imbalance, as described above.
.RE
.SH Amount formatting
.SS Commodity display style
For the amounts in each commodity, hledger chooses a consistent display
style (symbol placement, decimal mark and digit group marks, number of
decimal digits) to use in most reports.
This is inferred as follows:
.PP
First, if there\(aqs a \f[CR]D\f[R] directive declaring a default
commodity, that commodity symbol and amount format is applied to all
no\-symbol amounts in the journal.
.PP
Then each commodity\(aqs display style is determined from its
\f[CR]commodity\f[R] directive.
We recommend always declaring commodities with \f[CR]commodity\f[R]
directives, since they help ensure consistent display styles and
precisions, and bring other benefits such as error checking for
commodity symbols.
Here\(aqs an example:
.IP
.EX
# Set display styles (and decimal marks, for parsing, if there is no decimal\-mark directive)
# for the $, EUR, INR and no\-symbol commodities:
commodity $1,000.00
commodity EUR 1.000,00
commodity INR 9,99,99,999.00
commodity 1 000 000.9455
.EE
.PP
But for convenience, if a \f[CR]commodity\f[R] directive is not present,
hledger infers a commodity\(aqs display styles from its amounts as they
are written in the journal (excluding cost amounts and amounts in
periodic transaction rules or auto posting rules).
It uses
.IP \(bu 2
the symbol placement and decimal mark of the first amount seen
.IP \(bu 2
the digit group marks of the first amount with digit group marks
.IP \(bu 2
and the maximum number of decimal digits seen across all amounts.
.PP
And as fallback if no applicable amounts are found, it would use a
default style, like \f[CR]$1000.00\f[R] (symbol on the left with no
space, period as decimal mark, and two decimal digits).
.PP
Finally, commodity styles can be overridden by the
\f[CR]\-c/\-\-commodity\-style\f[R] command line option, described next.
.PP
.SS Commodity style override
The \f[CR]\-c/\-\-commodity\-style\f[R] option overrides a
commodity\(aqs declared or inferred display style, for the current
command.
Its argument is a sample amount, as in the commodity directive.
Eg, to show dollar amounts with period digit group marks, comma decimal
mark, and one decimal digit:
.IP
.EX
$ hledger print \-c \(aq$1.000,0\(aq
.EE
.PP
Some things to note:
.IP \(bu 2
The option can be repeated, to set the display style of several
commodities.
.IP \(bu 2
Omitting the commodity symbol sets the style of just the no\-symbol
commodity, not of all commodities.
.IP \(bu 2
For cost amounts, and amounts displayed by the \f[CR]print\f[R] command,
it affects only the symbol placement and digit group/decimal marks;
those amounts are always displayed with all of their decimal digits.
.IP \(bu 2
In some cases hledger will adjust number formatting to improve
parseability, eg by adding trailing decimal marks when needed.
.PP
.SS Display rounding
Amounts are stored internally as decimal numbers with up to 255 decimal
places (see Amount arithmetic).
They are displayed with their original journal precisions by print and
print\-like reports, and rounded to their display precision (the number
of decimal digits specified by the commodity display style) by other
reports.
When rounding, hledger uses banker\(aqs rounding (it rounds to the
nearest even digit).
So eg 0.5 displayed with zero decimal digits appears as \(dq0\(dq.
.SS Trailing decimal marks
If you\(aqre wondering why your \f[CR]print\f[R] report sometimes shows
trailing decimal marks, with no decimal digits; it does this when
showing amounts that have digit group marks but no decimal digits, to
disambiguate them and allow them to be re\-parsed reliably (see Decimal
marks).
Eg:
.IP
.EX
commodity $1,000.00
2023\-01\-02
(a) $1000
.EE
.IP
.EX
$ hledger print
2023\-01\-02
(a) $1,000.
.EE
.PP
You can avoid this by disabling digit group marks, eg temporarily with
\-c/\-\-commodity:
.IP
.EX
$ hledger print \-c \(aq$1000.00\(aq
2023\-01\-02
(a) $1000
.EE
.PP
or by forcing print to show some decimal digits, with \-\-round:
.IP
.EX
$ hledger print \-c \(aq$1,000.00\(aq \-\-round=soft
2023\-01\-02
(a) $1,000.00
.EE
.SS Amount parseability
More generally, hledger output falls into three rough categories, which
format amounts a little bit differently to suit different consumers:
.PP
\f[B]1.
\(dqhledger\-readable output\(dq \- should be readable by hledger (and
by humans)\f[R]
.IP \(bu 2
This is produced by reports that show full journal entries:
\f[CR]print\f[R], \f[CR]import\f[R], \f[CR]close\f[R],
\f[CR]rewrite\f[R] etc.
.IP \(bu 2
It shows amounts with their original journal precisions, which may not
be consistent from one amount to the next.
.IP \(bu 2
It adds a trailing decimal mark when needed to avoid showing ambiguous
amounts.
.IP \(bu 2
It can be parsed reliably (by hledger and ledger2beancount at least, but
perhaps not by Ledger..)
.PP
\f[B]2.
\(dqhuman\-readable output\(dq \- usually for humans\f[R]
.IP \(bu 2
This is produced by all other reports.
.IP \(bu 2
It shows amounts with standard display precisions, which will be
consistent within each commodity.
.IP \(bu 2
It shows ambiguous amounts unmodified.
.IP \(bu 2
It can be parsed reliably in the context of a known report (when you
know decimals are consistently not being shown, you can assume a single
mark is a digit group mark).
.PP
\f[B]3.
\(dqmachine\-readable output\(dq \- usually for other software\f[R]
.IP \(bu 2
This is produced by all reports when an output format like
\f[CR]csv\f[R], \f[CR]tsv\f[R], \f[CR]json\f[R], or \f[CR]sql\f[R] is
selected.
.IP \(bu 2
It shows amounts as 1 or 2 do, but without digit group marks.
.IP \(bu 2
It can be parsed reliably (if needed, the decimal mark can be changed
with \-c/\-\-commodity\-style).
.SH Cost reporting
In some transactions \- for example a currency conversion, or a purchase
or sale of stock \- one commodity is exchanged for another.
In these transactions there is a conversion rate, also called the cost
(when buying) or selling price (when selling).
(In hledger docs we just say \(dqcost\(dq generically for convenience.)
With the \f[CR]\-B/\-\-cost\f[R] flag, hledger can show amounts \(dqat
cost\(dq, converted to the cost\(aqs commodity.
.SS Recording costs
We\(aqll explore several ways of recording transactions involving costs.
These are also compared at Currency conversion > Four ways to record a
conversion, compared.
.PP
Costs can be recorded explicitly in the journal, using the
\f[CR]\(at UNITCOST\f[R] or \f[CR]\(at\(at TOTALCOST\f[R] notation
described in Journal > Costs:
.PP
\f[B]Variant 1\f[R]
.IP
.EX
2022\-01\-01
assets:dollars $\-135
assets:euros €100 \(at $1.35 ; $1.35 per euro (unit cost)
.EE
.PP
\f[B]Variant 2\f[R]
.IP
.EX
2022\-01\-01
assets:dollars $\-135
assets:euros €100 \(at\(at $135 ; $135 total cost
.EE
.PP
Typically, writing the unit cost (variant 1) is preferable; it can be
more effort, requiring more attention to decimal digits; but it reveals
the per\-unit cost basis, and makes stock sales easier.
.PP
Costs can also be left implicit, and hledger will infer the cost that is
consistent with a balanced transaction:
.PP
\f[B]Variant 3\f[R]
.IP
.EX
2022\-01\-01
assets:dollars $\-135
assets:euros €100
.EE
.PP
Here, hledger will attach a \f[CR]\(at\(at €100\f[R] cost to the first
amount (you can see it with \f[CR]hledger print \-x\f[R]).
This form looks convenient, but there are downsides:
.IP \(bu 2
It sacrifices some error checking.
For example, if you accidentally wrote €10 instead of €100, hledger
would not be able to detect the mistake.
.IP \(bu 2
It is sensitive to the order of postings \- if they were reversed, a
different entry would be inferred and reports would be different.
.IP \(bu 2
The per\-unit cost basis is not easy to read.
.PP
So generally this kind of entry is not recommended.
You can make sure you have none of these by using \f[CR]\-s\f[R] (strict
mode), or by running \f[CR]hledger check balanced\f[R].
.SS Reporting at cost
Now when you add the \f[CR]\-B\f[R]/\f[CR]\-\-cost\f[R] flag to reports
(\(dqB\(dq is from Ledger\(aqs \-B/\-\-basis/\-\-cost flag), any amounts
which have been annotated with costs will be converted to their
cost\(aqs commodity (in the report output).
Ie they will be displayed \(dqat cost\(dq or \(dqat sale price\(dq.
.PP
For lot postings, which carry a cost basis, \f[CR]\-B\f[R] converts to
the cost basis instead: a disposal shows what the disposed units cost,
not what they sold for, consistent with how such entries balance, so eg
a lot account\(aqs cost balance is the cost of the units still held (and
zero once they are all sold), and \f[CR]bse \-B\f[R] balances.
To see transacted amounts (proceeds) instead, use
\f[CR]\-\-value=transacted\f[R].
.PP
Some things to note:
.IP \(bu 2
Costs are attached to specific posting amounts in specific transactions,
and once recorded they do not change.
This contrasts with market prices, which are ambient and fluctuating.
.IP \(bu 2
Conversion to cost is performed before conversion to market value
(described below).
.IP \(bu 2
A total at cost can be slightly off zero where you might expect zero (eg
a few cents in \f[CR]bse \-B\f[R]), because hledger accepts entries
whose costs were rounded; see Accumulated imbalances.
.SS Equity conversion postings
There is a problem with the entries above \- they are not conventional
Double Entry Bookkeeping (DEB) notation, and because of the
\(dqmagical\(dq transformation of one commodity into another, they cause
an imbalance in the Accounting Equation.
This shows up as a non\-zero grand total in balance reports like
\f[CR]hledger bse\f[R].
.PP
Most hledger users use cost notation and don\(aqt use equity postings;
for them this imbalance doesn\(aqt matter in practice and can safely be
ignored.
But if you\(aqd like to learn more, keep reading.
.PP
Conventional DEB uses an extra pair of equity postings to balance the
transaction.
Of course you can do this in hledger as well:
.PP
\f[B]Variant 4\f[R]
.IP
.EX
2022\-01\-01
assets:dollars $\-135
assets:euros €100
equity:conversion $135
equity:conversion €\-100
.EE
.PP
Now the transaction is perfectly balanced according to standard DEB, and
\f[CR]hledger bse\f[R]\(aqs total will not be disrupted.
It also translates easily to any other double entry accounting system.
.PP
And, hledger can still infer the cost for cost reporting, but it\(aqs
not done by default \- you must add the \f[CR]\-\-infer\-costs\f[R] flag
like so:
.IP
.EX
$ hledger print \-\-infer\-costs
2022\-01\-01 one hundred euros purchased at $1.35 each
assets:dollars $\-135 \(at\(at €100
assets:euros €100
equity:conversion $135
equity:conversion €\-100
.EE
.IP
.EX
$ hledger bal \-\-infer\-costs \-B
€\-100 assets:dollars
€100 assets:euros
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
0
.EE
.PP
Here are some downsides of this kind of entry:
.IP \(bu 2
The per\-unit cost basis is not easy to read.
.IP \(bu 2
Instead of \f[CR]\-B\f[R] you must remember to type
\f[CR]\-B \-\-infer\-costs\f[R].
.IP \(bu 2
\f[CR]\-\-infer\-costs\f[R] works only where hledger can identify the
two equity:conversion postings and match them up with the two
non\-equity postings.
So writing the journal entry in a particular format becomes more
important.
More on this below.
.SS Inferring equity conversion postings
Can we go in the other direction ?
Yes, if you have transactions written with the \(at/\(at\(at cost
notation, hledger can infer the missing equity postings, if you add the
\f[CR]\-\-infer\-equity\f[R] flag.
Eg:
.IP
.EX
2022\-01\-01
assets:dollars \-$135
assets:euros €100 \(at $1.35
.EE
.IP
.EX
$ hledger print \-\-infer\-equity
2022\-01\-01
assets:dollars $\-135
assets:euros €100 \(at $1.35
equity:conversion:$\-€:€ €\-100
equity:conversion:$\-€:$ $135.00
.EE
.PP
The equity account names will be \(dqequity:conversion:A\-B:A\(dq and
\(dqequity:conversion:A\-B:B\(dq where A is the alphabetically first
commodity symbol.
You can customise the \(dqequity:conversion\(dq part by declaring an
account with the \f[CR]V\f[R]/\f[CR]Conversion\f[R] account type (the
first\-declared one, if there are several; or if none is declared, the
alphabetically first account whose type is inferred as V, such as
\f[CR]equity:trading\f[R], is used).
.PP
For a lot disposal, the conversion postings record the units sold at
their cost basis, not at the sale price, so that the entry (and your
balance sheet) still sums to zero; the difference between the two is the
gain posting.
Eg:
.IP
.EX
commodity AAPL ; lots:
2026\-01\-02 buy
assets:stock 10 AAPL \(at\(at $1000
assets:cash
2026\-01\-03 sell
assets:stock \-4 AAPL \(at\(at $600
assets:cash $600
.EE
.IP
.EX
$ hledger print \-\-infer\-equity desc:sell
2026\-01\-03 sell
assets:stock \-4 AAPL {2026\-01\-02, $100} \(at\(at $600
equity:conversion:$\-AAPL:AAPL 4 AAPL
equity:conversion:$\-AAPL:$ $\-400
assets:cash $600
revenues:gain $\-200
.EE
.PP
If you write such an entry yourself, write the conversion postings at
cost basis like this, and keep the transacted cost
(\f[CR]\(at\f[R]/\f[CR]\(at\(at\f[R]) on the disposal posting, since the
gain is calculated from it.
.PP
The generated equity conversion accounts need not be declared, even in
strict mode.
(And unlike normal postings, generated equity postings do not inherit
tags from account declarations.)
.SS Combining costs and equity conversion postings
Finally, you can use both the \(at/\(at\(at cost notation and equity
postings at the same time.
This in theory gives the best of all worlds \- preserving the accounting
equation, revealing the per\-unit cost basis, and providing more
flexibility in how you write the entry:
.PP
\f[B]Variant 5\f[R]
.IP
.EX
2022\-01\-01 one hundred euros purchased at $1.35 each
assets:dollars $\-135
equity:conversion $135
equity:conversion €\-100
assets:euros €100 \(at $1.35
.EE
.PP
All the other variants above can (usually) be rewritten to this final
form with:
.IP
.EX
$ hledger print \-x \-\-infer\-costs \-\-infer\-equity
.EE
.PP
Or you can enable both flags always, eg in your config file, and your
reports will have the advantages of both.
.PP
Downsides:
.IP \(bu 2
The precise format of the journal entry becomes more important.
If hledger can\(aqt detect and match up the cost and equity postings, it
will give a transaction balancing error.
.IP \(bu 2
The add command does not yet accept this kind of entry (#2056).
.IP \(bu 2
This is the most verbose form.
.SS Requirements for detecting equity conversion postings
\f[CR]\-\-infer\-costs\f[R] has certain requirements (unlike
\f[CR]\-\-infer\-equity\f[R], which always works).
It will infer costs only in transactions with:
.IP \(bu 2
Two non\-equity postings, in different commodities.
If one of them is lotful, the cost will be added to that one; otherwise
it will be added to the first (top) one.
.IP \(bu 2
Two postings to equity conversion accounts, next to one another, which
balance the two non\-equity postings.
This balancing is checked to the same precision (number of decimal
places) used in the conversion posting\(aqs amount.
Equity conversion accounts are:
.RS 2
.IP \(bu 2
any accounts declared with account type
\f[CR]V\f[R]/\f[CR]Conversion\f[R], or their subaccounts
.IP \(bu 2
otherwise, accounts named \f[CR]equity:conversion\f[R],
\f[CR]equity:trade\f[R], or \f[CR]equity:trading\f[R], or their
subaccounts.
.RE
.PP
And multiple such four\-posting groups can coexist within a single
transaction.
When \f[CR]\-\-infer\-costs\f[R] fails, it does not infer a cost in that
transaction, and does not raise an error (ie, it infers costs where it
can).
.PP
Reading variant 5 journal entries, combining cost notation and equity
postings, has all the same requirements.
When reading such an entry fails, hledger raises an \(dqunbalanced
transaction\(dq error.
For a lot disposal, the conversion postings may balance the
disposal\(aqs cost basis instead of its transacted cost, as described
above.
.PP
.SH Value reporting
hledger can also show amounts \(dqat market value\(dq, converted to some
other commodity using the market price or conversion rate on a certain
date.
.PP
This is controlled by the \f[CR]\-\-value=TYPE[,COMMODITY]\f[R] option.
We also provide simpler \f[CR]\-V\f[R] and \f[CR]\-X COMMODITY\f[R]
aliases for this, which are often sufficient.
The market prices are declared with a special \f[CR]P\f[R] directive,
and/or they can be inferred from the costs recorded in transactions, by
using the \f[CR]\-\-infer\-market\-prices\f[R] flag.
.SS \-X: Value in specified commodity
The \f[CR]\-X COMM\f[R] (or \f[CR]\-\-exchange=COMM\f[R]) option
converts amounts to their market value in the specified commodity, using
the market prices in effect on the \f[I]valuation date(s)\f[R], if any.
(More on these in a minute.)
.PP
Use this when you want to (eg) show everything in your base currency as
far as possible.
(Commodities for which no conversion rate can be found, will not be
converted.)
.PP
COMM should be the commodity symbol exactly as written in the
journal\(aqs amounts or market prices (eg \f[CR]$\f[R], not
\f[CR]USD\f[R], if the journal uses \f[CR]$\f[R]); ISO currency codes
are not matched to symbols.
If no conversion price to COMM can be found, a warning is printed,
suggesting an equivalent journal commodity if one exists.
Remember to quote special shell characters, if needed.
Some examples:
.IP \(bu 2
\f[CR]\-X€\f[R]
.IP \(bu 2
\f[CR]\-X$\f[R] (nothing after $, no quoting needed)
.IP \(bu 2
\f[CR]\-X CNY\f[R] (the space after \-X is optional)
.IP \(bu 2
\f[CR]\-X \(aqred apples\(aq\f[R]
.IP \(bu 2
\f[CR]\-X \(aqr&r\(aq\f[R]
.SS \-V: Value in default commodity(s)
The \f[CR]\-V/\-\-market\f[R] flag is a variant of \f[CR]\-X\f[R] where
you don\(aqt have to specify COMM.
Instead it tries to guess a \f[I]default valuation commodity\f[R] for
each original commodity, based on the market prices in effect on the
valuation date(s).
.PP
\f[CR]\-V\f[R] can often be a convenient shortcut for
\f[CR]\-X MYCURRENCY\f[R], but not always; depending on your data it
could guess multiple valuation commodities.
Usually you want to convert to a single commodity, so it\(aqs better to
use \f[CR]\-X\f[R], unless you\(aqre sure \f[CR]\-V\f[R] is doing what
you want.
.SS Valuation date
Market prices can change from day to day.
hledger will use the prices on a particular valuation date (or on more
than one date).
By default hledger uses \(dqend\(dq dates for valuation.
More specifically:
.IP \(bu 2
For single period reports (including normal print and register reports):
.RS 2
.IP \(bu 2
If an explicit report end date is specified, that is used.
.IP \(bu 2
Otherwise the latest transaction date or non\-future P directive date is
used.
.RE
.IP \(bu 2
For multiperiod reports, each period is valued on its last day.
.PP
This can be customised with the \-\-value option described below, which
can select either \(dqthen\(dq, \(dqend\(dq, \(dqnow\(dq, or
\(dqcustom\(dq dates.
.SS Finding market price
To convert a commodity A to its market value in another commodity B,
hledger looks for a suitable market price (exchange rate) as follows, in
this order of preference:
.IP "1." 3
A \f[I]declared market price\f[R] or \f[I]inferred market price\f[R]:
A\(aqs latest market price in B on or before the valuation date as
declared by a P directive, or (with the
\f[CR]\-\-infer\-market\-prices\f[R] flag) inferred from costs.
.IP "2." 3
A \f[I]reverse market price\f[R]: the inverse of a declared or inferred
market price from B to A.
.IP "3." 3
A \f[I]forward chain of market prices\f[R]: a synthetic price formed by
combining the shortest chain of \(dqforward\(dq (only 1 above) market
prices, leading from A to B.
.IP "4." 3
\f[I]Any chain of market prices\f[R]: a chain of any market prices,
including both forward and reverse prices (1 and 2 above), leading from
A to B.
.IP "5." 3
\f[I]Commodity alias rates\f[R]: if none of the above is found, the same
search is repeated, also using commodity aliases as fixed exchange rates
(between a commodity and its alias, when there are no market prices
between them).
This lets you value amounts in an alias declared by another file, or
show amounts in an alias with \f[CR]\-X\f[R], but aliases never change a
conversion that market prices can provide.
To see these rates and where their aliases were declared, use
\f[CR]prices \-\-show\-aliases \-\-locations\f[R];
\f[CR]\-\-debug=2\f[R] output shows when they are tried.
.PP
There is a limit to the length of these price chains; if hledger reaches
that length without finding a complete chain or exhausting all
possibilities, it will give up (with a \(dqgave up\(dq message visible
in \f[CR]\-\-debug=2\f[R] output).
That limit is currently 1000.
.PP
Amounts for which no suitable market price can be found, are not
converted.
.PP
Commodity alias rates are used only for converting, never as a default
valuation commodity for \f[CR]\-V\f[R].
.SS \-\-infer\-market\-prices: market prices from transactions
Normally, market value in hledger is fully controlled by, and requires,
P directives in your journal.
Since adding and updating those can be a chore, and since transactions
usually take place at close to market value, why not use the recorded
costs as additional market prices (as Ledger does) ?
Adding the \f[CR]\-\-infer\-market\-prices\f[R] flag to \f[CR]\-V\f[R],
\f[CR]\-X\f[R] or \f[CR]\-\-value\f[R] enables this.
.PP
So for example, \f[CR]hledger bs \-V \-\-infer\-market\-prices\f[R] will
get market prices both from P directives and from transactions.
If both occur on the same day, the P directive takes precedence.
.PP
There is a downside: value reports can sometimes be affected in
confusing/undesired ways by your journal entries.
If this happens to you, read all of this Value reporting section
carefully, and try adding \f[CR]\-\-debug\f[R] or \f[CR]\-\-debug=2\f[R]
to troubleshoot.
.PP
\f[CR]\-\-infer\-market\-prices\f[R] can infer market prices from:
.IP \(bu 2
multicommodity transactions with explicit prices
(\f[CR]\(at\f[R]/\f[CR]\(at\(at\f[R])
.IP \(bu 2
multicommodity transactions with implicit prices (no \f[CR]\(at\f[R],
two commodities, unbalanced).
(With these, the order of postings matters.
\f[CR]hledger print \-x\f[R] can be useful for troubleshooting.)
.IP \(bu 2
multicommodity transactions with equity postings, if cost is inferred
with \f[CR]\-\-infer\-costs\f[R].
.PP
There is a limitation (bug) currently: when a valuation commodity is not
specified, prices inferred with \f[CR]\-\-infer\-market\-prices\f[R] do
not help select a default valuation commodity, as \f[CR]P\f[R] prices
would.
So conversion might not happen because no valuation commodity was
detected (\f[CR]\-\-debug=2\f[R] will show this).
To be safe, specify the valuation commmodity, eg:
.IP \(bu 2
\f[CR]\-X EUR \-\-infer\-market\-prices\f[R], not
\f[CR]\-V \-\-infer\-market\-prices\f[R]
.IP \(bu 2
\f[CR]\-\-value=then,EUR \-\-infer\-market\-prices\f[R], not
\f[CR]\-\-value=then \-\-infer\-market\-prices\f[R]
.PP
Signed costs and market prices can be confusing.
For reference, here is the current behaviour.
(If you think it should work differently, see #1870.)
.IP
.EX
2022\-01\-01 Positive Unit prices
a A 1
b B \-1 \(at A 1
2022\-01\-01 Positive Total prices
a A 1
b B \-1 \(at\(at A 1
2022\-01\-02 Negative unit prices
a A 1
b B 1 \(at A \-1
2022\-01\-02 Negative total prices
a A 1
b B 1 \(at\(at A \-1
2022\-01\-03 Double Negative unit prices
a A \-1
b B \-1 \(at A \-1
2022\-01\-03 Double Negative total prices
a A \-1
b B \-1 \(at\(at A \-1
.EE
.PP
All of the transactions above are considered balanced (and on each day,
the two transactions are considered equivalent).
Here are the market prices inferred for B:
.IP
.EX
$ hledger \-f\- \-\-infer\-market\-prices prices
P 2022\-01\-01 B A 1
P 2022\-01\-01 B A 1.0
P 2022\-01\-02 B A \-1
P 2022\-01\-02 B A \-1.0
P 2022\-01\-03 B A \-1
P 2022\-01\-03 B A \-1.0
.EE
.SS Valuation commodity
\f[B]When you specify a valuation commodity (\f[CB]\-X COMM\f[B] or
\f[CB]\-\-value TYPE,COMM\f[B]):\f[R]
.PD 0
.P
.PD
hledger will convert all amounts to COMM, wherever it can find a
suitable market price (including by reversing or chaining prices).
.PP
\f[B]When you leave the valuation commodity unspecified (\f[CB]\-V\f[B]
or \f[CB]\-\-value TYPE\f[B]):\f[R]
.PD 0
.P
.PD
For each commodity A, hledger picks a default valuation commodity as
follows, in this order of preference:
.IP "1." 3
The price commodity from the latest P\-declared market price for A on or
before valuation date.
.IP "2." 3
The price commodity from the latest P\-declared market price for A on
any date.
(Allows conversion to proceed when there are inferred prices before the
valuation date.)
.IP "3." 3
If there are no P directives at all (any commodity or date) and the
\f[CR]\-\-infer\-market\-prices\f[R] flag is used: the price commodity
from the latest transaction\-inferred price for A on or before valuation
date.
.PP
This means:
.IP \(bu 2
If you have P directives, they determine which commodities
\f[CR]\-V\f[R] will convert, and to what.
.IP \(bu 2
If you have no P directives, and use the
\f[CR]\-\-infer\-market\-prices\f[R] flag, costs determine it.
.PP
Amounts for which no valuation commodity can be found are not converted.
.SS \-\-value: Flexible valuation
\f[CR]\-V\f[R] and \f[CR]\-X\f[R] are special cases of the more general
\f[CR]\-\-value\f[R] option:
.IP
.EX
\-\-value=TYPE[,COMM] TYPE is then, end, now, YYYY\-MM\-DD, cost or transacted.
COMM is an optional commodity symbol.
Shows amounts converted to:
\- default valuation commodity (or COMM) using market prices at posting dates
\- default valuation commodity (or COMM) using market prices at period end(s)
\- default valuation commodity (or COMM) using current market prices
\- default valuation commodity (or COMM) using market prices at some date
\- cost basis, or else transacted cost (like \-B)
\- transacted cost only
.EE
.PP
The TYPE part selects cost or value and valuation date:
.TP
\f[CR]\-\-value=then\f[R]
Convert amounts to their value in the default valuation commodity, using
market prices on each posting\(aqs date.
.TP
\f[CR]\-\-value=end\f[R]
Convert amounts to their value in the default valuation commodity, using
market prices on the last day of the report period (or if unspecified,
the journal\(aqs end date); or in multiperiod reports, market prices on
the last day of each subperiod.
.TP
\f[CR]\-\-value=now\f[R]
Convert amounts to their value in the default valuation commodity using
current market prices (as of when report is generated).
.TP
\f[CR]\-\-value=YYYY\-MM\-DD\f[R]
Convert amounts to their value in the default valuation commodity using
market prices on this date.
.TP
\f[CR]\-\-value=cost\f[R]
Convert amounts to their cost basis where they have one (lot postings),
otherwise to their transacted cost.
Same as \f[CR]\-B\f[R]/\f[CR]\-\-cost\f[R]; see Reporting at cost.
.TP
\f[CR]\-\-value=transacted\f[R]
Convert amounts to their transacted cost or sale amount
(\f[CR]\(at\f[R]/\f[CR]\(at\(at\f[R]), ignoring any cost basis.
This is \f[CR]\-B\f[R]\(aqs behaviour for non\-lot postings, and shows
proceeds rather than cost for lot disposals.
.PP
To select a different valuation commodity, add the optional
\f[CR],COMM\f[R] part: a comma, then the target commodity\(aqs symbol.
Eg: \f[B]\f[CB]\-\-value=now,EUR\f[B]\f[R].
hledger will do its best to convert amounts to this commodity, deducing
market prices as described above.
.PP
The symbol may be written in double quotes, as in a journal.
To select the no\-symbol commodity, write it as \f[CR]\(dq\(dq\f[R], or
leave the symbol empty:
\f[B]\f[CB]\-\-value=now,\(aq\(dq\(dq\(aq\f[B]\f[R],
\f[B]\f[CB]\-\-value=now,\f[B]\f[R],
\f[B]\f[CB]\-X \(aq\(dq\(dq\(aq\f[B]\f[R] and
\f[B]\f[CB]\-X \(aq\(aq\f[B]\f[R] all work.
.SS Valuation examples
Here are some quick examples of \f[CR]\-V\f[R]:
.IP
.EX
; one euro is worth this many dollars from nov 1
P 2016/11/01 € $1.10
; purchase some euros on nov 3
2016/11/3
assets:euros €100
assets:checking
; the euro is worth fewer dollars by dec 21
P 2016/12/21 € $1.03
.EE
.PP
How many euros do I have ?
.IP
.EX
$ hledger \-f t.j bal \-N euros
€100 assets:euros
.EE
.PP
What are they worth at end of nov 3 ?
.IP
.EX
$ hledger \-f t.j bal \-N euros \-V \-e 2016/11/4
$110.00 assets:euros
.EE
.PP
What are they worth after 2016/12/21 ?
(no report end date specified, defaults to today)
.IP
.EX
$ hledger \-f t.j bal \-N euros \-V
$103.00 assets:euros
.EE
.PP
Here are some examples showing the effect of \f[CR]\-\-value\f[R], as
seen with \f[CR]print\f[R]:
.IP
.EX
P 2000\-01\-01 A 1 B
P 2000\-02\-01 A 2 B
P 2000\-03\-01 A 3 B
P 2000\-04\-01 A 4 B
2000\-01\-01
(a) 1 A \(at 5 B
2000\-02\-01
(a) 1 A \(at 6 B
2000\-03\-01
(a) 1 A \(at 7 B
.EE
.PP
Show the cost of each posting:
.IP
.EX
$ hledger \-f\- print \-\-cost
2000\-01\-01
(a) 5 B
2000\-02\-01
(a) 6 B
2000\-03\-01
(a) 7 B
.EE
.PP
Show the value as of the last day of the report period (2000\-02\-29):
.IP
.EX
$ hledger \-f\- print \-\-value=end date:2000/01\-2000/03
2000\-01\-01
(a) 2 B
2000\-02\-01
(a) 2 B
.EE
.PP
With no report period specified, the latest transaction date or price
date is used as valuation date (2000\-04\-01):
.IP
.EX
$ hledger \-f\- print \-\-value=end
2000\-01\-01
(a) 3 B
2000\-02\-01
(a) 3 B
2000\-03\-01
(a) 3 B
.EE
.PP
The value today is the same (the 2000\-04\-01 price is still in effect):
.IP
.EX
$ hledger \-f\- print \-\-value=now
2000\-01\-01
(a) 4 B
2000\-02\-01
(a) 4 B
2000\-03\-01
(a) 4 B
.EE
.PP
Show the value on 2000/01/15:
.IP
.EX
$ hledger \-f\- print \-\-value=2000\-01\-15
2000\-01\-01
(a) 1 B
2000\-02\-01
(a) 1 B
2000\-03\-01
(a) 1 B
.EE
.SS Interaction of valuation and queries
When matching postings based on queries in the presence of valuation,
the following happens:
.IP "1." 3
The query is separated into two parts:
.RS 4
.IP "1." 3
the currency (\f[CR]cur:\f[R]) or amount (\f[CR]amt:\f[R]).
.IP "2." 3
all other parts.
.RE
.IP "2." 3
The postings are matched to the currency and amount queries based on
pre\-valued amounts.
.IP "3." 3
Valuation is applied to the postings.
.IP "4." 3
The postings are matched to the other parts of the query based on
post\-valued amounts.
.PP
Related: #1625
.SS Effect of valuation on reports
Here is a reference for how valuation is supposed to affect each part of
hledger\(aqs reports.
It may be useful when troubleshooting.
Related: #329, #1083.
.PP
First, a quick glossary:
.TP
\f[I]cost\f[R]
calculated using price(s) recorded in the transaction(s).
.TP
\f[I]value\f[R]
market value using available market price declarations, or the unchanged
amount if no conversion rate can be found.
.TP
\f[I]report start\f[R]
the first day of the report period specified with \-b or \-p or date:,
otherwise today.
.TP
\f[I]report or journal start\f[R]
the first day of the report period specified with \-b or \-p or date:,
otherwise the earliest transaction date in the journal, otherwise today.
.TP
\f[I]report end\f[R]
the last day of the report period specified with \-e or \-p or date:,
otherwise today.
.TP
\f[I]report or journal end\f[R]
the last day of the report period specified with \-e or \-p or date:,
otherwise the latest transaction date in the journal, otherwise today.
.TP
\f[I]report interval\f[R]
a flag (\-D/\-W/\-M/\-Q/\-Y) or period expression that activates the
report\(aqs multi\-period mode (whether showing one or many subperiods).
.PP
.TS
tab(@);
lw(9.5n) lw(11.8n) lw(12.0n) lw(17.2n) lw(12.0n) lw(7.4n).
T{
Report type
T}@T{
\f[CR]\-B\f[R], \f[CR]\-\-cost\f[R]
T}@T{
\f[CR]\-V\f[R], \f[CR]\-X\f[R]
T}@T{
\f[CR]\-\-value=then\f[R]
T}@T{
\f[CR]\-\-value=end\f[R]
T}@T{
\f[CR]\-\-value=DATE\f[R], \f[CR]\-\-value=now\f[R]
T}
_
T{
\f[B]print\f[R]
T}@T{
T}@T{
T}@T{
T}@T{
T}@T{
T}
T{
posting amounts
T}@T{
cost
T}@T{
value at report end or today
T}@T{
value at posting date
T}@T{
value at report or journal end
T}@T{
value at DATE/today
T}
T{
balance assertions/assignments
T}@T{
unchanged
T}@T{
unchanged
T}@T{
unchanged
T}@T{
unchanged
T}@T{
unchanged
T}
T{
T}@T{
T}@T{
T}@T{
T}@T{
T}@T{
T}
T{
\f[B]register\f[R]
T}@T{
T}@T{
T}@T{
T}@T{
T}@T{
T}
T{
starting balance (\-H)
T}@T{
cost
T}@T{
value at report or journal end
T}@T{
valued at day each historical posting was made
T}@T{
value at report or journal end
T}@T{
value at DATE/today
T}
T{
starting balance (\-H) with report interval
T}@T{
cost
T}@T{
value at day before report or journal start
T}@T{
valued at day each historical posting was made
T}@T{
value at day before report or journal start
T}@T{
value at DATE/today
T}
T{
posting amounts
T}@T{
cost
T}@T{
value at report or journal end
T}@T{
value at posting date
T}@T{
value at report or journal end
T}@T{
value at DATE/today
T}
T{
summary posting amounts with report interval
T}@T{
summarised cost
T}@T{
value at period ends
T}@T{
sum of postings in interval, valued at interval start
T}@T{
value at period ends
T}@T{
value at DATE/today
T}
T{
running total/average
T}@T{
sum/average of displayed values
T}@T{
sum/average of displayed values
T}@T{
sum/average of displayed values
T}@T{
sum/average of displayed values
T}@T{
sum/average of displayed values
T}
T{
T}@T{
T}@T{
T}@T{
T}@T{
T}@T{
T}
T{
\f[B]balance (bs, bse, cf, is)\f[R]
T}@T{
T}@T{
T}@T{
T}@T{
T}@T{
T}
T{
balance changes
T}@T{
sums of costs
T}@T{
value at report end or today of sums of postings
T}@T{
value at posting date
T}@T{
value at report or journal end of sums of postings
T}@T{
value at DATE/today of sums of postings
T}
T{
budget amounts (\-\-budget)
T}@T{
like balance changes
T}@T{
like balance changes
T}@T{
like balance changes
T}@T{
like balances
T}@T{
like balance changes
T}
T{
grand total
T}@T{
sum of displayed values
T}@T{
sum of displayed values
T}@T{
sum of displayed valued
T}@T{
sum of displayed values
T}@T{
sum of displayed values
T}
T{
T}@T{
T}@T{
T}@T{
T}@T{
T}@T{
T}
T{
\f[B]balance (bs, bse, cf, is) with report interval\f[R]
T}@T{
T}@T{
T}@T{
T}@T{
T}@T{
T}
T{
starting balances (\-H)
T}@T{
sums of costs of postings before report start
T}@T{
value at report start of sums of all postings before report start
T}@T{
sums of values of postings before report start at respective posting
dates
T}@T{
value at report start of sums of all postings before report start
T}@T{
sums of postings before report start
T}
T{
balance changes (bal, is, bs \-\-change, cf \-\-change)
T}@T{
sums of costs of postings in period
T}@T{
same as \-\-value=end
T}@T{
sums of values of postings in period at respective posting dates
T}@T{
balance change in each period, valued at period ends
T}@T{
value at DATE/today of sums of postings
T}
T{
end balances (bal \-H, is \-\-H, bs, cf)
T}@T{
sums of costs of postings from before report start to period end
T}@T{
same as \-\-value=end
T}@T{
sums of values of postings from before period start to period end at
respective posting dates
T}@T{
period end balances, valued at period ends
T}@T{
value at DATE/today of sums of postings
T}
T{
budget amounts (\-\-budget)
T}@T{
like balance changes/end balances
T}@T{
like balance changes/end balances
T}@T{
like balance changes/end balances
T}@T{
like balances
T}@T{
like balance changes/end balances
T}
T{
row totals, row averages (\-T, \-A)
T}@T{
sums, averages of displayed values
T}@T{
sums, averages of displayed values
T}@T{
sums, averages of displayed values
T}@T{
sums, averages of displayed values
T}@T{
sums, averages of displayed values
T}
T{
column totals
T}@T{
sums of displayed values
T}@T{
sums of displayed values
T}@T{
sums of displayed values
T}@T{
sums of displayed values
T}@T{
sums of displayed values
T}
T{
grand total, grand average
T}@T{
sum, average of column totals
T}@T{
sum, average of column totals
T}@T{
sum, average of column totals
T}@T{
sum, average of column totals
T}@T{
sum, average of column totals
T}
T{
T}@T{
T}@T{
T}@T{
T}@T{
T}@T{
T}
.TE
.PP
\f[CR]\-\-cumulative\f[R] is omitted to save space, it works like
\f[CR]\-H\f[R] but with a zero starting balance.
.PP
.SH Lots and capital gains
When you buy (acquire) some amount of an investment commodity (a lot),
it can be important (depending on your local tax rules) to keep track of
its original cost and acquisition date (cost basis), so that when you
sell (dispose) it, you can calculate capital gains (or losses), and
document how you satisfied the rules about disposal order, short term vs
long term gains, and so on.
.PP
For many kinds of investment, each individual lot has its own cost
basis, which must be tracked even if the lot is reduced, split up, or
transferred.
Also lots may need to be moved and disposed of in a prescribed order.
All this can be very hard to keep track of by hand, so usually it is
done by an investment broker, cryptocurrency exchange, or specialised
tax software.
Now, you can also do it yourself with hledger.
.PP
Automated lot tracking and capital gains reporting is the biggest new
feature of hledger 2.
Lot tracking was first shipped in Ledger, then improved in Beancount;
hledger 2 evolves PTA lot tracking further, making it more powerful and
ergonomic.
You can record lot details explicitly, or let hledger infer them.
hledger checks lot entries; tracks, infers and validates lot movements;
and calculates capital gains when lots are sold.
.PP
Note hledger 2\(aqs lot processing happens only for entries that use lot
notation, or where lots are inferred.
If you have hledger 1 journal files that you want to migrate, or use
with both hledger 1 and hledger 2, see hledger 1 and hledger 2.
.PP
For practical advice on turning on lot tracking in an existing journal,
see Start tracking lots.
For a more technical version of what\(aqs in this manual, see
SPEC\-lots.
.SS First lots example
hledger\(aqs lot tracking does not require much extra work.
Here is a small example, using just the familiar \(at syntax, and new
\f[CR]lots\f[R] tag.
(Several ways to write lot entries below shows the other notations.):
.IP
.EX
commodity AAPL ; lots:
2026\-01\-15 buy
assets:cash \-$500
assets:stocks 10 AAPL \(at $50
2026\-02\-01 sell some
assets:stocks \-5 AAPL \(at $70
assets:cash $350
.EE
.PP
Lot tracking is activated for AAPL by the \f[CR]lots\f[R] tag, so
hledger will
.IP \(bu 2
keep track of each lot that\(aqs acquired (and optionally show them in
reports)
.IP \(bu 2
dispose of lots in the right order (FIFO by default)
.IP \(bu 2
calculate the resulting capital gain, and add the gain posting if
missing
.IP \(bu 2
check for many kinds of error (such as selling more than you have).
.PP
\f[CR]print\f[R] shows the inferred cost basis annotations and gain
posting (so its output can be re\-read even without the
\f[CR]commodity\f[R] directive, if the default cost basis method is
used):
.IP
.EX
$ hledger print
2026\-01\-15 buy
assets:cash $\-500
assets:stocks 10 AAPL {$50} \(at $50
2026\-02\-01 sell some
assets:stocks \-5 AAPL {2026\-01\-15, $50} \(at $70
assets:cash $350
revenues:gain $\-100
.EE
.PP
\f[CR]print\f[R]\(aqs \f[CR]\-a\f[R] flag (short for \f[CR]\-\-all\f[R])
shows maximum detail, including the lots as subaccounts and tags showing
how the entry was analysed:
.IP
.EX
$ hledger print \-a
2026\-01\-15 buy
assets:cash $\-500
assets:stocks:{2026\-01\-15, $50} 10 AAPL {$50} \(at $50 ; ptype: acquire
2026\-02\-01 sell some
assets:stocks:{2026\-01\-15, $50} \-5 AAPL {2026\-01\-15, $50} \(at $70 ; ptype: dispose
assets:cash $350
revenues:gain $\-100 ; ptype: gain, generated\-posting:
.EE
.PP
If anything looks wrong, see Troubleshooting lots below.
.PP
Once you have lot entries, \f[CR]holdings\f[R] will show an overview of
your investments \- units held, per\-unit and total cost and value,
realised and unrealised gain, and XIRR (extended internal rate of
return).
To see all of these, add at least one market price declaration, eg:
.IP
.EX
P 2026\-03\-31 AAPL $72
.EE
.PP
Then:
.IP
.EX
$ hledger holdings \-e 2026\-04\-01
Holdings on 2026\-03\-31
|| Date Age Units Avg cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR
===============++===============================================================================================================
assets:stocks || 2026\-01\-15 75d 5 AAPL $50 $72 $250 $360 100.0% $110 44.0% $100 1865.3%
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 5 AAPL $50 $250 $360 100.0% $110 44.0% $100 1865.3%
.EE
.PP
You can add \f[CR]\-\-lots\f[R] to see the individual lots (this works
with all reports):
.IP
.EX
$ hledger holdings \-e 2026\-04\-01 \-\-lots
Holdings on 2026\-03\-31
|| Date Age Units Unit cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR
=================================++================================================================================================================
assets:stocks:{2026\-01\-15, $50} || 2026\-01\-15 75d 5 AAPL $50 $72 $250 $360 100.0% $110 44.0% $100 1865.3%
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| 5 AAPL $50 $250 $360 100.0% $110 44.0% $100 1865.3%
.EE
.SS Writing lot entries
Lot tracking can be enabled in two ways:
.IP \(bu 2
\f[I]Per posting:\f[R] write explicit cost basis annotations like in
Ledger or Beancount, or explicit lot subaccount names.
These postings will be tracked lotfully.
.IP \(bu 2
\f[I]Per commodity:\f[R] declare the commodity lotful with a
\f[CR]lots\f[R] tag.
All of its postings are tracked lotfully, and the annotations are
inferred for you.
This is convenient, and recommended.
.PP
A posting with any of these is called a lot posting.
.SS Cost basis annotations
Each acquisition of an investment creates a \f[I]lot\f[R], with a
\f[I]cost basis\f[R].
In hledger, a lot\(aqs cost basis has 2\-3 parts:
.IP "1." 3
The nominal acquisition date (required).
Usually this is the date you acquired the lot.
.IP "2." 3
A short text label (optional).
This can be used to distinguish lots acquired on the same date.
.IP "3." 3
The nominal acquisition cost (required).
Usually this is what you paid for it.
.PP
In the journal, we can write \f[I]cost basis annotations\f[R], enclosed
in {} after an amount (the syntax is described in Cost basis), above.
These often mention only part of the cost basis, typically just the cost
(\f[CR]{$50}\f[R]), or nothing at all (\f[CR]{}\f[R]); hledger infers
the rest.
.PP
On an acquisition, the annotation records the new lot\(aqs cost basis.
On a disposal or transfer, it is instead a \f[I]lot selector\f[R],
choosing which existing lot(s) to take from: a full or partial cost
basis, like \f[CR]{2026\-01\-15, $50}\f[R] or \f[CR]{2026\-01\-15}\f[R],
identifies one specific lot, while \f[CR]{}\f[R] (or no annotation) lets
hledger choose, using the cost basis method.
.SS Lotful commodities
A more convenient way to record lot transactions, is to declare
commodities as \f[I]lotful\f[R], by adding a \f[CR]lots\f[R] tag in
their declaration.
Eg:
.IP
.EX
commodity AAPL ; lots:
.EE
.PP
This tells hledger that postings involving these commodities always
involve lots, so it will infer cost basis annotations automatically, and
you won\(aqt need to write them in the journal.
.PP
The \f[CR]lots\f[R] tag can also have a value, selecting the disposal
order (see Cost basis methods); and on account declarations it disables
or customises lot tracking per account, as described in Disabling lot
tracking below.
.SS Lot subaccounts
Internally, hledger tracks each lot in a subaccount, named like the cost
basis.
You don\(aqt need to write these subaccounts in the journal; hledger
infers them automatically.
They are hidden from reports by default, since there can be many lots.
To show them, add the \f[CR]\-\-lots\f[R] flag to any report (the
holdings command is designed for viewing them).
.PP
If you do write a lot subaccount in the journal, it is equivalent to
writing a cost basis annotation on the amount:
.IP
.EX
2026\-01\-15 buy
assets:stocks:{2026\-01\-15, $50} 10 AAPL
assets:cash
.EE
.IP
.EX
$ hledger print
2026\-01\-15 buy
assets:stocks 10 AAPL {2026\-01\-15, $50}
assets:cash
.EE
.PP
A final account name part enclosed in \f[CR]{\f[R] and \f[CR]}\f[R] is
reserved for lot subaccounts, and it must be a valid lot subaccount name
(unless using \f[CR]\-I\f[R] or \f[CR]\-\-ignore\-lots\f[R]).
Lot subaccount names must be complete, including all cost basis parts \-
date, label if any, and cost.
.PP
When strictly checking account names, lot subaccounts are ignored \- you
only need to declare the base account (eg \f[CR]assets:stocks\f[R]), not
the lot subaccounts.
.SS Several ways to write lot entries
Here are two acquisitions and a disposal, written in several ways.
First, with explicit lot subaccounts:
.IP
.EX
2026\-01\-15 buy low
assets:stocks:{2026\-01\-15, $50} 10 AAPL
assets:cash \-$500
2026\-02\-01 buy high
assets:stocks:{2026\-02\-01, $60} 10 AAPL
assets:cash \-$600
2026\-03\-01 sell some
assets:stocks:{2026\-01\-15, $50} \-5 AAPL \(at $70
assets:cash $350
.EE
.PP
Second, with cost basis annotations (here the \f[CR]{}\f[R] selector
means: use the default method, FIFO; and the \f[CR]\(at\f[R] costs could
be omitted, since hledger can infer them from the cash postings):
.IP
.EX
2026\-01\-15 buy low
assets:stocks 10 AAPL {$50}
assets:cash \-$500
2026\-02\-01 buy high
assets:stocks 10 AAPL {$60}
assets:cash \-$600
2026\-03\-01 sell some
assets:stocks \-5 AAPL {} \(at $70
assets:cash $350
.EE
.PP
Third, with a \f[CR]lots\f[R] tag on the commodity, lots are inferred
from the transacted costs:
.IP
.EX
commodity AAPL ; lots:
2026\-01\-15 buy low
assets:stocks 10 AAPL \(at $50
assets:cash \-$500
2026\-02\-01 buy high
assets:stocks 10 AAPL \(at $60
assets:cash \-$600
2026\-03\-01 sell some
assets:stocks \-5 AAPL \(at $70
assets:cash $350
.EE
.PP
All three notations produce the same lots and the same $100 gain; Lot
reports below shows them.
.SS Disabling lot tracking
If you want a commodity tracked lotfully in only some accounts, use
annotations rather than the \f[CR]lots\f[R] tag.
Or if it should be tracked everywhere except certain accounts (eg
tax\-sheltered accounts where cost basis doesn\(aqt matter), use the
\f[CR]lots\f[R] tag, and add a \f[CR]lots: NONE\f[R] tag to those
accounts\(aq declarations to disable lot tracking there:
.IP
.EX
account assets:ira ; lots: NONE
.EE
.PP
Postings in such accounts are not lot\-tracked and get no lot
subaccounts or gain postings, unless they have explicit lot annotations,
which always enable tracking.
Moving a lotful commodity from a tracked account into such an account is
a disposal; moving it out again needs a cost basis or price on the
receiving posting.
.PP
Sometimes you may want to disable lots/gains processing entirely, to
silence lot\-related errors when you are working with incomplete
journals (eg, when piping hledger print into another hledger command, or
when fixing a complex journal\(aqs problems one at a time).
For this, use the \f[CR]\-\-ignore\-lots\f[R] flag, or just
\f[CR]\-I\f[R].
This skips lot tracking, capital gains calculation, and all lot error
checking, while still doing enough lot inference that lot entries
balance as usual.
Reports then show no lot subaccounts or gains, and \f[CR]print\f[R]
shows lot entries as you wrote them, without inferred cost basis
annotations or gain postings (explicit annotations are kept, and may not
be readable by hledger 1; if that\(aqs needed, use \f[CR]\-O ledger\f[R]
to write them in Ledger\(aqs syntax, which hledger 1 accepts and
ignores).
.SS Lot movements
hledger understands three kinds of lot movement: acquire, transfer, and
dispose.
Other real\-world lot events can usually be modelled using combinations
of these (see Other lot events below).
These are described for lots in asset accounts; in liability accounts,
which hold short positions, the signs are reversed.
.PP
Lots are calculated in date order, and entries on the same date in the
order they are read (an included file is read at the point where it is
included).
So an entry which takes lots out of an account must come after the
entries that put them there, even on the same date; hledger doesn\(aqt
reorder entries to make lots available.
When this goes wrong, the \(dqno lots available\(dq error names a later
entry on the same date which would have supplied the lots, if there is
one.
.SS Acquire
A positive lot posting in an asset account creates a new lot.
.IP
.EX
2026\-01\-01 buy shares
assets:cash \-$500
assets:broker 10 ETSY {$50}
.EE
.PP
The asset posting\(aqs cost is the lot\(aqs cost basis; hledger balances
the transaction and calculates gains with it.
It can be written as a cost basis annotation (\f[CR]{UNITCOST}\f[R] or
\f[CR]{{TOTALCOST}}\f[R]) or as a transacted cost
(\f[CR]\(at UNITCOST\f[R] or \f[CR]\(at\(at TOTALCOST\f[R]); in an
acquisition these mean the same thing.
(Note, \f[CR]\(at\f[R] alone makes a lot posting only if the commodity
is declared lotful or the account is named like a lot subaccount;
otherwise it is just a conversion and creates no lot.
To make it an acquisition, adding just \f[CR]{}\f[R] would be enough, eg
\f[CR]10 ETSY {} \(at $50\f[R].)
Usually you write just one and the other is inferred; if both are
written, they must agree (at the precision you wrote the basis with; the
exact transacted cost is then used as the basis; see also Basis and
transacted cost must agree).
(The total cost forms are useful when the unit cost is
non\-terminating.)
The cost can also be inferred from a lot subaccount name, or, for a
lotful commodity, from the transaction\(aqs other postings \- so even a
bare positive posting (no \f[CR]{}\f[R] or \f[CR]\(at\f[R]) can be an
acquire.
.PP
The other postings show what funded the basis, such as:
.IP \(bu 2
cash for what you paid (including fees if you want those capitalised in
the basis; see Capitalising fees)
.IP \(bu 2
an expense posting for any part of what you paid that isn\(aqt basis (a
fee you don\(aqt want to capitalise)
.IP \(bu 2
an income or equity posting for any part you didn\(aqt pay (as with a
gift\(aqs carryover basis or shares received as compensation).
.PP
Eg shares received as a gift, with the giver\(aqs basis carried over:
.IP
.EX
2026\-01\-01 gift of 10 AAPL, carryover basis $50/share
equity:gifts received $\-500
assets:stocks 10 AAPL \(at $50
.EE
.PP
Other cases with a basis differing from what was paid include
inheritance (stepped\-up basis), stock options and RSUs, and wash sales;
see https://en.wikipedia.org/wiki/Cost_basis.
Recording them this way keeps the accounting equation balanced and shows
where the basis came from.
.SS Basis and transacted cost must agree
In an acquisition, if both a cost basis (\f[CR]{}\f[R]) and a transacted
cost (\f[CR]\(at\f[R]) are written, they must be the same.
(Ledger and Beancount allow them to differ; hledger reports an error.)
This is because:
.IP \(bu 2
In hledger, \f[CR]\(at\f[R] has one consistent meaning: the transacted
cost, what was actually exchanged.
It\(aqs what transactions balance with (except for lot disposals, which
balance with the cost basis; see Gains).
Market prices are recorded with \f[CR]P\f[R] directives, and cost basis
with \f[CR]{}\f[R] annotations.
(hledger may infer the \f[CR]{}\f[R] from \f[CR]\(at\f[R] in a lot
acquisition, as \f[CR]print \-a\f[R] will show.)
.IP \(bu 2
If \f[CR]\(at\f[R] and \f[CR]{}\f[R] could differ, the difference would
have no proper place.
If the entry balanced with \f[CR]\(at\f[R] while gains were calculated
from \f[CR]{}\f[R], the difference would be unaccounted for: it would be
neither gain nor income, and cost reports (eg \f[CR]bse \-B\f[R]) would
be off by it.
If it balanced with \f[CR]{}\f[R] instead (as in Ledger and Beancount),
\f[CR]\(at\f[R] would need a second meaning, an informational market
price.
.IP \(bu 2
Real cases where the basis differs from what was paid (gifts,
inheritance, RSUs..)
don\(aqt need it.
They are better recorded as shown above, with the difference funded by a
separate posting, recording where it came from.
.IP \(bu 2
It catches mistakes.
Otherwise, a typo in either amount would silently miscalculate gains.
.PP
So, if you have such entries (eg from Ledger or Beancount), you can
rewrite them depending on what was intended:
.IP \(bu 2
If \f[CR]\(at\f[R] was meant as a market price (the usual Ledger and
Beancount meaning), drop it, and record the price with a \f[CR]P\f[R]
directive.
Eg, this Ledger entry, which balances with the basis, and records a
market price of 1.30 USD:
.RS 2
.IP
.EX
2026\-01\-01 buy
assets:test 10.00 EUR {1.23 USD} \(at 1.30 USD
assets:bank
.EE
.PP
can be written for hledger like this:
.IP
.EX
P 2026\-01\-01 EUR 1.30 USD
2026\-01\-01 buy
assets:test 10.00 EUR {1.23 USD}
assets:bank
.EE
.RE
.IP \(bu 2
If the basis really differs from what you paid, write the same amount in
both (or just one of them), and record the difference with a separate
posting, as in the gift example above.
.IP \(bu 2
If they differ only by rounding, write the basis with more decimal
places, or use the total cost forms.
.IP \(bu 2
To load an old journal without errors (and without lot tracking), use
\f[CR]\-I\f[R]/\f[CR]\-\-ignore\-lots\f[R].
.SS Capitalising fees
hledger does not automatically capitalise fees into cost basis (as some
tax treatments allow, for purchase or transfer fees).
To capitalise an acquisition fee, fold it into the acquisition cost:
.IP
.EX
2026\-01\-15 buy 10 AAPL at $50, plus a $10 commission, capitalised
assets:stocks 10 AAPL \(at\(at $510
assets:cash \-$510
.EE
.PP
This lot\(aqs cost basis is $51 per share.
(Recording the commission as a separate expense posting would instead
keep it out of the basis.)
Capitalising an in\-kind transfer fee is possible too, but fiddly; see
Other lot events.
.SS Transfer
A matching pair of negative/positive lotful postings moves one or more
existing lots between accounts, preserving their cost basis.
.IP
.EX
2026\-05\-01 transfer to another broker
assets:broker \-10 ETSY
assets:broker2 10 ETSY
.EE
.PP
Transfer postings should not have a transacted price, and the total
quantities sent and received must match: transferred lots keep their
identity.
Within that, source and destination postings need not pair up one to one
\- one source posting can feed several destination accounts, or several
sources one destination.
The destination amount, or the source amount, can also be elided, even
when the other posting carries a lot selector (eg
\f[CR]assets:broker \-10 ETSY {2026\-01\-01}\f[R] balanced by a bare
\f[CR]assets:broker2\f[R] posting, or vice versa).
.PP
A consequence: a disposal entry mistakenly written without a selling
price, and with the other amount left implicit, looks like a lot
transfer, and is quietly read as one, without raising an error.
If in doubt, \f[CR]print \-a\f[R] shows how an entry was read.
.SS Transfer fees
If the destination receives less than the source sends (eg because an
exchange deducted a fee), record the fee as its own posting in the same
commodity, eg \f[CR]expenses:fees 0.001 ETH \(at $3000\f[R] (or without
the price); several fee postings which together make up the difference
also work.
hledger reads the fee as a small disposal (consuming lots in the usual
cost basis method order, before the transfer) and transfers the rest.
With a price, the fee disposal gets a gain calculated; without one, it
doesn\(aqt.
Otherwise, mismatched sent/received totals are an error.
\f[CR]print \-\-lots\f[R] (or \f[CR]print \-a\f[R]) shows how the entry
was read.
.PP
Conversely, if the destination receives \f[I]more\f[R] than the source
sends (eg a reclaimed fee, or dust from a past bookkeeping error), a fee
can\(aqt explain that, and the extra should be recorded as its own
acquisition: give it a real or dummy cost basis (or price) annotation,
which keeps it out of the transfer matching.
Eg:
.IP
.EX
2026\-05\-01 transfer, plus a reclaimed fee
assets:broker \-10 ETH
assets:broker2 10 ETH
expenses:fees \-0.001 ETH
assets:broker2 0.001 ETH {$0}
.EE
.SS Transfers recorded in two entries
A transfer between your own accounts is sometimes recorded twice, once
from each account\(aqs statement, the two entries meeting in a clearing
account:
.IP
.EX
2026\-01\-03 send to wallet A ; from wallet B\(aqs statement
assets:wallet B \-0.11 ETH
assets:transfers 0.10 ETH
expenses:fees 0.01 ETH
2026\-01\-03 receive from wallet B ; from wallet A\(aqs statement
assets:transfers \-0.10 ETH
assets:wallet A 0.10 ETH
.EE
.PP
The receiving entry takes the lots out of the clearing account, so the
sending entry must be read first (see Lot movements).
When each statement is imported into its own file, this depends on the
order the files are included in.
Some ways to make it reliable:
.IP \(bu 2
Record the transfer as one entry, from one statement, and drop it from
the other (eg with a \f[CR]skip\f[R] rule in that account\(aqs CSV
rules).
This is the most accurate model of a single event, and doesn\(aqt depend
on order.
.IP \(bu 2
Include the sending account\(aqs files before the receiving
account\(aqs.
This stops working if, on some date, transfers go both ways.
.SS Dispose
A negative lot posting sells from one or more existing lots.
.IP
.EX
2026\-08\-01 sell at a gain
assets:broker2 \-10 ETSY {$50} \(at $90 ; selecting the lot by specific identification
assets:cash $900
revenues:gain $\-400 ; gain can be recorded explicitly or left implicit
.EE
.PP
The disposal posting must have a transacted price (the selling price),
either explicit or inferred: $90 here.
.PP
One exception: an \f[I]in\-kind disposal\f[R], where the entry\(aqs
non\-asset postings receive the disposed units (the same commodity, in
the same total quantity, possibly split across postings), may be
priceless.
Eg a transfer fee deducted in the commodity, or an in\-kind donation.
This is a simple way to record such outflows when you don\(aqt need a
gain calculated: the disposed units leave their lot(s) carrying their
own cost basis, so the remaining units\(aq basis is unchanged, but no
gain or loss is recognised, and the receiving posting holds unpriced
commodity units.
To have the gain calculated, give the receiving posting a transacted
price.
.PP
When the gain posting is inferred, it is calculated from the entry\(aqs
dispose postings only (the quantity times the difference between selling
price and cost basis, summed); acquire postings in the same entry
don\(aqt contribute.
.SS Short positions
A short position \- units sold before they are bought, with the broker
lending them \- is recorded as lots in a \f[I]liability\f[R] account
(type \f[CR]L\f[R], declared or inferred from the account name).
There the signs are reversed: a \f[I]negative\f[R] lot posting opens a
short lot (it is an acquire, whose cost basis is the short\-sale price),
and a \f[I]positive\f[R] lot posting closes it, by buying units back (it
is a disposal, whose transacted price is the buying price).
A short lot\(aqs gain is its basis minus the buying price, so it is
positive when the price has fallen:
.IP
.EX
commodity XYZ ; lots:
2026\-01\-02 sell short
liabilities:broker:XYZ \-10 XYZ \(at $100
assets:broker:cash
P 2026\-01\-31 XYZ $90
2026\-02\-02 cover
liabilities:broker:XYZ 10 XYZ \(at $90
assets:broker:cash
revenues:gain
.EE
.IP
.EX
$ hledger \-f short.journal print \-x
2026\-01\-02 sell short
liabilities:broker:XYZ \-10 XYZ {$100} \(at $100
assets:broker:cash $1000
2026\-02\-02 cover
liabilities:broker:XYZ 10 XYZ {2026\-01\-02, $100} \(at $90
assets:broker:cash $\-900
revenues:gain $\-100
.EE
.PP
Reports work as for long positions.
While the position is open, \f[CR]bs \-B\f[R] shows the liability at
cost ($1000), offsetting the cash received; \f[CR]bs \-V\f[R] shows it
at market value ($900), so the net worth includes the unrealised gain;
\f[CR]bal \-\-gain\f[R] shows that gain ($100); and \f[CR]holdings\f[R]
shows negative units and cost (but no XIRR, which is not meaningful for
a short position).
After covering, the realised gain is in \f[CR]revenues:gain\f[R], and
\f[CR]bse\f[R] balances.
.PP
Everything else is as for lots in asset accounts: cost basis annotations
and lot subaccounts, lot selectors and cost basis methods, generated or
user\-written gain postings, and \f[CR]lots: NONE\f[R] to opt out.
Note that HIFO covers the highest short\-sale price first, which
realises the largest gain first; use SPECID to choose.
Long lots and short lots of the same commodity are separate pools, so
they may use different methods.
.PP
Transferring a short position between accounts is not yet supported:
cover it in one account and open it in the other, with prices.
(\f[CR]close \-\-lots\f[R] can move short lots to and from equity,
though.)
A negative posting in an \f[I]asset\f[R] account holding no lots is
still an error, since it is usually a mistake.
.SS Other lot events
Other real\-world events \- a gift received with a carryover cost basis,
bonus shares, a stock split, capitalising an in\-kind transfer fee \-
can be recorded as combinations of acquires, transfers and disposals.
Other lot events on hledger.org has worked examples.
The right treatment varies by jurisdiction, so check your local tax
rules.
.SS Cost basis methods
If a lot transfer or a lot disposal doesn\(aqt specifically identify the
lot(s) involved, hledger selects from the available lots automatically,
using a \f[I]cost basis method\f[R] (AKA disposal method / reduction
method / booking method).
.PP
Use the method your tax jurisdiction requires or allows.
The default method is FIFO (first in, first out).
You can override this with a \f[CR]lots\f[R] tag value on the commodity
or account declaration.
(An account tag will take precedence; on an account, the tag requires a
method value.)
Eg:
.IP
.EX
commodity FUND ; lots: AVERAGE
account assets:stocks ; lots: LIFO
.EE
.PP
These methods are supported:
.PP
.TS
tab(@);
lw(8.2n) lw(14.3n) lw(11.9n) lw(35.6n).
T{
Method
T}@T{
Lots selected
T}@T{
Disposal cost basis
T}@T{
Error checking
T}
_
T{
\f[B]SPECID\f[R]
T}@T{
one specific lot
T}@T{
specified lot\(aqs cost
T}@T{
A matching lot, with sufficient balance, exists in the account.
T}
T{
\f[B]FIFO\f[R]
T}@T{
oldest first
T}@T{
each lot\(aqs cost
T}@T{
Sufficient lot(s) exist in the account.
T}
T{
\f[B]LIFO\f[R]
T}@T{
newest first
T}@T{
each lot\(aqs cost
T}@T{
\(dq
T}
T{
\f[B]HIFO\f[R]
T}@T{
highest cost first
T}@T{
each lot\(aqs cost
T}@T{
\(dq
T}
T{
\f[B]AVERAGE\f[R]
T}@T{
oldest first
T}@T{
average cost
T}@T{
\(dq
T}
T{
\f[B]FIFOALL\f[R]
T}@T{
oldest first (all accounts)
T}@T{
each lot\(aqs cost
T}@T{
Sufficient lot(s) exist in the account, and are highest priority across
all accounts.
T}
T{
\f[B]LIFOALL\f[R]
T}@T{
newest first (all accounts)
T}@T{
each lot\(aqs cost
T}@T{
\(dq
T}
T{
\f[B]HIFOALL\f[R]
T}@T{
highest cost first (all accounts)
T}@T{
each lot\(aqs cost
T}@T{
\(dq
T}
T{
\f[B]AVERAGEALL\f[R]
T}@T{
oldest first (all accounts)
T}@T{
average cost (all accounts)
T}@T{
Sufficient lot(s) exist across all accounts.
T}
.TE
.PP
\f[B]SPECID\f[R] (specific identification) is what you\(aqre using when
a disposal names its lot(s), with a lot selector like
\f[CR]{2026\-01\-15, $50}\f[R] or an explicit lot subaccount.
Select by date (and label) rather than by cost alone: costs shown in lot
names may be rounded (see Cost basis precision), so a cost\-only
selector like \f[CR]{$50}\f[R] can match more lots than intended (an
ambiguity error under SPECID; under other methods, consumed in the
method\(aqs order).
.PP
\f[B]AVERAGE\f[R] keeps one running average cost per account (pool),
recalculated at each acquisition and applied to every lot in the pool;
disposals use it, consuming lots in FIFO order so acquisition dates stay
meaningful for holding periods.
Lot names omit the cost (\f[CR]{2026\-01\-15}\f[R]), the average appears
in the holdings Avg cost column and in disposal postings shown by
\f[CR]print \-x\f[R], and transferring lots into or out of the pool
carries the average with them (a lot\(aqs original cost can\(aqt be
recovered from a pool).
close \-\-lots writes each lot with the pool\(aqs average cost as of the
closing date (\f[CR]{2026\-01\-15, $55}\f[R]), so that its output can be
read back, eg to start a new file.
(\f[CR]print \-\-lots\f[R] output for AVERAGE lots can\(aqt be read back
yet.)
.PP
The \f[B]*ALL\f[R] variants additionally check that the lots selected
are the ones that would be chosen across all accounts holding the
commodity, and raise an error naming the other account otherwise; use
them to enforce a global disposal order across brokers, exchanges and
wallets.
Since they involve every account, declare them on the commodity, not on
accounts.
\f[B]AVERAGEALL\f[R] likewise keeps a single average across all
accounts.
.SS Changing the cost basis method
hledger recalculates all lots on each run, using the currently declared
methods.
So changing a declared method also reinterprets past history under the
new method.
Sometimes that\(aqs fine; but usually you\(aqll want past disposals to
keep their original lot selections and gains (tax authorities generally
expect a method change to apply only going forward).
Things to know:
.IP \(bu 2
Disposals recorded without explicit lot selectors or gain amounts will
select different lots under the new method, changing their cost bases
and realised gains.
.IP \(bu 2
Disposals which do record the old method\(aqs selections \- as explicit
gain amounts, lot selectors, lot subaccount names, or balance assertions
\- will be checked against the new method\(aqs selections, and any
differences will be reported as errors.
.PP
hledger doesn\(aqt yet support declaring different methods for different
time periods, but you can make a method change apply only to the future,
in either of two ways:
.IP "1." 3
Make past disposals fully explicit, with lot selectors and gain amounts,
so they no longer depend on the declared method (\f[CR]print \-x\f[R]
and \f[CR]print \-\-lots\f[R] can help with this).
Then change the method.
.IP "2." 3
Or, start a new journal file at the changeover date, using
\f[CR]close \-\-clopen \-\-lots\f[R] to carry the current lots into it,
and declare the new method in the new file.
.SS Gains
Each disposal transaction has a \f[B]gain posting\f[R], usually on a
Gain\-type account, recording the capital gain (or loss) as revenue (or
negative revenue).
(Following the usual PTA style, a negative number here means profit, a
positive number means loss.)
.PP
A disposal balances at cost basis, not at transacted cost: the disposed
units count as their quantity times their cost basis (what they cost
you), the proceeds are what you received, and the gain posting accounts
for the difference.
Eg selling 5 AAPL bought at $50 for $70 each:
\f[CR]\-5 AAPL {$50} \(at $70\f[R] counts as \-$250, \f[CR]$350\f[R] is
received, and \f[CR]revenues:gain $\-100\f[R] balances the entry.
(This is the historical cost accounting convention, and is how hledger 1
users have recorded gains.
Unrealised gains are not recorded as postings, but can be reported from
market prices, eg with holdings or \f[CR]\-\-gain\f[R].
Consequently the accounting equation stays balanced through disposals.)
.PP
The gain posting can be left implicit (and hledger will infer it); or it
can be written explicitly in the journal.
Recording gains below shows examples of both.
.PP
In an inferred gain posting, the gain amount will be rounded to the
entry\(aqs local precision for the gain commodity (or if the local
precision is zero, two decimal digits will be shown \- except when both
of those digits are zero).
More decimals can be seen by increasing the display precision (eg
\f[CR]hledger print \-\-round=soft \-c \(aq$1.0000\(aq\f[R]).
.PP
An explicit gain posting can also be written without an amount, in which
case hledger fills in the calculated gain (as when the gain posting is
omitted, but with your choice of account).
At most one gain posting per entry can be left amountless.
.SS Gain accounts
The \f[B]\f[CB]Gain\f[B]\f[R] (\f[B]\f[CB]G\f[B]\f[R]) account type is a
subtype of Revenue.
Declaring an account with the G type serves three purposes:
.IP "1." 3
\f[B]Recognising gain postings\f[R] \- explicit gain postings which use
the G account will be detected reliably by account type, and error
messages may be clearer.
.IP "2." 3
\f[B]Customising account names\f[R] \- inferred gain postings will use
the first\-declared G account, rather than the default
(\f[CR]revenues:gain\f[R]).
(If no account is declared with the G type, they use the alphabetically
first account whose type is inferred as G, if any.)
.IP "3." 3
\f[B]Categorising\f[R] \- when reporting, you can match on the G account
type specifically.
.PP
G is inferred from conventional English account names (eg
\f[CR]revenues:gain\f[R], \f[CR]income:capital\-gains\f[R]; see the
regex table under Account types).
You can also declare it explicitly:
.IP
.EX
account revenues:capital gain ; type: G
.EE
.PP
(There is also an \f[B]\f[CB]UnrealisedGain\f[B]\f[R]
(\f[B]\f[CB]U\f[B]\f[R]) account type, a subtype of Equity, for accounts
like \f[CR]equity:unrealised\-gain\f[R]; hledger does not currently
generate postings to these.)
.PP
Why do we post both gains and losses to a revenue account ?
It\(aqs more convenient than using separate revenue and expense
accounts, and the sign keeps things correct.
.SS Recording gains
In a disposal entry, you can leave the gain posting out and let hledger
infer it.
This is the simplest style, and avoids most problems:
.IP
.EX
2026\-02\-01 sell
assets:stocks \-1 AAPL {$50} \(at $60
assets:cash $60
.EE
.PP
Or you can write it, on an account declared with the G account type.
hledger then checks your amount against the calculated gain, catching
more errors:
.IP
.EX
account revenues:gain ; type:G
2026\-02\-01 sell
assets:stocks \-1 AAPL {$50} \(at $60
assets:cash $60
revenues:gain $\-10
.EE
.PP
Multiple gain postings are allowed, eg one per lot when disposing from
several lots.
.PP
Your amount needs to match the calculated gain only at the entry\(aqs
precision (the most decimal places used by the entry\(aqs amounts in
that commodity, as in transaction balancing).
hledger then uses the exact calculated gain, so that the small
difference isn\(aqt left unaccounted for (with several gain postings, it
adjusts the last one).
\f[CR]print\f[R] still shows your amount as written.
.PP
A written gain posting also protects your history, like a balance
assertion: hledger recalculates lots and gains from the whole journal
each time it runs, so if a past acquisition is edited, an inferred gain
could silently change, whereas a written one no longer matches and is
reported as an error.
\f[CR]hledger print \-x\f[R] shows the inferred gain postings, if you
want to write them into the journal.
.PP
A gain posting on an undeclared account also works: hledger detects it
heuristically (roughly: a posting to a non\-asset/liability/equity
account, not itself a lot posting, without which the rest of the entry
balances).
But the heuristic fails when the entry has another such posting, eg a
fee, and the entry is then reported as unbalanced.
So if you write gain postings, declare the account\(aqs type.
\f[CR]hledger print \-a\f[R] shows what was detected.
.PP
(Earlier hledger 2 previews also generated an
\f[CR]equity:unrealised\-gain\f[R] counter posting in each disposal, so
that disposals balanced at transacted cost.
This is no longer done, and such postings, if written explicitly, will
now leave the entry unbalanced; remove them.)
.SS Lot reports
Once lot entries are in the journal, all the usual reports work as
normal, hiding lot detail by default; \f[CR]\-\-lots\f[R] shows it.
Using the several ways journal above (any version):
.PP
\f[CR]holdings\f[R] gives an overview of your investments: units held,
cost, value, unrealised and realised gain, and XIRR (see First lots
example; add \f[CR]\-\-lots\f[R] for per\-lot detail, \f[CR]\-e\f[R] to
choose the date).
.PP
\f[CR]balance \-\-lots\f[R] (or \f[CR]bs \-\-lots\f[R]) shows the
current lots:
.IP
.EX
$ hledger bal assets:stocks \-\-lots \-N
5 AAPL assets:stocks:{2026\-01\-15, $50}
10 AAPL assets:stocks:{2026\-02\-01, $60}
.EE
.SS Realised gains
Realised gains are on the Gain\-type account (see Gain accounts), so
\f[CR]type:G\f[R] queries select them.
The total for a period:
.IP
.EX
$ hledger bal type:G \-p 2026
$\-100 revenues:gain
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
$\-100
.EE
.PP
Each disposal\(aqs gain, with a running total:
.IP
.EX
$ hledger reg type:G
2026\-03\-01 sell some revenues:gain $\-100 $\-100
.EE
.PP
The disposal entries, with the lots and gain amounts hledger inferred
(\f[CR]\-x\f[R] shows inferred amounts, \f[CR]\-\-lots\f[R] the lot
subaccounts, \f[CR]\-a\f[R] everything including each posting\(aqs
classification):
.IP
.EX
$ hledger print tag:ptype=dispose \-x \-\-lots
2026\-03\-01 sell some
assets:stocks:{2026\-01\-15, $50} \-5 AAPL {2026\-01\-15, $50} \(at $70
assets:cash $350
revenues:gain $\-100
.EE
.PP
When using the roi command with a journal that records lots, make sure
\f[CR]\-\-pnl\f[R] matches the gain account, eg:
.IP
.EX
$ hledger roi \-\-inv assets:stocks \-\-pnl revenues:gain
.EE
.PP
so that realised gains are counted as profit rather than as cash flows
out of the investment.
.SS Unrealised gains
Unrealised gains \- on the units you still hold \- are not recorded in
the journal (see Gains); hledger calculates them from market prices when
asked.
Adding some month\-end prices to the journal above:
.IP
.EX
P 2026\-01\-31 AAPL $55
P 2026\-02\-28 AAPL $65
P 2026\-03\-31 AAPL $80
.EE
.PP
\f[CR]holdings\f[R] shows the unrealised gain (UGain) next to the
realised gain (RGain), per commodity or per lot (\f[CR]\-\-lots\f[R]),
as of today or some other date (\f[CR]\-e\f[R]).
.PP
\f[CR]balance \-\-gain\f[R] shows the unrealised gain per account: the
current value of the units held, minus what they cost.
Like \f[CR]\-V\f[R], it uses the market price at the end of the report
period (today, unless you specify \f[CR]\-e\f[R] or a period):
.IP
.EX
$ hledger bal assets:stocks \-\-gain
$350 assets:stocks
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
$350
.EE
.PP
That is: 15 AAPL are held, which cost $850 and are worth $1200 at $80.
\f[CR]\-\-lots\f[R] breaks it down by lot:
.IP
.EX
$ hledger bal assets:stocks \-\-gain \-\-lots \-N
$150 assets:stocks:{2026\-01\-15, $50}
$200 assets:stocks:{2026\-02\-01, $60}
.EE
.PP
With a report interval, \f[CR]\-H\f[R] shows the unrealised gain as of
each period end, and without \f[CR]\-H\f[R], how much it changed during
each period:
.IP
.EX
$ hledger bal assets:stocks \-\-gain \-M \-H
Historical gain in 2026Q1, valued at period ends:
|| 2026\-01\-31 2026\-02\-28 2026\-03\-31
===============++====================================
assets:stocks || $50 $200 $350
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| $50 $200 $350
.EE
.PP
(This is not the same as \f[CR]\-\-valuechange\f[R], which shows how
much an account\(aqs value changed in each period, from price movements
and from buying and selling.)
.PP
\f[CR]\-\-gain\f[R] needs a market price for the units; where none is
found, the units are shown unconverted, alongside the negated cost.
Realised and unrealised gains don\(aqt overlap: the gain on units sold
is realised, the gain on units held is unrealised, and together they are
the total gain on the investment so far (here, $100 + $350).
.SS Lot details
Some finer points, for reference.
.SS Lot labels
Internally, each lot is identified by its cost basis date plus an
optional label.
Lots of a commodity acquired on the same date (even in different
accounts) must have unique labels to help identify them.
If you don\(aqt provide these, hledger adds sequential labels
automatically (\f[CR]\(dq0001\(dq\f[R], \f[CR]\(dq0002\(dq\f[R], ..).
Labels are used for sorting, so if you write your own, make them
sortable.
.PP
Automatic labels depend on which transactions hledger reads, so the same
lot can get a different label when files are combined (eg yearly files
with closing and opening balances).
If a lot needs a stable label, eg an acquisition dated to an earlier
purchase\(aqs date after a split or demerger, write your own.
Use a descriptive label, eg \f[CR]\(dqdemerger\(dq\f[R], not numbers
like \f[CR]\(dq0001\(dq\f[R], which can clash with automatic labels.
(More detail: SPEC\-lots.)
.SS Cost basis precision
An inferred cost basis can be a non\-terminating decimal (eg
\f[CR]3 ABC \(at\(at $10\f[R] gives a $10/3 unit cost).
hledger keeps such costs at high precision internally and calculates
gains from the unrounded value, but in lot names it displays at most 8
decimal digits, or more if the cost commodity\(aqs declared display
style has more.
Two consequences: when lots are carried into a new file as text (eg with
\f[CR]close \-\-lots\f[R]), only the displayed digits survive, so if you
track commodities needing finer cost precision, declare a wider display
style for the cost commodity up front; and changing a commodity\(aqs
display precision can change how lot names render, so lot selectors
written with the old rendering will need updating (see Troubleshooting
lots).
Selectors using just the date (and label) don\(aqt embed a cost, and are
unaffected.
(More detail: SPEC\-lots.)
.SS Lot postings and balance assertions
See also Assertions and lot subaccounts above.
.PP
On a dispose or transfer posting without an explicit lot subaccount, a
balance assertion always refers to the parent account\(aqs balance.
So if lot subaccounts are added with \f[CR]\-\-lots\f[R], the assertion
is not affected.
.PP
By contrast, in a journal entry where the lot subaccounts are recorded
explicitly, a balance assertion refers to the lot subaccount\(aqs
balance.
.PP
This means that \f[CR]hledger print \-\-lots\f[R], if it adds explicit
lot subaccounts to a journal entry, could potentially change the meaning
of balance assertions, breaking them.
To avoid this, in such cases it will move the balance assertion to a new
zero\-amount posting to the parent account (and make sure it\(aqs
subaccount\-inclusive).
(So eg
\f[CR]hledger \-f\- print \-\-lots \-x | hledger \-f\- check assertions\f[R]
will still pass.)
.SS Troubleshooting lots
hledger analyses lot entries carefully, but it won\(aqt understand every
possible shape.
When it reports a lot\-related error, or a report looks wrong:
.IP \(bu 2
\f[CR]hledger print \-a\f[R] shows how each entry was read: the inferred
cost basis, lot subaccounts and gain posting, and each posting\(aqs
classification (\f[CR]ptype: acquire\f[R], \f[CR]dispose\f[R],
\f[CR]transfer\-from\f[R], \f[CR]transfer\-to\f[R] or \f[CR]gain\f[R]).
If an entry was misread, rewrite it more explicitly, eg by adding a cost
basis annotation, or a transacted cost.
.IP \(bu 2
\(dqno lots matching ...\(dq means a lot selector matched nothing in
that account; the error lists the account\(aqs actual lots.
Common causes: the lot is in another account, or a cost\-only selector
no longer matches the displayed cost (see Cost basis precision; date
selectors avoid this).
.IP \(bu 2
A disposal written without a selling price, with the other amount left
implicit, is silently read as a transfer.
Add the price.
.IP \(bu 2
\(dqrealised gain amount is wrong\(dq means a written gain posting
doesn\(aqt match the calculated gain; the error shows both amounts.
Check which lots were selected (\f[CR]print \-a\f[R]) and the amounts.
.IP \(bu 2
\(dqcost basis ...
differs from its transacted cost\(dq means an acquisition wrote both a
\f[CR]{}\f[R] basis and an \f[CR]\(at\f[R] cost which don\(aqt agree.
Write just one of them, or see Basis and transacted cost must agree for
other fixes.
.IP \(bu 2
\(dqno ...
lots available for disposal\(dq means a sale from an account holding
none of the commodity.
If it is a short sale, record it in a liability account (see Short
positions).
If the purchases were written with just an \f[CR]\(at\f[R] cost (common
in Ledger journals), they did not create lots; declare the commodity
lotful.
.IP \(bu 2
For more detail, \f[CR]\-\-debug=5\f[R] (eg
\f[CR]hledger check \-\-debug=5\f[R]) traces lot processing step by
step.
It\(aqs verbose, and mostly useful for advanced troubleshooting or bug
reports.
.IP \(bu 2
To silence lot processing while fixing other problems, use
\f[CR]\-I\f[R] or \f[CR]\-\-ignore\-lots\f[R].
.SH Generating data
hledger can enrich the data provided to it, or generate new data, in a
number of ways.
Mostly, this is done only if you request it:
.IP \(bu 2
Missing amounts, costs, cost basis, and capital gain amounts are
inferred automatically when possible.
.IP \(bu 2
Lot subaccounts are also inferred (invisibly by default;
\f[CR]\-\-lots\f[R] makes them visible in reports).
.IP \(bu 2
The \f[CR]\-\-infer\-equity\f[R] flag infers missing conversion equity
postings from \(at/\(at\(at costs.
.IP \(bu 2
The \f[CR]\-\-infer\-costs\f[R] flag infers missing costs from
conversion equity postings.
.IP \(bu 2
The \f[CR]\-\-infer\-market\-prices\f[R] flag infers \f[CR]P\f[R] price
directives from costs.
.IP \(bu 2
The \f[CR]\-\-auto\f[R] flag adds extra postings to transactions matched
by auto posting rules.
.IP \(bu 2
The \f[CR]\-\-forecast\f[R] option generates transactions from periodic
transaction rules.
.IP \(bu 2
The \f[CR]balance \-\-budget\f[R] report infers budget goals from
periodic transaction rules.
.IP \(bu 2
Commands like \f[CR]close\f[R], \f[CR]rewrite\f[R], and
\f[CR]hledger\-interest\f[R] generate transactions or postings.
.IP \(bu 2
CSV data is converted to transactions by applying CSV conversion rules..
etc.
.PP
Such generated data is temporary, existing only at report time.
You can convert it to permanent recorded data by, eg, capturing the
output of \f[CR]hledger print\f[R] and saving it in your journal file.
This can sometimes be useful as a data entry aid.
.PP
If you are curious what data is being generated and why, run
\f[CR]hledger print \-a\f[R] (equivalent to
\f[CR]\-\-explicit \-\-lots \-\-verbose\-tags\f[R]).
\f[CR]\-x/\-\-explicit\f[R] shows inferred amounts and conversion
prices, \f[CR]\-\-lots\f[R] shows lot subaccounts and lot\-specific
postings, and \f[CR]\-\-verbose\-tags\f[R] shows the hidden tags which
hledger uses for analysing transactions .
.SH Forecasting
Forecasting, or speculative future reporting, can be useful for
estimating future balances, or for exploring different future scenarios.
.PP
The simplest and most flexible way to do it with hledger is to manually
record a bunch of future\-dated transactions.
You could keep these in a separate \f[CR]future.journal\f[R] and include
that with \f[CR]\-f\f[R] only when you want to see them.
.SS \-\-forecast
There is another way: with the \f[CR]\-\-forecast\f[R] option, hledger
can generate temporary \(dqforecast transactions\(dq for reporting
purposes, according to periodic transaction rules defined in the
journal.
Each rule can generate multiple recurring transactions, so by changing
one rule you can change many forecasted transactions.
.PP
Forecast transactions usually start after ordinary transactions end.
By default, they begin after your latest\-dated ordinary transaction, or
today, whichever is later, and they end six months from today.
(The exact rules are a little more complicated, and are given below.)
.PP
This is the \(dqforecast period\(dq, which need not be the same as the
report period.
You can override it \- eg to forecast farther into the future, or to
force forecast transactions to overlap your ordinary transactions \- by
giving the \-\-forecast option a period expression argument, like
\f[CR]\-\-forecast=..2099\f[R] or
\f[CR]\-\-forecast=2023\-02\-15..\f[R].
Note that the \f[CR]=\f[R] is required.
.SS Inspecting forecast transactions
\f[CR]print\f[R] is the best command for inspecting and troubleshooting
forecast transactions.
Eg:
.IP
.EX
\(ti monthly from 2022\-12\-20 rent
assets:bank:checking
expenses:rent $1000
.EE
.IP
.EX
$ hledger print \-\-forecast \-\-today=2023/4/21
2023\-05\-20 rent
; generated\-transaction: \(ti monthly from 2022\-12\-20
assets:bank:checking
expenses:rent $1000
2023\-06\-20 rent
; generated\-transaction: \(ti monthly from 2022\-12\-20
assets:bank:checking
expenses:rent $1000
2023\-07\-20 rent
; generated\-transaction: \(ti monthly from 2022\-12\-20
assets:bank:checking
expenses:rent $1000
2023\-08\-20 rent
; generated\-transaction: \(ti monthly from 2022\-12\-20
assets:bank:checking
expenses:rent $1000
2023\-09\-20 rent
; generated\-transaction: \(ti monthly from 2022\-12\-20
assets:bank:checking
expenses:rent $1000
.EE
.PP
Here there are no ordinary transactions, so the forecasted transactions
begin on the first occurrence after today\(aqs date.
(You won\(aqt normally use \f[CR]\-\-today\f[R]; it\(aqs just to make
these examples reproducible.)
.SS Forecast reports
Forecast transactions affect all reports, as you would expect.
Eg:
.IP
.EX
$ hledger areg rent \-\-forecast \-\-today=2023/4/21
Transactions in expenses:rent and subaccounts:
2023\-05\-20 rent as:ba:checking $1000 $1000
2023\-06\-20 rent as:ba:checking $1000 $2000
2023\-07\-20 rent as:ba:checking $1000 $3000
2023\-08\-20 rent as:ba:checking $1000 $4000
2023\-09\-20 rent as:ba:checking $1000 $5000
.EE
.IP
.EX
$ hledger bal \-M expenses \-\-forecast \-\-today=2023/4/21
Balance changes in 2023\-05\-01..2023\-09\-30:
|| May Jun Jul Aug Sep
===============++===================================
expenses:rent || $1000 $1000 $1000 $1000 $1000
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
|| $1000 $1000 $1000 $1000 $1000
.EE
.SS Forecast tags
Forecast transactions generated by \-\-forecast have a hidden tag,
\f[CR]_generated\-transaction\f[R].
So if you ever need to match forecast transactions, you could use
\f[CR]tag:_generated\-transaction\f[R] (or just
\f[CR]tag:generated\f[R]) in a query.
.PP
For troubleshooting, you can add the \f[CR]\-\-verbose\-tags\f[R] flag.
Then, visible \f[CR]generated\-transaction\f[R] tags will be added also,
so you can view them with the \f[CR]print\f[R] command.
Their value indicates which periodic rule was responsible.
.SS Forecast period, in detail
Forecast start/end dates are chosen so as to do something useful by
default in almost all situations, while also being flexible.
Here are (with luck) the exact rules, to help with troubleshooting:
.PP
The forecast period starts on:
.IP \(bu 2
the later of
.RS 2
.IP \(bu 2
the start date in the periodic transaction rule
.IP \(bu 2
the start date in \f[CR]\-\-forecast\f[R]\(aqs argument
.RE
.IP \(bu 2
otherwise (if those are not available): the later of
.RS 2
.IP \(bu 2
the report start date specified with
\f[CR]\-b\f[R]/\f[CR]\-p\f[R]/\f[CR]date:\f[R]
.IP \(bu 2
the day after the latest ordinary transaction in the journal
.RE
.IP \(bu 2
otherwise (if none of these are available): today.
.PP
The forecast period ends on:
.IP \(bu 2
the earlier of
.RS 2
.IP \(bu 2
the end date in the periodic transaction rule
.IP \(bu 2
the end date in \f[CR]\-\-forecast\f[R]\(aqs argument
.RE
.IP \(bu 2
otherwise: the report end date specified with
\f[CR]\-e\f[R]/\f[CR]\-p\f[R]/\f[CR]date:\f[R]
.IP \(bu 2
otherwise: 180 days (\(ti6 months) from today.
.SS Forecast troubleshooting
When \-\-forecast is not doing what you expect, one of these tips should
help:
.IP \(bu 2
Remember to use the \f[CR]\-\-forecast\f[R] option.
.IP \(bu 2
Remember to have at least one periodic transaction rule in your journal.
.IP \(bu 2
Test with \f[CR]print \-\-forecast\f[R].
.IP \(bu 2
Check for typos or too\-restrictive start/end dates in your periodic
transaction rule.
.IP \(bu 2
Leave at least 2 spaces between the rule\(aqs period expression and
description fields.
.IP \(bu 2
Check for future\-dated ordinary transactions suppressing forecasted
transactions.
.IP \(bu 2
Try setting explicit report start and/or end dates with \f[CR]\-b\f[R],
\f[CR]\-e\f[R], \f[CR]\-p\f[R] or \f[CR]date:\f[R]
.IP \(bu 2
Try adding the \f[CR]\-E\f[R] flag to encourage display of empty
periods/zero transactions.
.IP \(bu 2
Try setting explicit forecast start and/or end dates with
\f[CR]\-\-forecast=START..END\f[R]
.IP \(bu 2
Consult Forecast period, in detail, above.
.IP \(bu 2
Check inside the engine: add \f[CR]\-\-debug=2\f[R] (eg).
.SH Budgeting
With the balance command\(aqs \f[CR]\-\-budget\f[R] report, each
periodic transaction rule generates recurring budget goals in specified
accounts, and goals and actual performance can be compared.
See the balance command\(aqs doc below.
.PP
You can generate budget goals and forecast transactions at the same
time, from the same or different periodic transaction rules:
\f[CR]hledger bal \-M \-\-budget \-\-forecast ...\f[R]
.PP
See also: Budgeting on hledger.org.
.SH Posting types
hledger detects and tags certain kinds of postings, to help it
understand complex transactions.
Here is quick overview of the posting detection rules.
.PP
By default, these tags are hidden (with a \f[CR]_\f[R] prefix), so they
can be queried but they won\(aqt appear in \f[CR]print\f[R] output.
To also add visible tags, for troubleshooting, use \f[CR]print\f[R]\(aqs
\f[CR]\-\-verbose\-tags\f[R] or \f[CR]\-a/\-\-all\f[R] flags.
.PP
.TS
tab(@);
lw(5.4n) lw(40.2n) lw(24.4n).
T{
Tag
T}@T{
Detected pattern
T}@T{
Effect
T}
_
T{
\f[CR]conversion\-posting\f[R]
T}@T{
A pair of adjacent, single\-commodity, costless postings to
\f[CR]Conversion\f[R]\-type accounts, with a nearby corresponding
costful or potentially corresponding costless posting
T}@T{
Helps transaction balancer infer costs or avoid redundancy in commodity
conversions
T}
T{
\f[CR]cost\-posting\f[R]
T}@T{
A costful posting whose amount and transacted cost correspond to a
conversion postings pair; or a costless posting matching one of the pair
T}@T{
Helps transaction balancer infer costs or avoid redundancy in commodity
conversions
T}
T{
\f[CR]generated\-posting\f[R]
T}@T{
Postings generated at runtime
T}@T{
Helps users understand or find postings added at runtime by hledger
T}
T{
\f[CR]ptype:acquire\f[R]
T}@T{
Positive postings with lot annotations, or in a lotful commodity, with
no matching counterposting (negative, in a liability account: a short
position)
T}@T{
Creates a new lot
T}
T{
\f[CR]ptype:dispose\f[R]
T}@T{
Negative postings with lot annotations, or in a lotful commodity, with
no matching counterposting (positive, in a liability account: covering a
short position)
T}@T{
Selects and reduces existing lots
T}
T{
\f[CR]ptype:transfer\-from\f[R]
T}@T{
The negative posting of a pair of counterpostings, at least one with lot
annotation or a lotful commodity; or a negative lot posting with an
equity counterpart (equity transfer)
T}@T{
Moves lots between accounts, preserving cost basis
T}
T{
\f[CR]ptype:transfer\-to\f[R]
T}@T{
The positive posting of a transfer pair; or a positive lot posting with
an equity counterpart (equity transfer, e.g.
opening balances)
T}@T{
As above
T}
T{
\f[CR]ptype:gain\f[R]
T}@T{
In a disposal: a user\-written posting to a \f[CR]Gain\f[R]\-type
account (or, failing that, a non\-asset/liability/equity posting without
which the entry balances); or the realised\-gain posting hledger
generates
T}@T{
Records the realised capital gain/loss; set aside by the transaction
balancer, so the disposal balances at cost basis
T}
.TE
.SH PART 5: MORE ABOUT THE COMMAND LINE
.SH Output
.SS Output destination
hledger commands send their output to the terminal by default.
You can of course redirect this, eg into a file, using standard shell
syntax:
.IP
.EX
$ hledger print > foo.txt
.EE
.PP
Some commands (print, register, stats, the balance commands) also
provide the \f[CR]\-o\f[R]/\f[CR]\-\-output\-file\f[R] option, which
does the same thing without needing the shell.
Eg:
.IP
.EX
$ hledger print \-o foo.txt
$ hledger print \-o \- # write to stdout (the default)
.EE
.PP
These commands (except stats) also provide \f[CR]\-\-view\f[R], which
writes the output to a file and opens it in your system\(aqs default
viewer for that kind of file, eg a web browser for HTML.
The file is the one given by \f[CR]\-o\f[R], or else \f[CR]view.FMT\f[R]
in hledger\(aqs cache directory (\f[CR]$XDG_CACHE_HOME/hledger/\f[R] or
\f[CR]\(ti/.cache/hledger/\f[R], or
\f[CR]%LOCALAPPDATA%\(rshledger\(rs\f[R] on Windows), replaced each
time, and readable only by you (on unix systems).
hledger shows the file\(aqs path; if the report is sensitive, you can
delete the file when you\(aqre done with it, or use \f[CR]\-o\f[R] to
save it somewhere else.
The output format is HTML unless you choose another, with \f[CR]\-O\f[R]
or the \f[CR]\-o\f[R] file\(aqs extension.
Eg:
.IP
.EX
$ hledger is \-M \-\-chart \-\-view # see an income statement chart and table in a web browser
$ hledger reg \-O csv \-\-view # or a register in a spreadsheet
.EE
.PP
To view several reports at once, on one page, use \f[CR]run\f[R] with
\f[CR]\-\-view\f[R]:
.IP
.EX
$ hledger run \-\-view \-\- is \-M \-\-chart \-\- bs \-Q \-\-chart \-\- reg expenses \-p thismonth
.EE
.SS Output format
Some commands offer other kinds of output, not just text on the
terminal.
Here are those commands and the formats currently supported:
.PP
.TS
tab(@);
lw(15.6n) lw(3.9n) lw(7.0n) lw(4.7n) lw(7.0n) lw(4.7n) lw(6.2n) lw(8.6n) lw(3.9n) lw(4.7n) lw(3.9n).
T{
command
T}@T{
txt
T}@T{
journal
T}@T{
html
T}@T{
csv/tsv
T}@T{
fods
T}@T{
ledger
T}@T{
beancount
T}@T{
sql
T}@T{
json
T}@T{
svg
T}
_
T{
aregister
T}@T{
Y
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}@T{
Y
T}@T{
Y
T}
T{
balance
T}@T{
Y
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}@T{
Y
T}@T{
Y
T}
T{
balancesheet
T}@T{
Y
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}@T{
Y
T}@T{
Y
T}
T{
balancesheetequity
T}@T{
Y
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}@T{
Y
T}@T{
Y
T}
T{
cashflow
T}@T{
Y
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}@T{
Y
T}@T{
Y
T}
T{
holdings
T}@T{
Y
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}@T{
Y
T}@T{
T}
T{
incomestatement
T}@T{
Y
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}@T{
Y
T}@T{
Y
T}
T{
print
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}
T{
register
T}@T{
Y
T}@T{
T}@T{
Y
T}@T{
Y
T}@T{
Y
T}@T{
T}@T{
T}@T{
T}@T{
Y
T}@T{
Y
T}
.TE
.PP
You can also see which output formats a command supports by running
\f[CR]hledger CMD \-h\f[R] and looking for the
\f[CR]\-O\f[R]/\f[CR]\-\-output\-format=FMT\f[R] option,
.PP
You can select the output format by using that option:
.IP
.EX
$ hledger print \-O csv # print CSV to standard output
.EE
.PP
or by choosing a suitable filename extension with the
\f[CR]\-o\f[R]/\f[CR]\-\-output\-file=FILE.FMT\f[R] option:
.IP
.EX
$ hledger balancesheet \-o foo.csv # write CSV to foo.csv
.EE
.PP
The \f[CR]\-O\f[R] option can be combined with \f[CR]\-o\f[R] to
override the file extension if needed:
.IP
.EX
$ hledger balancesheet \-o foo.txt \-O csv # write CSV to foo.txt
.EE
.PP
Here are some notes about the various output formats.
.SS Text output
This is the default: human readable, plain text report output, suitable
for viewing with a monospace font in a terminal.
If your data contains unicode or wide characters, you\(aqll need a
terminal and font that render those correctly.
(This can be challenging on MS Windows.)
.PP
Some reports (\f[CR]register\f[R], \f[CR]aregister\f[R]) will normally
use the full window width.
If this isn\(aqt working or you want to override it, you can use the
\f[CR]\-w\f[R]/\f[CR]\-\-width\f[R] option.
.PP
Balance reports (\f[CR]balance\f[R], \f[CR]balancesheet\f[R],
\f[CR]incomestatement\f[R]...)
use whatever width they need.
Multi\-period multi\-currency reports can often be wider than the
window.
Besides using a pager, helpful techniques for this situation include
\f[CR]\-\-layout=bare\f[R], \f[CR]\-X COMM\f[R], \f[CR]cur:\f[R],
\f[CR]\-\-transpose\f[R], \f[CR]\-\-tree\f[R], \f[CR]\-\-depth\f[R],
\f[CR]\-\-drop\f[R], switching to html output, etc.
.PP
The display style of amounts (symbol placement, decimal and digit group
marks, number of decimal digits) is inferred per commodity, and can be
overridden with \f[CR]\-c/\-\-commodity\-style\f[R]; see Amount
formatting.
.SS Box\-drawing characters
hledger draws simple table borders by default, to minimise the risk of
display problems caused by a terminal/font not supporting box\-drawing
characters.
.PP
But your terminal and font probably do support them, so we recommend
using the \f[CR]\-\-pretty\f[R] flag to show prettier tables in the
terminal.
This is a good flag to add to your hledger config file.
.SS Colour
hledger tries to automatically detect ANSI colour and text styling
support and use it when appropriate.
(Currently, it is used rather minimally: some reports show negative
numbers in red, and help output uses bold text for emphasis.)
Colour is not used when the \f[CR]TERM\f[R] environment variable is
\f[CR]dumb\f[R], or \f[CR]NO_COLOR\f[R] is set, or output is not going
to a colour\-capable terminal.
.PP
You can override this by setting the \f[CR]NO_COLOR\f[R] environment
variable to disable it, or by using the \f[CR]\-\-color/\-\-colour\f[R]
option, perhaps in your config file, with a \f[CR]y\f[R]/\f[CR]yes\f[R]
or \f[CR]n\f[R]/\f[CR]no\f[R] value to force it on or off.
.SS Paging
In unix\-like environments, when displaying large output (in any output
format) in the terminal, hledger tries to use a pager when appropriate.
(You can disable this with the \f[CR]\-\-pager=no\f[R] option, perhaps
in your config file.)
.PP
The pager shows one page of text at a time, and lets you scroll around
to see more.
While it is active, usually \f[CR]SPACE\f[R] shows the next page,
\f[CR]h\f[R] shows help, and \f[CR]q\f[R] quits.
The home/end/page up/page down/cursor keys, and mouse scrolling, may
also work.
.PP
hledger will use the pager specified by the \f[CR]PAGER\f[R] environment
variable, otherwise \f[CR]less\f[R] if available, otherwise
\f[CR]more\f[R] if available.
(With one exception: \f[CR]hledger help \-p TOPIC\f[R] will always use
\f[CR]less\f[R], so that it can scroll to the topic.)
.PP
The pager is expected to display hledger\(aqs ANSI colour and text
styling.
If you see junk characters, you might need to configure your pager to
handle ANSI codes.
Or you could disable colour as described above.
.PP
If you are using the \f[CR]less\f[R] pager, hledger tries to provide a
consistently pleasant experience by running it with some extra options
added to your \f[CR]LESS\f[R] environment variable:
.PP
\-\-chop\-long\-lines \-\-hilite\-unread \-\-ignore\-case \-\-no\-init
\-\-quit\-if\-one\-screen \-\-shift=8 \-\-squeeze\-blank\-lines
\-\-use\-backslash
.PP
and when colour output is enabled:
.PP
\-\-RAW\-CONTROL\-CHARS
.PP
You can prevent this by setting your preferred options in the
\f[CR]HLEDGER_LESS\f[R] variable, which will be used instead of
\f[CR]LESS\f[R].
.SS HTML output
HTML output has some default styling built in; eg, it prevents wrapping
within dates and individual commodity amounts.
It can be customised (or overridden) by an optional
\f[CR]hledger.css\f[R] file in the same directory (there is a sample in
the hledger repo).
.PP
With \f[CR]\-\-chart\f[R], commands that can show charts show one (as
inline SVG), with the text report collapsed below it (see Balance
charts).
.PP
HTML output will be a HTML fragment, not a complete HTML document.
It has a newline after each table row, for readability.
Like other hledger output, for non\-ascii characters it will use the
system locale\(aqs text encoding (see Text encoding).
.SS CSV / TSV output
In CSV or TSV output, digit group marks (such as thousands separators)
are disabled automatically.
.SS FODS output
FODS is the OpenDocument Spreadsheet format as plain XML, as read by
LibreOffice and OpenOffice.
For those spreadsheet applications it is better than CSV.
It works across locales: decimal point or comma, and the character
encoding is stored in the XML header, so non\-ascii text is safe.
It supports fixed header rows and columns, cell types (string, number,
date), styles (bold) and borders.
And it keeps number and currency separate, so amounts show their
currency but remain numbers usable in formulas.
You can still extract CSV from FODS/ODS if needed, with utilities like
\f[CR]libreoffice \-\-headless\f[R] or ods2csv.
.PP
ODS supports only the locale\(aqs thousands separator as a digit group
mark, so FODS output enables thousands separators if your commodity
style has any digit groups.
.SS Ledger output
This is a Ledger\-specific journal format supported by the
\f[CR]print\f[R] command.
It is currently identical to hledger\(aqs default \f[CR]print\f[R]
output except that cost basis annotations will use Ledger\(aqs syntax,
(\f[CR]{COST} [DATE] (NOTE)\f[R]), not hledger\(aqs
(\f[CR]{DATE, \(dqLABEL\(dq, COST}\f[R]).
With \f[CR]print \-\-export\f[R], directives and comments are also
reproduced, and directives which Ledger does not support are commented
out.
.SS Beancount output
This is Beancount\(aqs journal format, supported by the \f[CR]print\f[R]
command.
You can use this to export your hledger data to Beancount, eg to use the
Fava web app.
.PP
hledger will try to adjust your data to suit Beancount, automatically.
By default only transactions are converted; with
\f[CR]print \-\-export\f[R], the options and \f[CR]commodity\f[R],
\f[CR]open\f[R] and \f[CR]price\f[R] directives Beancount needs are
generated too, and top\-level comments are converted, so the output can
be read by Beancount directly.
Be cautious and check the conversion until you are confident it is good.
If you plan to export to Beancount often, you may want to follow its
conventions, for a cleaner conversion:
.IP \(bu 2
use Beancount\-friendly account names
.IP \(bu 2
use currency codes instead of currency symbols
.IP \(bu 2
use cost notation instead of equity conversion postings
.IP \(bu 2
avoid virtual postings, balance assignments, and secondary dates.
.PP
There is one big adjustment: for Beancount, the top level account names
must be \f[CR]Assets\f[R], \f[CR]Liabilities\f[R], \f[CR]Equity\f[R],
\f[CR]Income\f[R], and/or \f[CR]Expenses\f[R].
A top level hledger account named \f[CR]revenue\f[R] or
\f[CR]revenues\f[R] (case insensitive) will be converted to
\f[CR]Income\f[R].
Any other top level account whose account type is known (declared or
inferred) will have the corresponding Beancount top level account
prepended; eg with \f[CR]account bonds ; type:A\f[R],
\f[CR]bonds:treasury\f[R] becomes \f[CR]Assets:Bonds:Treasury\f[R].
Otherwise, you should use \f[CR]\-\-alias\f[R] (see \f[CR]\-\-alias\f[R]
option, or this hledger2beancount.conf file).
.PP
Other adjustments hledger makes:
.IP \(bu 2
\f[B]Account names:\f[R] aside from the top\-level names, hledger makes
valid Beancount account names by capitalising each part, replacing
spaces and underscores with \f[CR]\-\f[R], replacing other unsupported
characters with \f[CR]C<HEXBYTES>\f[R], prepending \f[CR]A\f[R] to parts
which don\(aqt begin with a letter or digit, and appending \f[CR]:A\f[R]
to account names which have only one part.
.IP \(bu 2
\f[B]Commodity names:\f[R] hledger makes valid Beancount
commodity/currency names, which must be 2\-24 uppercase letters, digits,
or \f[CR]\(aq\f[R], \f[CR].\f[R], \f[CR]_\f[R], \f[CR]\-\f[R], beginning
with a letter and ending with a letter or digit.
Known currency symbols become ISO 4217 currency codes; otherwise letters
are capitalised, spaces become \f[CR]\-\f[R], other unsupported
characters become \f[CR]C<HEXBYTES>\f[R], and \f[CR]C\f[R] is prepended
or appended if needed.
One\-letter symbols are doubled, and the no\-symbol commodity becomes
\f[CR]CC\f[R].
(hledger tries to keep your commodities distinct, but collisions are
possible with short symbols like \f[CR]CC\f[R], \f[CR]C\f[R] and
no\-symbol, which are distinct in hledger but all become \f[CR]CC\f[R]
in Beancount.)
.IP \(bu 2
\f[B]Balance assignments\f[R] are not supported by Beancount, so they
are converted to explicit amounts.
.IP \(bu 2
\f[B]Virtual postings\f[R] are not allowed by Beancount, so any virtual
postings are omitted.
.IP \(bu 2
\f[B]Tags\f[R] become Beancount metadata (except tags whose name begins
with \f[CR]_\f[R]).
Metadata names are adjusted to be Beancount\-compatible: beginning with
a lowercase letter, at least two characters long, with unsupported
characters encoded; values use Beancount\(aqs string type.
A tag repeated with multiple values (eg an account with both
\f[CR]type:Asset\f[R] and \f[CR]type:Cash\f[R]) becomes one metadata
entry with the values comma separated:
\f[CR]type: \(dqAsset, Cash\(dq\f[R].
.IP \(bu 2
\f[B]Costs:\f[R] Beancount doesn\(aqt allow redundant costs and
conversion postings as hledger does; if you have any, the conversion
postings are omitted.
Currently at most one cost + conversion postings group per transaction
is supported.
.IP \(bu 2
\f[B]Directives:\f[R] with \f[CR]print \-\-export\f[R], hledger
generates a \f[CR]commodity\f[R] directive for each declared commodity,
and an \f[CR]open\f[R] directive for each declared or used account,
dated on the account\(aqs earliest posting (or the earliest transaction
date).
Account and commodity tags become metadata on these directives, and an
account\(aqs \f[CR]lots:\f[R] tag becomes its Beancount booking method.
Other hledger directives have no Beancount equivalent and are dropped.
.IP \(bu 2
\f[B]Tolerance:\f[R] with \f[CR]print \-\-export\f[R], a sample
\f[CR]inferred_tolerance_default\f[R] option is provided, commented out.
If Beancount complains that transactions aren\(aqt balanced, this is an
easy workaround.
.IP \(bu 2
\f[B]Operating currency:\f[R] declaring one or more improves Beancount
and Fava reports.
With \f[CR]print \-\-export\f[R], hledger declares each currency used in
cost amounts as an operating currency.
If needed, replace these with your own declaration, like
\f[CR]option \(dqoperating_currency\(dq \(dqUSD\(dq\f[R].
.SS SQL output
SQL output is expected to work at least with SQLite, MySQL and Postgres.
.PP
The SQL statements are expected to be executed in the empty database.
If you already have tables created via SQL output of hledger, you would
probably want to either clear data from these (via \f[CR]delete\f[R] or
\f[CR]truncate\f[R] SQL statements) or \f[CR]drop\f[R] the tables
completely before import; otherwise your postings would be duplicated.
.PP
For SQLite, it is more useful if you modify the generated \f[CR]id\f[R]
field to be a PRIMARY KEY.
Eg:
.IP
.EX
$ hledger print \-O sql | sed \(aqs/id serial/id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL/g\(aq | ...
.EE
.SS JSON output
Our JSON is rather large and verbose, since it is a faithful
representation of hledger\(aqs internal data types.
To understand its structure, read the Haskell type definitions, which
are mostly in
https://github.com/hledgerorg/hledger/blob/main/hledger\-lib/Hledger/Data/Types.hs.
hledger\-web\(aqs OpenAPI specification may also be relevant.
.PP
hledger stores numbers with sometimes up to 255 significant digits.
This is too many digits for most JSON consumers, so in JSON output we
round numbers to at most 10 decimal places.
(We don\(aqt limit the number of integer digits.)
Related: #1195
.SS SVG output
SVG output shows a chart of the report, rather than the report\(aqs
table (as the \f[CR]\-\-chart\f[R] flag does with text output; see
Balance charts).
It is a self\-contained image file, viewable in web browsers and many
image viewers.
It has a light and a dark colour scheme, chosen by the viewer\(aqs
preference, and tooltips showing each bar\(aqs or point\(aqs values.
Currently the \f[CR]aregister\f[R], \f[CR]balance\f[R],
\f[CR]balancesheet\f[R], \f[CR]balancesheetequity\f[R],
\f[CR]cashflow\f[R], \f[CR]incomestatement\f[R] and \f[CR]register\f[R]
commands can produce it.
Eg:
.IP
.EX
$ hledger bal \-M expenses \-o expenses.svg
.EE
.SS Debug output
We intend hledger to be relatively easy to troubleshoot, introspect and
develop.
You can add \f[CR]\-\-debug[=N]\f[R] to any hledger command line to see
additional debug output.
N ranges from 1 (least output, the default) to 9 (maximum output).
Typically you would start with 1 and increase until you are seeing
enough.
At level 1 or higher, the output includes timing lines, showing the run
time and memory allocation of each phase of hledger\(aqs work: reading
and parsing data, each stage of journal finalising, and running the
command.
These can show where the time goes when processing a large journal.
Debug output goes to stderr, and is not affected by
\f[CR]\-o/\-\-output\-file\f[R] (unless you redirect stderr to stdout,
eg: \f[CR]2>&1\f[R]).
It will be interleaved with normal output, which can help reveal when
parts of the code are evaluated.
To capture debug output in a log file instead, you can usually redirect
stderr, eg:
.IP
.EX
hledger bal \-\-debug=3 2>hledger.log
.EE
.PP
(This option doesn\(aqt work in a config file yet.)
.SS Built\-in tests
hledger\(aqs unit tests are built in to the executable, and
\f[CR]\-\-test\f[R] runs them, printing the results and exiting with a
non\-zero code if any fail.
\f[CR]\-\-test=PATTERN\f[R] runs just the tests whose names contain
PATTERN (it can also be a tasty pattern).
Eg:
.IP
.EX
$ hledger \-\-test # run all unit tests
$ hledger \-\-test=balance # run tests with \(dqbalance\(dq in their name
.EE
.PP
This can be a sanity check of an unusual hledger build; failures are
unlikely, but if you see one, please report it as a bug.
(hledger\-web also has a \f[CR]\-\-test\f[R] flag, which runs its own
tests.)
.SH Charts
hledger can show many reports as a chart: add \f[CR]\-\-chart\f[R] to a
\f[CR]balance\f[R], \f[CR]balancesheet\f[R],
\f[CR]balancesheetequity\f[R], \f[CR]cashflow\f[R],
\f[CR]incomestatement\f[R], \f[CR]aregister\f[R], \f[CR]register\f[R] or
\f[CR]holdings\f[R] report.
(The \f[CR]activity\f[R] command always shows one.)
A suitable kind of chart is chosen for the report: eg stacked bars per
period for balance changes, lines for balances over time, or a bar per
account for a single period.
In the terminal the chart is drawn with text characters, filling the
terminal\(aqs width (or the width set by \f[CR]\-w\f[R]):
.IP
.EX
$ hledger bal \-Q expenses income \-\-chart \-w 50
Balance changes in 2008:
░ expenses:food ▒ expenses:supplies
█ income:gifts ▓ income:salary
2008Q1 $\-1 ▓▓▓▓▓▓▓▓▓▓▓▓│
2008Q2 $1 ████████████│░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒
2008Q3 0 │
2008Q4 0 │
.EE
.PP
With SVG output (eg \f[CR]\-o chart.svg\f[R]) it is a graphical chart;
with HTML output it is shown with the report\(aqs table collapsed below
it; and with CSV, TSV or JSON output you get the chart\(aqs data.
To see a graphical chart quickly, add \f[CR]\-\-view\f[R], eg
\f[CR]hledger is \-M \-\-chart \-\-view\f[R].
\f[CR]\-\-chart\f[R] also accepts a chart kind, \f[CR]net\f[R] (to draw
the net total, which charts leave out by default), and a fixed scale, eg
to compare charts.
For the details, see Balance charts, aregister, Register charts and
Holdings charts.
.SH Command line tips
Here are some tips for using hledger at the command line; feel free to
skip these until you need them.
.SS Special characters
In commands you type at the command line, certain characters have
special meaning and sometimes need to be \(dqescaped\(dq or
\(dqquoted\(dq, by prefixing backslashes or enclosing in quotes.
.PP
If you are able to minimise the use of special characters in your data,
you won\(aqt have to deal with this as much.
For example, you could use hyphen \f[CR]\-\f[R] or underscore
\f[CR]_\f[R] instead of spaces in account names, and you could use the
\f[CR]USD\f[R] currency code instead of the \f[CR]$\f[R] currency symbol
in amounts.
.PP
But if you prefer to use spaced account names and \f[CR]$\f[R], it\(aqs
fine.
Just be aware of this topic so you can check this doc when needed.
(These examples are mostly tested on unix; some details might need to be
adapted if you\(aqre on Windows.)
.SS Escaping shell special characters
These are some characters which may have special meaning to your shell
(the program which interprets command lines):
.IP \(bu 2
SPACE, \f[CR]<\f[R], \f[CR]>\f[R], \f[CR](\f[R], \f[CR])\f[R],
\f[CR]|\f[R], \f[CR]\(rs\f[R], \f[CR]%\f[R]
.IP \(bu 2
\f[CR]$\f[R] if followed by a word character
.PP
So for example, to match an account name containing spaces, like
\(dqcredit card\(dq, don\(aqt write:
.IP
.EX
$ hledger register credit card
.EE
.PP
Instead, enclose the name in single quotes:
.IP
.EX
$ hledger register \(aqcredit card\(aq
.EE
.PP
On unix or in Windows powershell, if you use double quotes your shell
will silently treat \f[CR]$\f[R] as variable interpolation.
So you should probably avoid double quotes, unless you want that
behaviour, eg in a script:
.IP
.EX
$ hledger register \(dqassets:$SOMEACCT\(dq
.EE
.PP
But in an older Windows CMD.EXE window, you must use double quotes:
.IP
.EX
C:\(rsUsers\(rsMe> hledger register \(dqcredit card\(dq
.EE
.PP
On unix or in Windows powershell, as an alternative to quotes you can
write a backslash before each special character:
.IP
.EX
$ hledger register credit\(rs card
.EE
.PP
Finally, since hledger\(aqs query arguments are regular expressions
(described below), you could also fill that gap with \f[CR].\f[R] which
matches any character:
.IP
.EX
$ hledger register credit.card
.EE
.SS Escaping regular expression special characters
Some characters also have special meaning in regular expressions, which
hledger\(aqs arguments often are.
Those include:
.IP \(bu 2
\f[CR].\f[R], \f[CR]\(ha\f[R], \f[CR]$\f[R], \f[CR][\f[R], \f[CR]]\f[R],
\f[CR](\f[R], \f[CR])\f[R], \f[CR]|\f[R], \f[CR]\(rs\f[R]
.PP
To escape one of these, write \f[CR]\(rs\f[R] before it.
But note this is in addition to the shell escaping above.
So for characters which are special to both shell and regular
expressions, like \f[CR]\(rs\f[R] and \f[CR]$\f[R], you will sometimes
need two levels of escaping.
.PP
For example, a balance report that uses a \f[CR]cur:\f[R] query
restricting it to just the $ currency, should be written like this:
.IP
.EX
$ hledger balance cur:\(rs\(rs$
.EE
.PP
Explanation:
.IP "1." 3
Add a backslash \f[CR]\(rs\f[R] before the dollar sign \f[CR]$\f[R] to
protect it from regular expressions (so it will be matched literally
with no special meaning).
.IP "2." 3
Add another backslash before that backslash, to protect it from the
shell (so the shell won\(aqt consume it).
.IP "3." 3
\f[CR]$\f[R] doesn\(aqt need to be protected from the shell in this
case, because it\(aqs not followed by a word character; but it would be
harmless to do so.
.PP
But here\(aqs another way to write that, which tends to be easier: add
backslashes to escape from regular expressions, then enclose with quotes
to escape from the shell:
.IP
.EX
$ hledger balance cur:\(aq\(rs$\(aq
.EE
.SS Escaping in other situations
hledger options and arguments are sometimes used in places other than
the command line, where the escaping/quoting rules are different.
For example, backslash\-quoting may not be available.
Here\(aqs a quick reference:
.PP
.TS
tab(@);
lw(17.5n) lw(52.5n).
T{
In unix shell
T}@T{
Use single quotes and/or backslash (or double quotes for variable
interpolation)
T}
T{
In Windows \f[CR]powershell\f[R]
T}@T{
Use single quotes (or double quotes for variable interpolation)
T}
T{
In Windows \f[CR]cmd\f[R]
T}@T{
Use double quotes
T}
T{
In hledger\-ui\(aqs filter prompt
T}@T{
Use single or double quotes
T}
T{
In hledger\-web\(aqs search form
T}@T{
Use single or double quotes
T}
T{
In an argument file
T}@T{
Don\(aqt use spaces, don\(aqt shell\-escape, do regex\-escape, write one
argument/option per line
T}
T{
In a config file
T}@T{
Use single or double quotes, enclosing all or part of an argument
(\f[CR]\(aqdesc:a b\(aq\f[R] or \f[CR]desc:\(aqa b\(aq\f[R], as in the
unix shell)
T}
T{
In \f[CR]repl\f[R] or a \f[CR]run\f[R] script
T}@T{
Use single or double quotes, enclosing all or part of an argument
T}
T{
In \f[CR]ghci\f[R] (the Haskell REPL)
T}@T{
Use double quotes, and enclose the whole argument
T}
.TE
.SS Unicode characters
hledger is expected to handle non\-ascii characters correctly:
.IP \(bu 2
they should be parsed correctly in input files and on the command line,
by all hledger tools (add, iadd, hledger\-web\(aqs search/add/edit
forms, etc.)
.IP \(bu 2
they should be displayed correctly by all hledger tools, and on\-screen
alignment should be preserved.
.PP
This requires a well\-configured environment.
Here are some tips:
.IP \(bu 2
A system locale must be configured, which can decode the characters
being used.
This is essential \- see Text encoding and Install: Text encoding.
.IP \(bu 2
Your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)
must support unicode.
On Windows, you may need to use Windows Terminal.
.IP \(bu 2
The terminal must be using a font which includes the required unicode
glyphs.
.IP \(bu 2
The terminal should be configured to display wide characters as double
width (for report alignment).
.IP \(bu 2
On Windows, for best results you should run hledger in the same kind of
environment in which it was built.
Eg hledger built in the standard CMD.EXE environment (like the binaries
on our download page) might show display problems when run in a cygwin
or msys terminal, and vice versa.
(See eg #961).
.SS Regular expressions
A regular expression (regexp) is a small piece of text where certain
characters (like \f[CR].\f[R], \f[CR]\(ha\f[R], \f[CR]$\f[R],
\f[CR]+\f[R], \f[CR]*\f[R], \f[CR]()\f[R], \f[CR]|\f[R], \f[CR][]\f[R],
\f[CR]\(rs\f[R]) have special meanings, forming a tiny language for
matching text precisely \- very useful in hledger and elsewhere.
To learn all about them, visit regular\-expressions.info.
.PP
hledger supports regexps whenever you are entering a pattern to match
something, eg in query arguments, account aliases, CSV if rules,
hledger\-web\(aqs search form, hledger\-ui\(aqs \f[CR]/\f[R] search,
etc.
You may need to wrap them in quotes, especially at the command line (see
Special characters above).
Here are some examples:
.PP
Account name queries (quoted for command line use):
.IP
.EX
Regular expression: Matches:
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
bank assets:bank, assets:bank:savings, expenses:art:banksy, ...
:bank assets:bank:savings, expenses:art:banksy
:bank: assets:bank:savings
\(aq\(habank\(aq none of those ( \(ha matches beginning of text )
\(aqbank$\(aq assets:bank ( $ matches end of text )
\(aqbig \(rs$ bank\(aq big $ bank ( \(rs disables following character\(aqs special meaning )
\(aq\(rsbbank\(rsb\(aq assets:bank, assets:bank:savings ( \(rsb matches word boundaries )
\(aq(sav|check)ing\(aq saving or checking ( (|) matches either alternative )
\(aqsaving|checking\(aq saving or checking ( outer parentheses are not needed )
\(aqsavings?\(aq saving or savings ( ? matches 0 or 1 of the preceding thing )
\(aqmy +bank\(aq my bank, my bank, ... ( + matches 1 or more of the preceding thing )
\(aqmy *bank\(aq mybank, my bank, my bank, ... ( * matches 0 or more of the preceding thing )
\(aqb.nk\(aq bank, bonk, b nk, ... ( . matches any character )
.EE
.PP
Some other queries:
.IP
.EX
desc:\(aqamazon|amzn|audible\(aq Amazon transactions
cur:EUR amounts with commodity symbol EUR
cur:\(rs\(rs$ amounts with commodity symbol $
cur:....? amounts with 3\- or 4\-character symbols
tag:.=202[1\-3] things with any tag whose value contains 2021, 2022 or 2023
.EE
.PP
Account name aliases: accept \f[CR].\f[R] instead of \f[CR]:\f[R] as
account separator:
.IP
.EX
alias /\(rs./=: replaces all periods in account names with colons
.EE
.PP
Show multiple top\-level accounts combined as one:
.IP
.EX
\-\-alias=\(aq/\(ha[\(ha:]+/=combined\(aq ( [\(ha:] matches any character other than : )
.EE
.PP
Show accounts with the second\-level part removed:
.IP
.EX
\-\-alias \(aq/\(ha([\(ha:]+):[\(ha:]+/ = \(rs1\(aq
match a top\-level account and a second\-level account
and replace those with just the top\-level account
( \(rs1 in the replacement text means \(dqwhatever was matched
by the first parenthesised part of the regexp\(dq
.EE
.PP
CSV rules: match CSV records containing dining\-related MCC codes:
.IP
.EX
if \(rs?MCC581[124]
.EE
.PP
Match CSV records with a specific amount around the end/start of month:
.IP
.EX
if %amount \(rsb3\(rs.99
& %date (29|30|31|01|02|03)$
.EE
.SS hledger\(aqs regular expressions
hledger\(aqs regular expressions come from the regex\-tdfa library.
If they\(aqre not doing what you expect, it\(aqs important to know
exactly what they support:
.IP "1." 3
they are case insensitive
.IP "2." 3
they are infix matching (they do not need to match the entire thing
being matched)
.IP "3." 3
they are POSIX ERE (extended regular expressions)
.IP "4." 3
they also support GNU word boundaries (\f[CR]\(rsb\f[R],
\f[CR]\(rsB\f[R], \f[CR]\(rs<\f[R], \f[CR]\(rs>\f[R])
.IP "5." 3
backreferences are supported when doing text replacement in account
aliases or CSV rules, where backreferences can be used in the
replacement string to reference capturing groups in the search regexp.
Otherwise, if you write \f[CR]\(rs1\f[R], it will match the digit
\f[CR]1\f[R].
.IP "6." 3
they do not support lazy quantifiers (\f[CR]*?\f[R]), mode modifiers
(\f[CR](?s)\f[R]), character classes (\f[CR]\(rsw\f[R],
\f[CR]\(rsd\f[R]), or anything else not mentioned above.
.IP "7." 3
they may not (I\(aqm guessing not) properly support right\-to\-left or
bidirectional text.
.PP
Some things to note:
.IP \(bu 2
In the \f[CR]alias\f[R] directive and \f[CR]\-\-alias\f[R] option,
regular expressions must be enclosed in forward slashes
(\f[CR]/REGEX/\f[R]).
Elsewhere in hledger, these are not required.
.IP \(bu 2
In queries, to match a regular expression metacharacter like
\f[CR]$\f[R] as a literal character, prepend a backslash.
Eg to search for amounts with the dollar sign in hledger\-web, write
\f[CR]cur:\(rs$\f[R].
.IP \(bu 2
On the command line, some metacharacters like \f[CR]$\f[R] have a
special meaning to the shell and so must be escaped at least once more.
See Special characters.
.SS Argument files
You can save a set of command line options and arguments in a file, and
then use them by writing \f[CR]\(atFILE.args\f[R] as a hledger command
argument.
The \f[CR].args\f[R] file extension is conventional, but not required.
In an argument file,
.IP \(bu 2
Each line can contain one argument, flag, or option.
.IP \(bu 2
Blank lines or lines beginning with \f[CR]#\f[R] are ignored.
.IP \(bu 2
An option\(aqs flag and value should be joined by \f[CR]=\f[R].
.IP \(bu 2
An option value or an argument may contain spaces.
Don\(aqt use single or double quotes.
.IP \(bu 2
And generally, use one less level of quoting/escaping than at the
command line.
Eg \f[CR]cur:\(rs$\f[R], not \f[CR]cur:\(rs\(rs$\f[R] as on the command
line.
.PP
For example:
.IP
.EX
# cash.args
assets:cash
assets:charles schwab:sweep
cur:\(rs$
\-c=$1.
.EE
.IP
.EX
$ hledger bal \(atcash.args
.EE
.SS Shell completions
If you use the bash, zsh or fish shells, you can optionally set up
context\-sensitive autocompletion for hledger command lines.
Try pressing \f[CR]hledger<SPACE><TAB><TAB>\f[R] (should list all
hledger commands) or \f[CR]hledger reg acct:<TAB><TAB>\f[R] (should list
your top\-level account names).
If completions aren\(aqt working, or for more details, see Install >
Shell completions.
.SH PART 6: COMMON TASKS
For a gentle, step by step introduction to hledger \- installing,
starting a journal, recording transactions, and running the main reports
\- see hledger by example on the website.
For a faster tour, see the 5 minute quick start.
Here are a few more tasks which aren\(aqt covered there.
.SH Setting LEDGER_FILE
hledger looks for your accounting data in a journal file,
\f[CR]$HOME/.hledger.journal\f[R] by default.
You can override this by setting the \f[CR]LEDGER_FILE\f[R] environment
variable (see Environment), eg to \f[CR]\(ti/finance/main.journal\f[R].
Here\(aqs how to do that on different systems:
.SS Set LEDGER_FILE on unix
It depends on your shell, but running these commands in the terminal
will work for many people; adapt if needed:
.IP
.EX
$ echo \(aqexport LEDGER_FILE=\(ti/finance/main.journal\(aq >> \(ti/.profile
$ source \(ti/.profile
.EE
.PP
When correctly configured:
.IP \(bu 2
\f[CR]env | grep LEDGER_FILE\f[R] will show your new setting
.IP \(bu 2
and so should \f[CR]hledger setup\f[R] and \f[CR]hledger files\f[R].
.SS Set LEDGER_FILE on mac
In a terminal window, follow the unix procedure above.
.PP
Note GUI applications started from the Dock or Spotlight, such as a GUI
Emacs, don\(aqt see variables set in your shell profile.
If needed, you can set the variable for them too, until the next reboot,
with \f[CR]launchctl setenv LEDGER_FILE \(ti/finance/main.journal\f[R]
(then restart the application).
.SS Set LEDGER_FILE on Windows
It can be easier to create a default file at
\f[CR]C:\(rsUsers\(rsUSER\(rs.hledger.journal\f[R], and have it include
your other files.
See I\(aqm on Windows, how do I keep my files in
\f[CR]AppData\(rsRoaming\f[R] ?
.PP
Otherwise: using the gui is easiest:
.IP "1." 3
In task bar, search for \f[CR]environment variables\f[R], and choose
\(dqEdit environment variables for your account\(dq.
.IP "2." 3
Create or change a \f[CR]LEDGER_FILE\f[R] setting in the User variables
pane.
A typical value would be
\f[CR]C:\(rsUsers\(rsUSER\(rsfinance\(rsmain.journal\f[R].
.IP "3." 3
Click OK to complete the change.
.IP "4." 3
And open a new powershell window.
(Existing windows won\(aqt see the change.)
.PP
Or at the command line, you can do it this way:
.IP "1." 3
In a powershell window, run
\f[CR][Environment]::SetEnvironmentVariable(\(dqLEDGER_FILE\(dq, \(dqC:\(rsUser\(rsUSER\(rsfinance\(rsmain.journal\(dq, [System.EnvironmentVariableTarget]::User)\f[R]
.IP "2." 3
And open a new powershell window.
(Existing windows won\(aqt see the change.)
.PP
Other methods you may find online are often unreliable: they may not
persist, may not affect the current window, or may need administrator
rights or a newer powershell.
If you still have trouble, see eg Setting Windows PowerShell environment
variables or Adding path permanently to windows using powershell
doesn\(aqt appear to work.
.PP
When correctly configured:
.IP \(bu 2
in a new powershell window, \f[CR]$env:LEDGER_FILE\f[R] will show your
new setting
.IP \(bu 2
and so should \f[CR]hledger setup\f[R] and (once the file exists)
\f[CR]hledger files\f[R].
.SH Reconciling
Periodically you should reconcile \- compare your hledger\-reported
balances against external sources of truth, like bank statements or your
bank\(aqs website \- to be sure that your ledger accurately represents
the real\-world balances (and, that the real\-world institutions have
not made a mistake!).
This gets easy and fast with (1) practice and (2) frequency.
If you do it daily, it can take 2\-10 minutes.
If you let it pile up, expect it to take longer as you hunt down errors
and discrepancies.
.PP
A typical workflow:
.IP "1." 3
Reconcile cash.
Count what\(aqs in your wallet.
Compare with what hledger reports (\f[CR]hledger bal cash\f[R]).
If they are different, try to remember the missing transaction, or look
for the error in the already\-recorded transactions.
A register report can be helpful (\f[CR]hledger reg cash\f[R]).
If you can\(aqt find the error, add an adjustment transaction.
Eg if you have $105 in your wallet but hledger says $107, and can\(aqt
explain the missing $2, it could be:
.RS 4
.IP
.EX
2023\-01\-16 * adjust cash
assets:cash $\-2 = $105
expenses:misc
.EE
.RE
.IP "2." 3
Reconcile checking.
Log in to your bank\(aqs website.
Compare today\(aqs (cleared) balance with hledger\(aqs cleared balance
(\f[CR]hledger bal checking \-C\f[R]).
If they are different, track down the error or record the missing
transaction(s) or add an adjustment transaction, similar to the above.
Unlike the cash case, you can usually compare the transaction history
and running balance from your bank with the one reported by
\f[CR]hledger reg checking \-C\f[R].
This will be easier if you generally record transaction dates quite
similar to your bank\(aqs clearing dates.
.IP "3." 3
Repeat for other asset/liability accounts.
.PP
Tip: an institution\(aqs numbers can be rounded differently in different
places \- its website, its CSV or other exports, its emailed and paper
statements.
Choose one as your reference (usually the official statement), and aim
to reproduce its numbers: adjust hledger\(aqs display precision with
\f[CR]\-c\f[R] or \f[CR]\-\-round\f[R] (see Display rounding), and
record any small remaining differences with an adjustment transaction,
eg to an \f[CR]expenses:rounding\f[R] account.
.PP
Tip: instead of the register command, use hledger\-ui to see a
live\-updating register while you edit the journal:
\f[CR]hledger\-ui \-\-register checking \-C\f[R]
.PP
After reconciling, it could be a good time to mark the reconciled
transactions\(aq status as \(dqcleared and confirmed\(dq, if you want to
track that, by adding the \f[CR]*\f[R] marker after the date.
.PP
If you\(aqre using version control, this can be a good time to commit:
.IP
.EX
$ git commit \-m \(aqtxns\(aq 2023.journal
.EE
.SH Closing a journal file
At the end of the year, you may want to continue your journal in a new
file, so that old transactions don\(aqt slow down or clutter your
reports, and to help ensure the integrity of your accounting history.
See the close command.
.PP
If using version control, don\(aqt forget to \f[CR]git add\f[R] the new
file.
.SH hledger 1 and hledger 2
hledger 2 (the 1.99.x previews, and 2.0 when released) reads hledger 1
data, and most hledger 1 journals work unchanged.
hledger 1 (1.52.x) continues to receive essential fixes, and both can be
installed side by side (eg by renaming the hledger 1 executable to
\f[CR]hledger1\f[R]).
.PP
To upgrade from hledger 1:
.IP "1." 3
Back up your data files, or commit them to version control.
.IP "2." 3
Run \f[CR]hledger check\f[R] with hledger 2.
If you import CSV, also run your usual import command with
\f[CR]\-\-dry\-run\f[R].
.IP "3." 3
Compare your usual reports with hledger 1\(aqs (eg
\f[CR]hledger1 bs\f[R] and \f[CR]hledger bs\f[R]), and investigate any
differences.
.PP
Things that can need attention include cost basis annotations like
\f[CR]{$50}\f[R], which hledger 1 ignored but hledger 2 uses to track
lots, and a few checks that are now stricter.
Upgrading to hledger 2 describes them all, with fixes, and how to switch
back, or keep data usable with both versions.
.SH BUGS
We welcome bug reports in the hledger issue tracker
(https://bugs.hledger.org), or on the hledger chat or mail list
(https://hledger.org/support).
.PP
Some known issues and limitations:
.PP
hledger uses the system\(aqs text encoding when reading non\-ascii text.
If no system encoding is configured, or if the data\(aqs encoding is
different, hledger will give an error.
(See Text encoding and Troubleshooting.)
.PP
On Microsoft Windows, depending what kind of terminal window you use,
non\-ascii characters, ANSI text formatting, and/or the add command\(aqs
TAB key, may not be fully supported.
(For best results, try a powershell window.)
.PP
When showing colour, hledger sometimes asks the terminal for its
background colour, to choose colours that suit it (for headings, and for
charts in terminals advertising 24\-bit colour).
Occasionally this can misbehave: a terminal that doesn\(aqt answer (eg
some tmux setups) can delay the output by up to half a second; over a
slow connection, a late answer may appear as stray characters at your
shell prompt; on macOS, hledger can hang if its input is explicitly
redirected from \f[CR]/dev/tty\f[R]; and hledger may be stopped if it is
run in the background.
\f[CR]\-\-color=no\f[R] avoids these.
.PP
When processing large data files, hledger uses more memory than Ledger.
You can cap its memory use with GHC runtime system options, eg
\f[CR]hledger +RTS \-M2G \-RTS ...\f[R] (if it needs more, it will stop
with an error), and see memory and garbage collection statistics with
\f[CR]+RTS \-s \-RTS\f[R].
To use less memory at some cost in speed, add \f[CR]+RTS \-c \-RTS\f[R]
to use the compacting garbage collector; on large journals this can
reduce memory use by 20\-40%, while running 40\-60% slower.
(A RTS \f[CR]\-M\f[R] limit also enables this automatically, as memory
use approaches the limit.)
A multi\-period report with more than 10,000 periods, or a
\f[CR]\-\-forecast\f[R] that would generate more than 100,000
transactions (which in practice means a mistyped date somewhere, making
the report or the forecast span thousands of years), prints a warning
before starting, since it may need a lot of memory, so that you can
cancel it.
.SS Troubleshooting
Here are some common issues you might encounter when you run hledger,
and how to resolve them (and remember also you can usually get quick
Support):
.PP
\f[B]PATH issues: I get an error like \(dqNo command \(aqhledger\(aq
found\(dq\f[R]
.PD 0
.P
.PD
Depending how you installed hledger, the executables may not be in your
shell\(aqs PATH.
Eg on unix systems, stack installs hledger in \f[CR]\(ti/.local/bin\f[R]
and cabal installs it in \f[CR]\(ti/.cabal/bin\f[R].
You may need to add one of these directories to your shell\(aqs PATH,
and/or open a new terminal window.
.PP
\f[B]LEDGER_FILE issues: I configured LEDGER_FILE but hledger is not
using it\f[R]
.PD 0
.P
.PD
.IP \(bu 2
\f[CR]LEDGER_FILE\f[R] should be a real environment variable, not just a
shell variable.
Eg on unix, the command \f[CR]env | grep LEDGER_FILE\f[R] should show
it.
You may need to use \f[CR]export\f[R] (see
https://stackoverflow.com/a/7411509).
On Windows, \f[CR]$env:LEDGER_FILE\f[R] should show it.
.IP \(bu 2
You may need to force your shell to see the new configuration.
A simple way is to close your terminal window and open a new one.
.PP
\f[B]Text decoding issues: I get errors like \(dqIllegal byte
sequence\(dq or \(dqInvalid or incomplete multibyte or wide
character\(dq or \(dqcommitAndReleaseBuffer: invalid argument (invalid
character)\(dq\f[R]
.PD 0
.P
.PD
hledger usually needs its input to be decodable with the system
locale\(aqs text encoding.
See Text encoding and Install: Text encoding.
.PP
\f[B]COMPATIBILITY ISSUES: hledger gives an error with my Ledger
file\f[R]
.PD 0
.P
.PD
Not all of Ledger\(aqs journal file syntax or feature set is supported.
See hledger and Ledger for full details.
.SH AUTHORS
Simon Michael <simon@joyful.com> and contributors.
.br
See http://hledger.org/CREDITS.html
.SH COPYRIGHT
Copyright 2007-2023 Simon Michael and contributors.
.SH LICENSE
Released under GNU GPL v3 or later.
.SH SEE ALSO
hledger(1), hledger\-ui(1), hledger\-web(1), ledger(1)