• Front Matter

\input texinfo @c -*-texinfo-*- @setfilename ledger.info @settitle Ledger: Command-Line Accounting @dircategory User Applications

• Content

@copying Copyright (c) 2003-2009, John Wiegley. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation a...

• Introduction

@chapter Introduction

• Content

Ledger is an accounting tool with the moxie to exist. It provides no bells or whistles, and returns the user to the days before user interfaces were even a twinkling in their father's CRT. What it does offer is a double-entry accounting ledger with all the flexibility and muscle of its modern day cousins, without any of the fat. Think of it as the Bran Muffin of accounting tools. To use it, you need to start keeping a ledger. This is the basis of all accounting, and if you haven't started y...

• More introduction

@section More introduction

• Content

The most important part of accounting is keeping a good ledger. If you have a good ledger, tools can be written to work whatever mathematically tricks you need to better understand your spending patterns. Without a good ledger, no tool, however smart, can help you. The Ledger program aims at making ledger transaction as simple as possible. Since it is a command-line tool, it does not provide a user interface for keeping a ledger. If you like, you may use GnuCash to maintain your ledger, in w...

• Building the program

@section Building the program

• Content

Ledger is written in ANSI C++, and should compile on any platform. It depends on the GNU multiprecision integer library (libgmp), and the Perl regular expression library (libpcre). It was developed using GNU make and gcc 3.3, on a PowerBook running OS/X. To build and install once you have these libraries on your system, enter these commands: @example ./configure && make install @end example

• Getting help

@section Getting help

• Content

If you need help on how to use Ledger, or run into problems, you can just the Ledger mailing list at the following Web address: @example https://lists.sourceforge.net/lists/listinfo/ledger-discuss @end example You can also find help at the @samp{#ledger} channel on the IRC server @samp{irc.freenode.net}.

• Quick Reference

@chapter Quick Reference

• Content

This chapter describes ledger's features and serves as a quick reference. You may wish to survey this to get an overview before diving in to the @ref{Ledger Tutorial} and more detailed examples that follow. Ledger has a very simple command-line interface, named---enticing enough---@command{ledger}. It supports a few reporting commands, and a large number of options for refining the output from those commands. The basic syntax of any ledger command is: @example ledger [OPTIONS...] COMMAND [ARG...

• Commands

@section Commands

• balance

@subsection balance

• Content

The @command{balance} command reports the current balance of all accounts. It accepts a list of optional regexps, which confine the balance report to the matching accounts. If an account contains multiple types of commodities, each commodity's total is reported separately.

• register

@subsection register

• Content

The @command{register} command displays all the postings occurring in a single account, line by line. The account regexp must be specified as the only argument to this command. If any regexps occur after the required account name, the register will contain only those postings that match. Very useful for hunting down a particular posting. The output from @command{register} is very close to what a typical checkbook, or single-account ledger, would look like. It also shows a running balance. ...

• print

@subsection print

• Content

The @command{print} command prints out ledger transactions in a textual format that can be parsed by Ledger. They will be properly formatted, and output in the most economic form possible. The ``print'' command also takes a list of optional regexps, which will cause only those postings which match in some way to be printed. The @command{print} command can be a handy way to clean up a ledger file whose formatting has gotten out of hand.

• output

@subsection output

• Content

The @command{output} command is very similar to the @command{print} command, except that it attempts to replicate the specified ledger file epostly. The format of the command is: @example ledger -f FILENAME output FILENAME @end example Where @file{FILENAME} is the name of the ledger file to output. The reason for specifying this command is that only transactions contained within that file will be output, and not an included transactions (as can happen with the @command{print} command).

• xml

@subsection xml

• Content

The @command{xml} command outputs results similar to what @command{print} and @command{register} display, but as an XML form. This data can then be read in and processed. Use the @option{--totals} option to include the running total with each posting.

• emacs

@subsection emacs

• Content

The @command{emacs} command outputs results in a form that can be read directly by Emacs Lisp. The format of the sexp is: @example ((BEG-POS CLEARED DATE CODE PAYEE (ACCOUNT AMOUNT)...) ; list of postings ...) ; list of transactions @end example

• equity

@subsection equity

• Content

The @command{equity} command prints out accounts balances as if they were transactions. This makes it easy to establish the starting balances for an account, such as when @ref{Archiving previous years}.

• prices

@subsection prices

• Content

