Closing out the books in ledger(1)
I put this here mostly because I forget how to do it and have to make multiple starts to get it right.
I have a
wrapper.txt
file that consists purely of settings
and including my files for my globals
(accounts, commodities, automated transactions, and tags
so that the
--pedantic
passes),
my transactions,
and my
balance-assertions.
--pedantic include globals.txt include opening_balances.txt include transactions.txt include balance_assertions.txt
wrapper.txt
CUR=
PREV=$(($CUR - 1))
ledger -f wrapper.txt print \
-b ${PREV}
-e ${CUR} > ${PREV}.txt
ledger -f wrapper.txt equity \
-e ${CUR} \
-l "commodity == 'USD'" \
^Equity: ^Assets: ^Liabilities \
| sed '$s/\> .*//' \
> temp_equity.txt
ledger -f wrapper.txt print \
-b ${CUR} > temp_transactions.txt
mv temp_equity.txt opening_balances.txt
mv temp_transactions.txt transactions.txt
Note:
I keep my
ledger
files in
git
so I have a fair bit of freedom to experiment.
If I mess things up beyond repair,
I can always
git reset --hard
to revert to the most recent snapshot.
I recommend you make a backup as well.
To make this easier, I start by setting a few variables for the current year and the previous year. This allows me to update one variable then copy/paste the rest of the instructions to close the books in subsequent years.
The first
print
step pulls all transactions beginning
(-b)
after the previous year and ending
(-e)
before the current year into
${PREV}.txt
as an archive.
Next, I create a temporary file
containing the
Opening Balances
for the period ending
(-e)
before the current year using the
equity
command.
In my case,
I also want to limit my commodities
(-l "commodity == 'USD'")
to "USD" only
because I don't want to carry forward
my gallons-of-gasoline and the like.
Similarly, I only want
Equity, Assets, and Liabilities
because I've found
that including Income & Expenses
gives me some unexpected results at times.
I also use
sed
to make the final
"Equity:Opening Balances"
transaction an auto-balancing transaction.
Finally, I need to filter out all
those archived transactions
so I use
print
to select only the transactions beginning
(-b)
on
${CUR}
into a second temporary file.
At this point,
we can move the
temp_equity.txt
back atop the original
opening_balances.txt
and move the
temp_transactions.txt
back atop the original
transactions.txt
file.
With all that,
I usually run a
ledger bal
to verify that everything balances as I expect.
If so, I add the
${PREV}.txtwrapper.txt
and updated
transactions.txt
files,
commit them,
and push them out to my other hosts.