The @command{prices} command displays the price history for matching commodities. The @option{-A} flag is useful with this report, to display the running average price, or @option{-D} to show each price's deviation from that average. There is also a @command{pricesdb} command which outputs the same information as @command{prices}, but does in a format that can be parsed by Ledger.

• xact

@subsection xact

• Content

The @command{xact} commands simplifies the creation of new transactions. It works on the principle that 80% of all postings are variants of earlier postings. Here's how it works: Say you currently have this posting in your ledger file: @smallexample 2004/03/15 * Viva Italiano Expenses:Food $12.45 Expenses:Tips $2.55 Liabilities:MasterCard $-15.00 @end smallexample Now it's @samp{2004/4/9}, and you've just eating at @samp{Vi...

• Options

@section Options

• Content

With all of the reports, command-line options are useful to modify the output generated. These command-line options always occur before the command word. This is done to distinguish options from exclusive regular expressions, which also begin with a dash. The basic form for most commands is: @example ledger [OPTIONS] COMMAND [REGEXPS...] [-- [REGEXPS...]] @end example The @var{OPTIONS} and @var{REGEXPS} expressions are both optional. You could just use @samp{ledger balance}, without any opt...

• Basic options

@subsection Basic options

• Content

These are the most basic command options. Most likely, the user will want to set them using environment variables (see @ref{Options}), instead of using actual command-line options: @option{--help} (@option{-h}) prints a summary of all the options, and what they are used for. This can be a handy way to remember which options do what. This help screen is also printed if ledger is run without a command. @option{--version} (@option{-v}) prints the current version of ledger and exits. This is u...

• Report filtering

@subsection Report filtering

• Content

These options change which postings affect the outcome of a report, in ways other than just using regular expressions: @option{--current}(@option{-c}) displays only transactions occurring on or before the current date. @option{--begin DATE} (@option{-b DATE}) constrains the report to transactions on or after @var{DATE}. Only transactions after that date will be calculated, which means that the running total in the balance report will always start at zero with the first matching transaction. ...

• Output customization

@subsection Output customization

• Content

These options affect only the output, but not which postings are used to create it: @option{--collapse} (@option{-n}) causes transactions in a @command{register} report with multiple postings to be collapsed into a single, subtotaled transaction. @option{--subtotal} (@option{-s}) causes all transactions in a @command{register} report to be collapsed into a single, subtotaled transaction. @option{--by-payee} (@option{-P}) reports subtotals by payee. @option{--comm-as-payee} (@option{-x}) chan...

• Commodity reporting

@subsection Commodity reporting

• Content

These options affect how commodity values are displayed: @option{--price-db FILE} sets the file that is used for recording downloaded commodity prices. It is always read on startup, to determine historical prices. Other settings can be placed in this file manually, to prevent downloading quotes for a specific, for example. This is done by adding a line like the following: @example ; Don't download quotes for the dollar, or timelog values N $ N h @end example @option{--price-exp MINS} (@opt...

• Environment variables

@subsection Environment variables

• Content

Every option to ledger may be set using an environment variable. If an option has a long name such @option{--this-option}, setting the environment variable @env{LEDGER_THIS_OPTION} will have the same affect as specifying that option on the command-line. Options on the command-line always take precedence over environment variable settings, however. Note that you may also permanently specify option values by placing option settings in the file @file{~/.ledgerrc}, for example: @example --cache ...

• Period expressions

@section Period expressions

• Content

A period expression indicates a span of time, or a reporting interval, or both. The full syntax is: @example [INTERVAL] [BEGIN] [END] @end example The optional @var{INTERVAL} part may be any one of: @example every day every week every monthly every quarter every year every N days # N is any integer every N weeks every N months every N quarters every N years daily weekly biweekly monthly bimonthly quarterly yearly @end example After the interval, a begin time, end time, both or neither m...

• Format strings

@section Format strings

• Content

Format strings may be used to change the output format of reports. They are specified by passing a formatting string to the @option{--format} (@option{-F}) option. Within that string, constructs are allowed which make it possible to display the various parts of an account or posting in custom ways. Within a format strings, a substitution is specified using a percent character (@samp{%}). The basic format of all substitutions is: @example %[-][MIN WIDTH][.MAX WIDTH]EXPR @end example If the o...

• Value expressions

@section Value expressions

• Content

Value expressions are an expression language used by Ledger to calculate values used by the program for many different purposes: @enumerate @item The values displayed in reports @item For predicates (where truth is anything non-zero), to determine which postings are calculated (@option{-l}) or displayed (@option{-d}). @item For sorting criteria, to yield the sort key. @item In the matching criteria used by automated postings. @end enumerate Value expressions support most simple math and logic ...

• Variables

@subsection Variables

• Content

Below are the one letter variables available in any value expression. For the register and print commands, these variables relate to individual postings, and sometimes the account affected by a posting. For the balance command, these variables relate to accounts---often with a subtle difference in meaning. The use of each variable for both is specified. @table @code @item t This maps to whatever the user specified with @option{-t}. In a register report, @option{-t} changes the value column; ...

• Posting/account details

@subsubsection Posting/account details

• Content

@table @code @item d A posting's date, as the number of seconds past the epoch. This is always ``today'' for an account. @item a The posting's amount; the balance of an account, without considering children. @item b The cost of a posting; the cost of an account, without its children. @item v The market value of a posting, or an account without its children. @item g The net gain (market value minus cost basis), for a posting or an account without its children. It is the same as @samp{v-b}. ...

• Calculated totals

@subsubsection Calculated totals

• Content

@table @code @item O The total of all postings seen so far, or the total of an account and all its children. @item N The total count of postings affecting an account and all its children. @item B The total cost of all postings seen so far; the total cost of an account and all its children. @item V The market value of all postings seen so far, or of an account and all its children. @item G The total net gain (market value minus cost basis), for a series of postings, or an account and its chil...

• Functions

@subsection Functions

• Content

The available one letter functions are: @table @code @item - Negates the argument. @item U The absolute (unsigned) value of the argument. @item S Strips the commodity from the argument. @item A The arithmetic mean of the argument; @samp{Ax} is the same as @samp{x/n}. @item P The present market value of the argument. The syntax @samp{P(x,d)} is supported, which yields the market value at time @samp{d}. If no date is given, then the current moment is used. @end table

• Operators

@subsection Operators

• Content

The binary and ternary operators, in order of precedence, are: @enumerate @item @samp{* /} @item @samp{+ -} @item @samp{! < > =} @item @samp{& | ?:} @end enumerate

• Complex expressions

@subsection Complex expressions

• Content

More complicated expressions are possible using: @table @code @item NUM A plain integer represents a commodity-less amount. @item @{AMOUNT@} An amount in braces can be any kind of amount supported by ledger, with or without a commodity. Use this for decimal values. @item /REGEXP/ @item W/REGEXP/ A regular expression that matches against an account's full name. If a posting, this will match against the account affected by the posting. @item //REGEXP/ @item p/REGEXP/ A regular expression tha...

• File format

@section File format

• Content

The ledger file format is quite simple, but also very flexible. It supports many options, though typically the user can ignore most of them. They are summarized below. The initial character of each line determines what the line means, and how it should be interpreted. Allowable initial characters are: @table @code @item NUMBER A line beginning with a number denotes a transaction. It may be followed by any number of lines, each beginning with whitespace, to denote the transaction's account ...

• Ledger Tutorial

@chapter Ledger Tutorial

• Content

This chapter presents a series of recipes, gradually introducing all of the command-line features of Ledger. For the purpose of these examples, assume the environment variable @var{LEDGER} is set to the file @file{sample.dat} (which is included in the distribution), and that the contents of that file are: @smallexample = /^Expenses:Books/ (Liabilities:Taxes) -0.10 ~ Monthly Assets:Bank:Checking $500.00 Income:Salary 2004/05/01 * Checking balance Assets:Bank:Check...

• Checking balances

@section Checking balances

• Content

Ledger has seven basic commands, but by far the most often used are @command{balance} and @command{register}. To see a summary balance of all accounts, use: @example ledger bal @end example @command{bal} is a short-hand for @command{balance}. This command prints out the summary totals of the five parent accounts used in @file{sample.dat}: @smallexample $1,480.00 50 AAPL Assets $-2,500.00 Equity $20.00 Expenses $-500.00 Income ...

• Sub-account balances

@subsection Sub-account balances

• Content

The totals reported by the balance command are only the topmost parent accounts. To see the totals of all child accounts as well, use the @option{-s} option: @example ledger --real -B -s bal @end example This reports: @smallexample $2,980.00 Assets $1,480.00 Bank:Checking $1,500.00 Brokerage $-2,500.00 Equity:Opening Balances $20.00 Expenses:Books $-500.00 Income:Salary @end smallexample This shows that the @samp...

• Specific account balances

@subsection Specific account balances

• Content

While reporting the totals for all accounts can be useful, most often you will want to check the balance of a specific account or accounts. To do this, put one or more account names after the balance command. Since these names are really regular expressions, you can use partial names if you wish: @example ledger bal checking @end example Reports: @smallexample $1,480.00 Assets:Bank:Checking @end smallexample Any number of names may be used: @example ledger bal checking broker li...

• The register report

@section The register report

• Content

While the @command{balance} command can be very handy for checking account totals, by far the most powerful of Ledger's reporting tools is the @command{register} command. In fact, internally both commands use the same logic, but report the results differently: @command{balance} shows the summary totals, while @command{register} reports each posting and how it contributes to that total. Paradoxically, the most basic form of @command{register} is almost never used, since it displays every postin...

• Specific register queries

@subsection Specific register queries

• Content

The most common use of the register command is to summarize postings based on the account(s) they affect. Using @file{sample.dat} as as example, we could look at all book purchases using: @example ledger reg books @end example Reports: @smallexample 2004/05/29 Book Store Expenses:Books $20.00 $20.00 @end smallexample If a double-dash (@samp{--}) occurs in the list of regular expressions, any following arguments are matched against payee names, instead of accoun...

• Selecting postings

@section Selecting postings

• Content

Although the easiest way to use the register is to report all the postings affecting a set of accounts, it can often result in more information than you want. To cope with an ever-growing amount of data, there are several options which can help you pinpoint your report to epostly the postings that interest you most. This is called the ``calculation'' phase of Ledger. All of its related options are documented under @option{--help-calc}.

• By date

@subsection By date

• Content

@c -c, --current show only current and past transactions (not future) @option{--current}(@option{-c}) displays transactions occurring on or before the current date. Any transaction recorded for a future date will be ignored, as if it had not been seen. This is useful if you happen to pre-record transactions, but still wish to view your balances in terms of what is available today. @c -b, --begin DATE set report begin date @c -e, --end DATE set report end date @opti...

• By status

@subsection By status

• Content

By default, all regular postings are included in each report. To limit the report to certain kinds of postings, use one or more of the following options: @table @option @item -C, --cleared Consider only cleared postings. @item -U, --uncleared Consider only uncleared and pending postings. @item -R, --real Consider only real (non-virtual) postings. @item -L, --actual Consider only actual (non-automated) postings. @end table Cleared postings are indicated by an asterix placed just before the pay...

• By relationship

@subsection By relationship

• Content

@c -r, --related calculate report using related postings Normally, a register report includes only the postings that match the regular expressions specified after the command word. For example, to report all expenses: @example ledger reg ^expenses @end example This reports: @smallexample 2004/05/29 Book Store Expenses:Books $20.00 $20.00 @end smallexample Using @option{--related} (@option{-r}) reports the postings that did not match your query, but o...

• By budget

@subsection By budget

• Content

@c --budget generate budget transactions based on FILE There is more information about budgeting and forecasting in @ref{Budgeting and forecasting}. Basically, if you have any period transactions in your ledger file, you can use these options. A period transaction looks like: @example ~ Monthly Assets:Bank:Checking $500.00 Income:Salary @end example The difference from a regular transaction is that the first line begins with a tilde (~), and instead of a payee the...

• By value expression

@subsection By value expression

• Content

@c -l, --limit EXPR calculate only postings matching EXPR Value expressions can be quite complex, and are treated more fully in @ref{Value expressions}. They can be used for limiting a report with @option{--limit} (@option{-l}). The following command report income since august, but expenses since october: @example ledger -l '(/income/&d>=[aug])|(/expenses/&d>=[oct])' reg @end example The basic form of this value expression is @samp{(A&B)|(A&B)}. The @samp{A} in each part matches aga...

• Massaging register output

@section Massaging register output

• Content

Even after filtering down your data to just the postings you're interested in, the default reporting method of one posting per line is often still too much. To combat this complexity, it is possible to ask Ledger to report the details to you in many different forms, summarized in various ways. This is the ``display'' phase of Ledger, and is documented under @option{--help-disp}.

• Summarizing

@subsection Summarizing

• Content

@c -n, --collapse register: collapse transactions with multiple postings When multiple postings relate to a single transaction, they are reported as part of that transaction. For example, in the case of @file{sample.dat}: @example ledger reg -- book @end example Reports: @smallexample 2004/05/29 Book Store Expenses:Books $20.00 $20.00 Liabilities:MasterCard $-20.00 0 (Liabi...

• Quick periods

@subsection Quick periods

• Content

Although the @option{-p} option (also @option{--period}) is much more versatile, there are other options to make the most common period reports easier: @table @option @item -W, --weekly Show weekly sub-totals. Same as @samp{-p weekly}. @item -M, --monthly Show monthly sub-totals. Same as @samp{-p monthly}. @item -Y, --yearly Show yearly sub-totals. Same as @samp{-p yearly}. @end table @c --dow show a days-of-the-week report There is one kind of period report cannot be don...

• Ordering and width

@subsection Ordering and width

• Content

@c -S, --sort EXPR sort report according to the value expression EXPR The postings displayed in a report are shown in the same order as they appear in the ledger file. To change the order and sort a report, use the @option{--sort} option. @option{--sort} takes a value expression to determine the value to sort against, making it possible to sort according to complex criteria. Here are some simple and useful examples: @example ledger --sort d reg ^exp # sort by date ledger --sort t...

• Averages and percentages

@subsection Averages and percentages

• Content

@c -A, --average report average posting amount To see the running total changed to a running average, use @option{-A}. The final posting's total will be the overall average of all displayed postings. The works in conjunction with period reporting, so that you can see your monthly average expenses with: @example ledger -AM reg ^expenses:food ledger -AMn reg ^expenses @end example This works in the balance report too: @example ledger -AM bal ^expenses:food ledger -AMs bal ^expens...

• Reporting total data

@subsection Reporting total data

• Content

@c --totals in the "xml" report, include running total Normally in the @command{xml} report, only posting amounts are printed. To include the running total under a @samp{<total>} tag, use @option{--totals}. This does not affect any other report. @c -j, --amount-data print only raw amount data (useful for scripting) @c -J, --total-data print only raw total data In the register report only, the output can be changed with @option{-j} to show only the date and the am...

• Display by value expression

@subsection Display by value expression

• Content

@c -d, --display EXPR display only postings matching EXPR With @option{-d} you can decide which postings (or accounts in the balance report) are displayed, according to a value expression. The computed total is not affected, only the display. This can be very useful for shortening a report without changing the running total: @example ledger -d 'd>=[last month]' reg checking @end example This command shows the checking account's register, beginning from last month, but with the running ...

• Change report format

@subsection Change report format

• Content

@c -y, --date-format STR use STR as the date format (default: %Y/%m/%d) When dates are printed in any report, the default format is @samp{%Y/%m/%d}, which yields dates of the form @samp{YYYY/mm/dd}. This can be changed with @option{-y}, whose argument is a @code{strftime} string---see your system's C library documentation for the allowable codes. Mostly you will want to use @samp{%Y}, @samp{%m} and @samp{%d}, in whatever combination is convenient for your locale. @c -F, --format STR ...

• Standard queries

@section Standard queries

• Content

If your ledger file uses the standard top-level accounts: Assets, Liabilities, Income, Expenses, Equity: then the following queries will enable you to generate some typical accounting reports from your data. Your @emph{net worth} can be determined by balancing assets against liabilities: @example ledger bal ^assets ^liab @end example By removing long-term investment and loan accounts, you can see your current net liquidity (or liquid net worth): @example ledger bal ^assets ^liab -retirement ...

• Reporting balance totals

@section Reporting balance totals

• Content

The balance command prints out the summarized balances of all my top-level accounts, excluding sub-accounts. In order to see the balances for a specific account, just specify a regular expression after the balance command: @example ledger balance expenses:food @end example This will show all the money that's been spent on food, since the beginning of the ledger. For food spending just this month (September), use: @example ledger -p sep balance expenses:food @end example Or maybe you want t...

• Reporting percentages

@section Reporting percentages

• Content

There is no built-in way to report posting amounts or account balances in terms of percentages.

• Ledger in Practice

@chapter Ledger in Practice

• Stating where money goes

@section Stating where money goes

• Content

Accountants will talk of ``credits'' and ``debits'', but the meaning is often different from the layman's understanding. To avoid confusion, Ledger uses only subtractions and additions, although the underlying intent is the same as standard accounting principles. Recall that every posting will involve two or more accounts. Money is transferred from one or more accounts to one or more other accounts. To record the posting, an amount is @emph{subtracted} from the source accounts, and @emph{adde...

• Assets and Liabilities

@section Assets and Liabilities

• Content

Assets are money that you have, and Liabilities are money that you owe. ``Liabilities'' is just a more inclusive name for Debts. An Asset is typically increased by transferring money from an Income account, such as when you get paid. Here is a typical transaction: @smallexample 2004/09/29 My Employer Assets:Checking $500.00 Income:Salary @end smallexample Money, here, comes from an Income account belonging to ``My Employer'', and is transferred to your checking accoun...

• Tracking reimbursable expenses

@subsection Tracking reimbursable expenses

• Content

Sometimes you will want to spend money on behalf of someone else, which will eventually get repaid. Since the money is still ``yours'', it is really an asset. And since the expenditure was for someone else, you don't want it contaminating your Expenses reports. You will need to keep an account for tracking reimbursements. This is fairly easy to do in ledger. When spending the money, spend it @emph{to} your Assets:Reimbursements, using a different account for each person or business that you...

• Typical queries

@section Typical queries

• Content

A query such as the following shows all expenses since last October, sorted by total: @example ledger -b "last oct" -s -S T bal ^expenses @end example From left to right the options mean: Show transactions since October, 2003; show all sub-accounts; sort by the absolute value of the total; and report the balance for all expenses.

• Reporting monthly expenses

@subsection Reporting monthly expenses

• Content

The following query makes it easy to see monthly expenses, with each month's expenses sorted by the amount: @example ledger -M --period-sort t reg ^expenses @end example Now, you might wonder where the money came from to pay for these things. To see that report, add @option{-r}, which shows the ``related account'' postings: @example ledger -M --period-sort t -r reg ^expenses @end example But maybe this prints too much information. You might just want to see how much you're spending with yo...

• Visualizing with Gnuplot

@subsection Visualizing with Gnuplot

• Content

If you have @command{Gnuplot} installed, you can graph any of the above register reports. The script to do this is included in the ledger distribution, and is named @file{scripts/report}. Install @file{report} anywhere along your @env{PATH}, and then use @command{report} instead of @command{ledger} when doing a register report. The only thing to keep in mind is that you must specify @option{-j} or @option{-J} to indicate whether Gnuplot should plot the amount, or the running total. For examp...

• Typical plots

@subsubsection Typical plots

• Content

Here are some useful plots: @smallexample report -j -M reg ^expenses # monthly expenses report -J reg checking # checking account balance report -J reg ^income ^expenses # cash flow report # net worth report, ignoring non-$ postings report -J -l "Ua>=@{\$0.01@}" reg ^assets ^liab # net worth report starting last February. the use of a display # predicate (-d) is needed, otherwise the balance will start at # zero, and thus the y-axis will not reflect the true balance ...

• Budgeting and forecasting

@section Budgeting and forecasting

• Budgeting

@subsection Budgeting

• Content

Keeping a budget allows you to pay closer attention to your income and expenses, by reporting how far your actual financial activity is from your expectations. To start keeping a budget, put some period transactions at the top of your ledger file. A period transaction is almost identical to a regular transaction, except that it begins with a tilde and has a period expression in place of a payee. For example: @smallexample ~ Monthly Expenses:Rent $500.00 Expenses:Food ...

• Forecasting

@subsection Forecasting

• Content

Sometimes it's useful to know what your finances will look like in the future, such as determining when an account will reach zero. Ledger makes this easy to do, using the same period transactions as are used for budgeting. An example forecast report can be generated with: @example ledger --forecast "T>@{\$-500.00@}" register ^assets ^liabilities @end example This report continues outputting postings until the running total is greater than $-500.00. A final posting is always output, to show...

• Commodities and Currencies

@section Commodities and Currencies

• Content

Ledger makes no assumptions about the commodities you use; it only requires that you specify a commodity. The commodity may be any non-numeric string that does not contain a period, comma, forward slash or at-sign. It may appear before or after the amount, although it is assumed that symbols appearing before the amount refer to currencies, while non-joined symbols appearing after the amount refer to commodities. Here are some valid currency and commodity specifiers: @example $20.00 ;...

• Commodity price histories

@subsection Commodity price histories

• Content

Whenever a commodity is purchased using a different commodity (such as a share of common stock using dollars), it establishes a price for that commodity on that day. It is also possible, by recording price details in a ledger file, to specify other prices for commodities at any given time. Such price transactions might look like those below: @smallexample P 2004/06/21 02:17:58 TWCUX $27.76 P 2004/06/21 02:17:59 AGTHX $25.41 P 2004/06/21 02:18:00 OPTFX $39.31 P 2004/06/21 02:18:01 FEQTX $22.49...

• Commodity equivalencies

@subsection Commodity equivalencies

• Content

Sometimes a commodity has several forms which are all equivalent. An example of this is time. Whether tracked in terms of minutes, hours or days, it should be possible to convert between the various forms. Doing this requires the use of commodity equivalencies. For example, you might have the following two postings, one which transfers an hour of time into a @samp{Billable} account, and another which decreases the same account by ten minutes. The resulting report will indicate that fifty min...

• Accounts and Inventories

@section Accounts and Inventories

• Content

Since Ledger's accounts and commodity system is so flexible, you can have accounts that don't really exist, and use commodities that no one else recognizes. For example, let's say you are buying and selling various items in EverQuest, and want to keep track of them using a ledger. Just add items of whatever quantity you wish into your EverQuest account: @smallexample 9/29 Get some stuff at the Inn Places:Black's Tavern -3 Apples Places:Black's Tavern ...

• Understanding Equity

@section Understanding Equity

• Content

The most confusing transaction in any ledger will be your equity account--- because starting balances can't come out of nowhere. When you first start your ledger, you will likely already have money in some of your accounts. Let's say there's $100 in your checking account; then add a transaction to your ledger to reflect this amount. Where will money come from? The answer: your equity. @smallexample 10/2 Opening Balance Assets:Checking $100.00 Equity:Opening B...

• Dealing with Petty Cash

@section Dealing with Petty Cash

• Content

Something that stops many people from keeping a ledger at all is the insanity of tracking small cash expenses. They rarely generate a receipt, and there are often a lot of small postings, rather than a few large ones, as with checks. One solution is: don't bother. Move your spending to a debit card, but in general ignore cash. Once you withdraw it from the ATM, mark it as already spent to an @samp{Expenses:Cash} category: @smallexample 2004/03/15 ATM Expenses:Cash $...

• Working with multiple funds and accounts

@section Working with multiple funds and accounts

• Content

There are situations when the accounts you're tracking are different between your clients and the financial institutions where money is kept. An example of this is working as the treasurer for a religious institution. From the secular point of view, you might be working with three different accounts: @itemize @item Checking @item Savings @item Credit Card @end itemize From a religious point of view, the community expects to divide its resources into multiple ``funds'', from which it makes pu...

• Archiving previous years

@section Archiving previous years

• Content

After a while, your ledger can get to be pretty large. While this will not slow down the ledger program much---it's designed to process ledger files very quickly---things can start to feel ``messy''; and it's a universal complaint that when finances feel messy, people avoid them. Thus, archiving the data from previous years into their own files can offer a sense of completion, and freedom from the past. But how to best accomplish this with the ledger program? There are two commands that make...

• Virtual postings

@section Virtual postings

• Content

A virtual posting is when you, in your mind, see money as moving to a certain place, when in reality that money has not moved at all. There are several scenarios in which this type of tracking comes in handy, and each of them will be discussed in detail. To enter a virtual posting, surround the account name in parentheses. This form of usage does not need to balance. However, if you want to ensure the virtual posting balances with other virtual postings in the same transaction, use square bra...

• Automated postings

@section Automated postings

• Content

As a Bahá'í, I need to compute Huqúqu'lláh whenever I acquire assets. It is similar to tithing for Jews and Christians, or to Zakát for Muslims. The epost details of computing Huqúqu'lláh are somewhat complex, but if you have further interest, please consult the Web. Ledger makes this otherwise difficult law very easy. Just set up an automated posting at the top of your ledger file: @smallexample ; This automated transaction will compute Huqúqu'lláh based on this ; journal's postings. Any t...

• Using Emacs to Keep Your Ledger

@section Using Emacs to Keep Your Ledger

• Content

In the Ledger tarball is an Emacs module, @file{ledger.el}. This module makes the process of keeping a text ledger much easier for Emacs users. I recommend putting this at the top of your ledger file: @example ; -*-ledger-*- @end example And this in your @file{.emacs} file, after copying @file{ledger.el} to your @file{site-lisp} directory: @example (load "ledger") @end example Now when you edit your ledger file, it will be in @command{ledger-mode}. @command{ledger-mode} adds these command...

• Using GnuCash to Keep Your Ledger

@section Using GnuCash to Keep Your Ledger

• Content

The Ledger tool is fast and simple, but it offers no custom method for actually editing the ledger. It assumes you know how to use a text editor, and like doing so. There is, at least, an Emacs mode that makes editing Ledger's data files much easier. You are also free to use GnuCash to maintain your ledger, and the Ledger program for querying and reporting on the contents of that ledger. It takes a little longer to parse the XML data format that GnuCash uses, but the end result is identical....

• Using timeclock to record billable time

@section Using timeclock to record billable time

• Content

The timeclock tool makes it easy to track time events, like clocking into and out of a particular job. These events accumulate in a timelog file. Each in/out event may have an optional description. If the ``in'' description is a ledger account name, these in/out pairs may be viewed as virtual postings, adding time commodities (hours) to that account. For example, the command-line version of the timeclock tool could be used to begin a timelog file like: @example export TIMELOG=$HOME/.timelog...

• Using XML

@section Using XML

• Content

By default, Ledger uses a human-readable data format, and displays its reports in a manner meant to be read on screen. For the purpose of writing tools which use Ledger, however, it is possible to read and display data using XML. This section documents that format. The general format used for Ledger data is: @smallexample <?xml version="1.0"?> <ledger> <xact>...</xact> <xact>...</xact> <xact>...</xact>... </ledger> @end smallexample The data stream is enclosed in a @samp{ledger} tag, ...

• Random things

@chapter Random things

• Content

Whenever a commodity is exchanged for another in a posting, one of the two is considered @emph{primary}, and the other secondary. Primariness of a commodity is remembered, since the @option{--market} option only renders balances into secondary commodities, never primaries. To render primaries, use the @option{--exchange=COMMODITY} option. In all of the following examples, the P commodity is considered primary and the S is secondary (the P at the beginning of the line indicates a price-setting ...

• Anatomy of a journal file

@chapter Anatomy of a journal file

• Content

Everything begins with a journal file---the anatomy of which is covered in detail in chapter one. To review: a @emph{journal} contains one or more @emph{transactions}, each of which refers to two or more @emph{postings}. A @emph{posting} specifies that a given @emph{amount} is added to, or subtracted from, an @emph{account}. (@emph{Accounts} may be nested hierarchically by separating the elements using a colon). Lastly, an @emph{amount} is a figure representing a given @emph{quantity} of a @e...

• Example accounting practices

@chapter Example accounting practices

• Generating useful reports

@chapter Generating useful reports

• Content

Once you have a journal file representing a recent history of your finances, the next step is to generate reports in order to give richer meaning to this data. For example: Where do you spend your money? Do you have enough to cover upcoming expenses? Are you creating or losing net worth? Are your investment performing well? All of these questions can be answered easily with Ledger---if you know how to ask them. Preparing complex reports is not a simple task, but neither is it a difficult o...

• Value expressions

@chapter Value expressions

• Format strings

@chapter Format strings

• Scripting in Python

@chapter Scripting in Python

• Content

Ledger is, at heart, just a sophisticated calculator. In addition to summing values within “accounts”, it guarantees that every transaction balances to zero to confirm these values are correctly transferred between accounts. In addition to using this calculator from the command-line to generate reports, you may also access it from the Python scripting language, in order to manipulate the figures however you wish. The following chapter presents the ideas you will need to know to accomplish thi...

• Creating a session

@section Creating a session

• Content

All interactions with the Ledger library take place in the context of a @var{Session}. You may create as many sessions as you like, though typically only one is needed during the lifetime of a scriptAn example where more might be needed is a GUI program that opens multiple Ledger files in different windows, and creates reports for each file separately. Ledger provides a pre-initialized session named @var{session}, but others can still be created. Creating a session is trivial, but before it m...

• Initialize a session

Example of creating a session, reading some journal data, and generating a simplistic report.

• The design of Ledger

@chapter The design of Ledger

• Content

The following sections discuss how Ledger is architected, from the ground up, and will show how to use the various parts of the Ledger library from your own scripts. Ledger essentially follows five steps in reporting data to the user: @enumerate @item Parse journal file into an internal representation @item Perform any implied math within the journal file @item ``Face'' this internal representation as a virtual document @item Apply a series of transforms to the virtual document @item Display t...

• Numerics

@section Numerics

• Basic amounts

@subsection Basic amounts

• Content

The most fundamental type in Ledger is the amount, which may or may not have a commodity attached to it. First, we'll deal with the bare case, just to show how the amount type works. In C++, most all of Ledger's internal types end in @code{_t}; in Python, the same type name is used, but the @code{_t} suffix is dropped. Examples of usage in both languages will be presented throughout. amount_t commodity_t updater_t datetime_t balance_t balance_pair_t value_t valexpr_t format_t mask_t

• Journal Representation

@section Journal Representation

• Content

journal_t account_t xact_t post_t parser_t

• Reporting

@section Reporting

• Terminal Interface

@section Terminal Interface

• General Utility

@section General Utility

• End Matter

@bye