hledger 1.19.1 → 1.20
raw patch · 62 files changed
+19522/−16020 lines, 62 filesdep −pretty-showdep ~hledger-libPVP ok
version bump matches the API change (PVP)
Dependencies removed: pretty-show
Dependency ranges changed: hledger-lib
API changes (from Hackage documentation)
- Hledger.Cli.CliOptions: [reportopts_] :: CliOpts -> ReportOpts
- Hledger.Cli.CliOptions: checkCliOpts :: CliOpts -> CliOpts
- Hledger.Cli.CliOptions: defaultBalanceLineFormat :: StringFormat
- Hledger.Cli.CliOptions: lineFormatFromOpts :: ReportOpts -> Either String StringFormat
- Hledger.Cli.Utils: fileModificationTime :: FilePath -> IO ClockTime
- Hledger.Cli.Utils: journalSpecifiedFileIsNewer :: Journal -> FilePath -> IO Bool
+ Hledger.Cli.CliOptions: [reportspec_] :: CliOpts -> ReportSpec
+ Hledger.Cli.Commands.Check: check :: CliOpts -> Journal -> IO ()
+ Hledger.Cli.Commands.Check: checkmode :: Mode RawOpts
+ Hledger.Cli.Commands.Check: instance GHC.Classes.Eq Hledger.Cli.Commands.Check.Check
+ Hledger.Cli.Commands.Check: instance GHC.Read.Read Hledger.Cli.Commands.Check.Check
+ Hledger.Cli.Commands.Check: instance GHC.Show.Show Hledger.Cli.Commands.Check.Check
+ Hledger.Cli.Utils: utcTimeToClockTime :: UTCTime -> ClockTime
- Hledger.Cli: checkMode :: () => Mode a -> Maybe String
+ Hledger.Cli: checkMode :: Mode a -> Maybe String
- Hledger.Cli: complete :: () => Mode a -> [String] -> (Int, Int) -> [Complete]
+ Hledger.Cli: complete :: Mode a -> [String] -> (Int, Int) -> [Complete]
- Hledger.Cli: flagArg :: () => Update a -> FlagHelp -> Arg a
+ Hledger.Cli: flagArg :: Update a -> FlagHelp -> Arg a
- Hledger.Cli: flagBool :: () => [Name] -> (Bool -> a -> a) -> Help -> Flag a
+ Hledger.Cli: flagBool :: [Name] -> (Bool -> a -> a) -> Help -> Flag a
- Hledger.Cli: flagHelpFormat :: () => (HelpFormat -> TextFormat -> a -> a) -> Flag a
+ Hledger.Cli: flagHelpFormat :: (HelpFormat -> TextFormat -> a -> a) -> Flag a
- Hledger.Cli: flagHelpSimple :: () => (a -> a) -> Flag a
+ Hledger.Cli: flagHelpSimple :: (a -> a) -> Flag a
- Hledger.Cli: flagNone :: () => [Name] -> (a -> a) -> Help -> Flag a
+ Hledger.Cli: flagNone :: [Name] -> (a -> a) -> Help -> Flag a
- Hledger.Cli: flagNumericVersion :: () => (a -> a) -> Flag a
+ Hledger.Cli: flagNumericVersion :: (a -> a) -> Flag a
- Hledger.Cli: flagOpt :: () => String -> [Name] -> Update a -> FlagHelp -> Help -> Flag a
+ Hledger.Cli: flagOpt :: String -> [Name] -> Update a -> FlagHelp -> Help -> Flag a
- Hledger.Cli: flagReq :: () => [Name] -> Update a -> FlagHelp -> Help -> Flag a
+ Hledger.Cli: flagReq :: [Name] -> Update a -> FlagHelp -> Help -> Flag a
- Hledger.Cli: flagVersion :: () => (a -> a) -> Flag a
+ Hledger.Cli: flagVersion :: (a -> a) -> Flag a
- Hledger.Cli: flagsVerbosity :: () => (Verbosity -> a -> a) -> [Flag a]
+ Hledger.Cli: flagsVerbosity :: (Verbosity -> a -> a) -> [Flag a]
- Hledger.Cli: fromGroup :: () => Group a -> [a]
+ Hledger.Cli: fromGroup :: Group a -> [a]
- Hledger.Cli: helpText :: () => [String] -> HelpFormat -> Mode a -> [Text]
+ Hledger.Cli: helpText :: [String] -> HelpFormat -> Mode a -> [Text]
- Hledger.Cli: mode :: () => Name -> a -> Help -> Arg a -> [Flag a] -> Mode a
+ Hledger.Cli: mode :: Name -> a -> Help -> Arg a -> [Flag a] -> Mode a
- Hledger.Cli: modeEmpty :: () => a -> Mode a
+ Hledger.Cli: modeEmpty :: a -> Mode a
- Hledger.Cli: modeFlags :: () => Mode a -> [Flag a]
+ Hledger.Cli: modeFlags :: Mode a -> [Flag a]
- Hledger.Cli: modeModes :: () => Mode a -> [Mode a]
+ Hledger.Cli: modeModes :: Mode a -> [Mode a]
- Hledger.Cli: modes :: () => String -> a -> Help -> [Mode a] -> Mode a
+ Hledger.Cli: modes :: String -> a -> Help -> [Mode a] -> Mode a
- Hledger.Cli: process :: () => Mode a -> [String] -> Either String a
+ Hledger.Cli: process :: Mode a -> [String] -> Either String a
- Hledger.Cli: processArgs :: () => Mode a -> IO a
+ Hledger.Cli: processArgs :: Mode a -> IO a
- Hledger.Cli: processValue :: () => Mode a -> [String] -> a
+ Hledger.Cli: processValue :: Mode a -> [String] -> a
- Hledger.Cli: processValueIO :: () => Mode a -> [String] -> IO a
+ Hledger.Cli: processValueIO :: Mode a -> [String] -> IO a
- Hledger.Cli: remapUpdate :: () => (a -> b) -> (b -> (a, a -> b)) -> Update a -> Update b
+ Hledger.Cli: remapUpdate :: (a -> b) -> (b -> (a, a -> b)) -> Update a -> Update b
- Hledger.Cli: toGroup :: () => [a] -> Group a
+ Hledger.Cli: toGroup :: [a] -> Group a
- Hledger.Cli.CliOptions: CliOpts :: RawOpts -> String -> [FilePath] -> InputOpts -> ReportOpts -> Maybe FilePath -> Maybe String -> Int -> Bool -> Maybe String -> Int -> CliOpts
+ Hledger.Cli.CliOptions: CliOpts :: RawOpts -> String -> [FilePath] -> InputOpts -> ReportSpec -> Maybe FilePath -> Maybe String -> Int -> Bool -> Maybe String -> Int -> CliOpts
- Hledger.Cli.Commands.Activity: showHistogram :: ReportOpts -> Query -> Journal -> String
+ Hledger.Cli.Commands.Activity: showHistogram :: ReportSpec -> Journal -> String
- Hledger.Cli.Commands.Balance: balanceReportItemAsText :: ReportOpts -> StringFormat -> BalanceReportItem -> [String]
+ Hledger.Cli.Commands.Balance: balanceReportItemAsText :: ReportOpts -> BalanceReportItem -> [String]
- Hledger.Cli.Commands.Checkdupes: checkdupes :: () => p -> Journal -> IO ()
+ Hledger.Cli.Commands.Checkdupes: checkdupes :: p -> Journal -> IO ()
- Hledger.Cli.CompoundBalanceCommand: CompoundBalanceCommandSpec :: CommandDoc -> String -> [CBCSubreportSpec] -> BalanceType -> CompoundBalanceCommandSpec
+ Hledger.Cli.CompoundBalanceCommand: CompoundBalanceCommandSpec :: CommandDoc -> String -> [CBCSubreportSpec DisplayName] -> BalanceType -> CompoundBalanceCommandSpec
- Hledger.Cli.CompoundBalanceCommand: [cbcqueries] :: CompoundBalanceCommandSpec -> [CBCSubreportSpec]
+ Hledger.Cli.CompoundBalanceCommand: [cbcqueries] :: CompoundBalanceCommandSpec -> [CBCSubreportSpec DisplayName]
- Hledger.Cli.Utils: journalAddForecast :: CliOpts -> Journal -> IO Journal
+ Hledger.Cli.Utils: journalAddForecast :: CliOpts -> Journal -> Journal
- Hledger.Cli.Utils: journalFileIsNewer :: Journal -> IO Bool
+ Hledger.Cli.Utils: journalFileIsNewer :: Journal -> FilePath -> IO Bool
- Hledger.Cli.Utils: journalTransform :: CliOpts -> Journal -> IO Journal
+ Hledger.Cli.Utils: journalTransform :: CliOpts -> Journal -> Journal
Files
- CHANGES.md +98/−0
- Hledger/Cli/CliOptions.hs +18/−47
- Hledger/Cli/Commands.hs +7/−5
- Hledger/Cli/Commands/Accounts.hs +4/−6
- Hledger/Cli/Commands/Activity.hs +14/−16
- Hledger/Cli/Commands/Add.hs +12/−7
- Hledger/Cli/Commands/Aregister.hs +31/−32
- Hledger/Cli/Commands/Balance.hs +102/−103
- Hledger/Cli/Commands/Balance.txt +57/−6
- Hledger/Cli/Commands/Balancesheet.hs +4/−2
- Hledger/Cli/Commands/Balancesheetequity.hs +6/−3
- Hledger/Cli/Commands/Cashflow.hs +2/−1
- Hledger/Cli/Commands/Check.hs +88/−0
- Hledger/Cli/Commands/Check.txt +64/−0
- Hledger/Cli/Commands/Checkdates.hs +19/−21
- Hledger/Cli/Commands/Checkdupes.hs +7/−1
- Hledger/Cli/Commands/Close.hs +6/−5
- Hledger/Cli/Commands/Codes.hs +3/−6
- Hledger/Cli/Commands/Descriptions.hs +2/−4
- Hledger/Cli/Commands/Diff.hs +2/−2
- Hledger/Cli/Commands/Import.hs +1/−1
- Hledger/Cli/Commands/Import.txt +5/−0
- Hledger/Cli/Commands/Incomestatement.hs +4/−2
- Hledger/Cli/Commands/Notes.hs +2/−5
- Hledger/Cli/Commands/Payees.hs +2/−5
- Hledger/Cli/Commands/Prices.hs +1/−2
- Hledger/Cli/Commands/Print.hs +8/−12
- Hledger/Cli/Commands/Register.hs +14/−17
- Hledger/Cli/Commands/Registermatch.hs +3/−6
- Hledger/Cli/Commands/Rewrite.hs +6/−6
- Hledger/Cli/Commands/Roi.hs +62/−31
- Hledger/Cli/Commands/Roi.txt +231/−4
- Hledger/Cli/Commands/Stats.hs +3/−3
- Hledger/Cli/Commands/Tags.hs +11/−9
- Hledger/Cli/CompoundBalanceCommand.hs +27/−20
- Hledger/Cli/Main.hs +7/−8
- Hledger/Cli/Utils.hs +86/−81
- embeddedfiles/hledger-ui.1 +4/−1
- embeddedfiles/hledger-ui.info +26/−22
- embeddedfiles/hledger-ui.txt +118/−114
- embeddedfiles/hledger-web.1 +9/−1
- embeddedfiles/hledger-web.info +27/−18
- embeddedfiles/hledger-web.txt +10/−2
- embeddedfiles/hledger.1 +552/−73
- embeddedfiles/hledger.info +4692/−4257
- embeddedfiles/hledger.txt +3378/−2997
- embeddedfiles/hledger_csv.5 +96/−21
- embeddedfiles/hledger_csv.info +144/−100
- embeddedfiles/hledger_csv.txt +173/−136
- embeddedfiles/hledger_journal.5 +97/−38
- embeddedfiles/hledger_journal.info +252/−179
- embeddedfiles/hledger_journal.txt +281/−231
- embeddedfiles/hledger_timeclock.5 +1/−1
- embeddedfiles/hledger_timeclock.info +2/−2
- embeddedfiles/hledger_timeclock.txt +1/−1
- embeddedfiles/hledger_timedot.5 +2/−2
- embeddedfiles/hledger_timedot.info +3/−3
- embeddedfiles/hledger_timedot.txt +2/−2
- hledger.1 +552/−73
- hledger.cabal +11/−13
- hledger.info +4692/−4257
- hledger.txt +3378/−2997
CHANGES.md view
@@ -1,6 +1,104 @@ User-visible changes in the hledger command line tool and library. +# 1.20 2020-12-05++## general++- strict mode: with -s/--strict, hledger requires that+ all accounts and commodities are declared with directives.++- Reverted a stripAnsi change in 1.19.1 that caused a 3x slowdown of amount rendering+ in terminal reports. (#1350)++- Amount and table rendering has been improved, so that stripAnsi is no longer needed.+ This speeds up amount rendering in the terminal, speeding up some reports by 10% or more since 1.19.+ (Stephen Morgan)++- Amount eliding no longer displays corrupted ANSI codes (#1352, Stephen Morgan)++- Eliding of multicommodity amounts now makes better use of available space,+ avoiding unnecessary eliding (showing as many amounts as possible within+ 32 characters). (Stephen Morgan)++- Command line help for --no-elide now mentions that it also disables eliding of+ multicommodity amounts.++- Query terms containing quotes (eg to match account names containing quotes)+ now work properly. (#1368, Stephen Morgan)++- cli, journal: Date range parsing is more robust, fixing failing/incorrect cases such as: (Stephen Morgan)++ - a hyphenated range with just years (`2017-2018`)+ - a hyphenated date with no day in a hyphenated range (`2017-07-2018`)+ - a dotted date with no day in a dotted range (`2017.07..2018.02`)+ +- Debug output is prettier (eg, in colour), using pretty-simple instead of pretty-show.++- csv, timedot, timeclock files now respect command line --alias options,+ like journal files. (#859)++- Market price lookup for value reports is now more robust, fixing several bugs+ (and debug output is more informative).+ There has been a slight change in functionality: when chaining prices,+ we now prefer chains of all "forward" prices, even if longer, with chains+ involving reverse prices being the last resort.+ (#1402)++## commands++- add: number style (eg thousands separators) no longer disturbs the value+ that is offered as default. (#1378)++- bal: --invert now affects -S/--sort-amount, reversing the order. (#1283, #1379) (Stephen Morgan)++- bal: --budget reports no longer insert an extra space inside the brackets. (Stephen Morgan)++- bal, is, bs --change: + Valued multiperiod balance change reports now show changes of value, + rather than the value of changes. (#1353, Stephen Morgan)++- bal: improve budget, MultiBalanceReport debug output+ Comply with debug levels policy, clarify some labels.++- bal: support CSV output for --budget reports (#1155)++- check: A new command which consolidating the various check-* commands.+ It runs the default, strict, or specified checks and produces+ no output and a zero exit code if all is well.++- check-dates: this command is deprecated and will be removed+ in next release; use "hledger check ordereddates" instead.++- check-dupes: this command is deprecated and will be removed+ in next release; use "hledger check uniqueleafnames" instead.++- import: The journal's commodity styles (declared or inferred) are now applied+ to imported amounts, overriding their original number format.++- roi: TWR now handles same-day pnl changes and cashflows,+ calculation failure messages have been improved, and+ the documentation includes more detail and examples.+ (#1398) (Dmitry Astapov)++## journal format++- The journal's commodity styles are now applied to forecasted transactions. (#1371)++- journal, csv: commodity style is now inferred from the first amount, as documented,+ not the last. This was "working wrongly" since hledger 1.12..++- A zero market price no longer causes "Ratio has zero denominator" error+ in valued reports. (#1373)++## csv format++- The new `decimal-mark` rule allows reliable number parsing+ when CSV numbers contain digit group marks (eg thousands separators).++- The CSV reader's verbose "assignment" debug output is now at level 9.++ # 1.19.1 2020-09-07 - Fix alignment of coloured numbers (#1345, #1349, Stephen Morgan)
Hledger/Cli/CliOptions.hs view
@@ -38,10 +38,8 @@ getHledgerCliOpts, getHledgerCliOpts', rawOptsToCliOpts,- checkCliOpts, outputFormats, defaultOutputFormat,- defaultBalanceLineFormat, CommandDoc, -- possibly these should move into argsToCliOpts@@ -56,8 +54,6 @@ replaceNumericFlags, -- | For register: registerWidthsFromOpts,- -- | For balance:- lineFormatFromOpts, -- * Other utils hledgerAddons,@@ -129,6 +125,7 @@ ,flagNone ["anon"] (setboolopt "anon") "anonymize accounts and payees" ,flagReq ["pivot"] (\s opts -> Right $ setopt "pivot" s opts) "TAGNAME" "use some other field/tag for account names" ,flagNone ["ignore-assertions","I"] (setboolopt "ignore-assertions") "ignore any balance assertions"+ ,flagNone ["strict","s"] (setboolopt "strict") "do extra error checking (check that all posted accounts are declared)" ] -- | Common report-related flags: --period, --cost, etc.@@ -403,7 +400,7 @@ ,command_ :: String ,file_ :: [FilePath] ,inputopts_ :: InputOpts- ,reportopts_ :: ReportOpts+ ,reportspec_ :: ReportSpec ,output_file_ :: Maybe FilePath ,output_format_ :: Maybe String ,debug_ :: Int -- ^ debug level, set by @--debug[=N]@. See also 'Hledger.Utils.debugLevel'.@@ -419,17 +416,18 @@ defcliopts :: CliOpts defcliopts = CliOpts- def- def- def- def- def- def- def- def- def- def- defaultWidth+ { rawopts_ = def+ , command_ = ""+ , file_ = []+ , inputopts_ = def+ , reportspec_ = def+ , output_file_ = Nothing+ , output_format_ = Nothing+ , debug_ = 0+ , no_new_accounts_ = False+ , width_ = Nothing+ , available_width_ = defaultWidth+ } -- | Default width for hledger console output, when not otherwise specified. defaultWidth :: Int@@ -448,9 +446,9 @@ -- today's date. Parsing failures will raise an error. -- Also records the terminal width, if supported. rawOptsToCliOpts :: RawOpts -> IO CliOpts-rawOptsToCliOpts rawopts = checkCliOpts <$> do+rawOptsToCliOpts rawopts = do let iopts = rawOptsToInputOpts rawopts- ropts <- rawOptsToReportOpts rawopts+ rspec <- rawOptsToReportSpec rawopts mcolumns <- readMay <$> getEnvSafe "COLUMNS" mtermwidth <- #ifdef mingw32_HOST_OS@@ -465,7 +463,7 @@ ,command_ = stringopt "command" rawopts ,file_ = listofstringopt "file" rawopts ,inputopts_ = iopts- ,reportopts_ = ropts+ ,reportspec_ = rspec ,output_file_ = maybestringopt "output-file" rawopts ,output_format_ = maybestringopt "output-format" rawopts ,debug_ = posintopt "debug" rawopts@@ -474,16 +472,6 @@ ,available_width_ = availablewidth } --- | Do final validation of processed opts, raising an error if there is trouble.-checkCliOpts :: CliOpts -> CliOpts-checkCliOpts opts =- either usageError (const opts) $ do- -- XXX move to checkReportOpts or move _format to CliOpts- case lineFormatFromOpts $ reportopts_ opts of- Left err -> Left $ "could not parse format option: "++err- Right _ -> Right ()- -- XXX check registerWidthsFromOpts opts- -- | A helper for addon commands: this parses options and arguments from -- the current command line using the given hledger-style cmdargs mode, -- and returns a CliOpts. Or, with --help or -h present, it prints@@ -532,8 +520,7 @@ putStrLn $ "running: " ++ progname' putStrLn $ "raw args: " ++ show args' putStrLn $ "processed opts:\n" ++ show opts- d <- getCurrentDay- putStrLn $ "search query: " ++ show (queryFromOpts d $ reportopts_ opts)+ putStrLn $ "search query: " ++ show (rsQuery $ reportspec_ opts) getHledgerCliOpts :: Mode RawOpts -> IO CliOpts getHledgerCliOpts mode' = do@@ -642,22 +629,6 @@ descwidth <- optional (char ',' >> read `fmap` some digitChar) eof return (totalwidth, descwidth)---- for balance, currently:---- | Parse the format option if provided, possibly returning an error,--- otherwise get the default value.-lineFormatFromOpts :: ReportOpts -> Either String StringFormat-lineFormatFromOpts = maybe (Right defaultBalanceLineFormat) parseStringFormat . format_---- | Default line format for balance report: "%20(total) %2(depth_spacer)%-(account)"-defaultBalanceLineFormat :: StringFormat-defaultBalanceLineFormat = BottomAligned [- FormatField False (Just 20) Nothing TotalField- , FormatLiteral " "- , FormatField True (Just 2) Nothing DepthSpacerField- , FormatField True Nothing Nothing AccountField- ] -- Other utils
Hledger/Cli/Commands.hs view
@@ -72,6 +72,7 @@ import Hledger.Cli.Commands.Balancesheet import Hledger.Cli.Commands.Balancesheetequity import Hledger.Cli.Commands.Cashflow+import Hledger.Cli.Commands.Check import Hledger.Cli.Commands.Checkdates import Hledger.Cli.Commands.Checkdupes import Hledger.Cli.Commands.Close@@ -109,6 +110,7 @@ ,(balancesheetequitymode , balancesheetequity) ,(balancesheetmode , balancesheet) ,(cashflowmode , cashflow)+ ,(checkmode , check) ,(checkdatesmode , checkdates) ,(checkdupesmode , checkdupes) ,(closemode , close)@@ -166,9 +168,9 @@ ,"" ,"Data management:" ,"+autosync download/deduplicate/convert OFX data"- ,"+check check more powerful balance assertions"- ," check-dates check transactions are ordered by date"- ," check-dupes check for accounts with the same leaf name"+ ," check check for various kinds of issue in the data"+ ,"+check-fancyassertions check more powerful balance assertions"+ ,"+check-tagfiles check file paths in tag values exist" ," close (equity) generate balance-resetting transactions" ," diff compare account transactions in two journal files" ,"+interest generate interest transactions"@@ -276,8 +278,8 @@ -- not be used (and would raise an error). -- testcmd :: CliOpts -> Journal -> IO ()-testcmd opts _undefined = do - withArgs (words' $ query_ $ reportopts_ opts) $+testcmd opts _undefined = do+ withArgs (listofstringopt "args" $ rawopts_ opts) $ Test.Tasty.defaultMain $ tests "hledger" [ tests_Hledger ,tests_Hledger_Cli
Hledger/Cli/Commands/Accounts.hs view
@@ -48,19 +48,17 @@ -- | The accounts command. accounts :: CliOpts -> Journal -> IO ()-accounts CliOpts{rawopts_=rawopts, reportopts_=ropts} j = do+accounts CliOpts{rawopts_=rawopts, reportspec_=ReportSpec{rsQuery=query,rsOpts=ropts}} j = do -- 1. identify the accounts we'll show- d <- getCurrentDay let tree = tree_ ropts declared = boolopt "declared" rawopts used = boolopt "used" rawopts- q = queryFromOpts d ropts -- a depth limit will clip and exclude account names later, but we don't want to exclude accounts at this stage- nodepthq = dbg1 "nodepthq" $ filterQuery (not . queryIsDepth) q+ nodepthq = dbg1 "nodepthq" $ filterQuery (not . queryIsDepth) query -- just the acct: part of the query will be reapplied later, after clipping- acctq = dbg1 "acctq" $ filterQuery queryIsAcct q- depth = dbg1 "depth" $ queryDepth $ filterQuery queryIsDepth q+ acctq = dbg1 "acctq" $ filterQuery queryIsAcct query+ depth = dbg1 "depth" $ queryDepth $ filterQuery queryIsDepth query matcheddeclaredaccts = dbg1 "matcheddeclaredaccts" $ filter (matchesAccount nodepthq) $ map fst $ jdeclaredaccounts j matchedusedaccts = dbg5 "matchedusedaccts" $ map paccount $ journalPostings $ filterJournalPostings nodepthq j accts = dbg5 "accts to show" $ -- no need to nub/sort, accountTree will
Hledger/Cli/Commands/Activity.hs view
@@ -30,23 +30,21 @@ -- | Print a bar chart of number of postings per report interval. activity :: CliOpts -> Journal -> IO ()-activity CliOpts{reportopts_=ropts} j = do- d <- getCurrentDay- putStr $ showHistogram ropts (queryFromOpts d ropts) j+activity CliOpts{reportspec_=rspec} j = putStr $ showHistogram rspec j -showHistogram :: ReportOpts -> Query -> Journal -> String-showHistogram opts q j = concatMap (printDayWith countBar) spanps- where- i = interval_ opts- interval | i == NoInterval = Days 1- | otherwise = i- span' = queryDateSpan (date2_ opts) q `spanDefaultsFrom` journalDateSpan (date2_ opts) j- spans = filter (DateSpan Nothing Nothing /=) $ splitSpan interval span'- spanps = [(s, filter (isPostingInDateSpan s) ps) | s <- spans]- -- same as Register- -- should count transactions, not postings ?- -- ps = sortBy (comparing postingDate) $ filterempties $ filter matchapats $ filterdepth $ journalPostings j- ps = sortOn postingDate $ filter (q `matchesPosting`) $ journalPostings j+showHistogram :: ReportSpec -> Journal -> String+showHistogram ReportSpec{rsQuery=q,rsOpts=ReportOpts{interval_=i,date2_=date2}} j =+ concatMap (printDayWith countBar) spanps+ where+ interval | i == NoInterval = Days 1+ | otherwise = i+ span' = queryDateSpan date2 q `spanDefaultsFrom` journalDateSpan date2 j+ spans = filter (DateSpan Nothing Nothing /=) $ splitSpan interval span'+ spanps = [(s, filter (isPostingInDateSpan s) ps) | s <- spans]+ -- same as Register+ -- should count transactions, not postings ?+ -- ps = sortBy (comparing postingDate) $ filterempties $ filter matchapats $ filterdepth $ journalPostings j+ ps = sortOn postingDate $ filter (q `matchesPosting`) $ journalPostings j printDayWith f (DateSpan b _, ps) = printf "%s %s\n" (show $ fromJust b) (f ps)
Hledger/Cli/Commands/Add.hs view
@@ -255,7 +255,7 @@ -- Identify the closest recent match for this description in past transactions. similarTransaction :: EntryState -> Text -> Maybe Transaction similarTransaction EntryState{..} desc =- let q = queryFromOptsOnly esToday $ reportopts_ esOpts+ let q = queryFromFlags . rsOpts $ reportspec_ esOpts historymatches = transactionsSimilarTo esJournal q desc bestmatch | null historymatches = Nothing | otherwise = Just $ snd $ head historymatches@@ -333,8 +333,12 @@ (mhistoricalp,followedhistoricalsofar) = case esSimilarTransaction of Nothing -> (Nothing,False)- Just Transaction{tpostings=ps} -> (if length ps >= pnum then Just (ps !! (pnum-1)) else Nothing- ,all (\(a,b) -> pamount a == pamount b) $ zip esPostings ps)+ Just Transaction{tpostings=ps} -> + ( if length ps >= pnum then Just (ps !! (pnum-1)) else Nothing+ , all sameamount $ zip esPostings ps+ )+ where+ sameamount (p1,p2) = mixedAmountUnstyled (pamount p1) == mixedAmountUnstyled (pamount p2) def = case (esArgs, mhistoricalp, followedhistoricalsofar) of (d:_,_,_) -> d (_,Just hp,True) -> showamt $ pamount hp@@ -343,7 +347,8 @@ retryMsg "A valid hledger amount is required. Eg: 1, $2, 3 EUR, \"4 red apples\"." $ parser parseAmountAndComment $ withCompletion (amountCompleter def) $- defaultTo' def $ nonEmpty $+ defaultTo' def $ + nonEmpty $ linePrewritten (green $ printf "Amount %d%s: " pnum (showDefault def)) (fromMaybe "" $ prevAmountAndCmnt `atMay` length esPostings) "" where parseAmountAndComment s = if s == "<" then return Nothing else either (const Nothing) (return . Just) $@@ -461,12 +466,12 @@ -- | Convert a string of journal data into a register report. registerFromString :: String -> IO String registerFromString s = do- d <- getCurrentDay j <- readJournal' $ T.pack s- return $ postingsReportAsText opts $ postingsReport ropts (queryFromOpts d ropts) j+ return . postingsReportAsText opts $ postingsReport rspec j where ropts = defreportopts{empty_=True}- opts = defcliopts{reportopts_=ropts}+ rspec = defreportspec{rsOpts=ropts}+ opts = defcliopts{reportspec_=rspec} capitalize :: String -> String capitalize "" = ""
Hledger/Cli/Commands/Aregister.hs view
@@ -19,7 +19,6 @@ ,tests_Aregister ) where -import Control.Monad (when) import Data.Aeson (toJSON) import Data.Aeson.Text (encodeToLazyText) import Data.List@@ -43,7 +42,7 @@ ([ flagNone ["txn-dates"] (setboolopt "txn-dates") "filter strictly by transaction date, not posting date. Warning: this can show a wrong running balance."- ,flagNone ["no-elide"] (setboolopt "no-elide") "don't limit amount commodities shown to 2"+ ,flagNone ["no-elide"] (setboolopt "no-elide") "don't show only 2 commodities per amount" -- flagNone ["cumulative"] (setboolopt "change") -- "show running total from report start date (default)" -- ,flagNone ["historical","H"] (setboolopt "historical")@@ -72,13 +71,14 @@ -- | Print an account register report for a specified account. aregister :: CliOpts -> Journal -> IO ()-aregister opts@CliOpts{rawopts_=rawopts,reportopts_=ropts} j = do+aregister opts@CliOpts{rawopts_=rawopts,reportspec_=rspec} j = do d <- getCurrentDay -- the first argument specifies the account, any remaining arguments are a filter query- let args' = listofstringopt "args" rawopts- when (null args') $ error' "aregister needs an account, please provide an account name or pattern" -- PARTIAL:+ (apat,querystring) <- case listofstringopt "args" rawopts of+ [] -> fail "aregister needs an account, please provide an account name or pattern"+ (a:as) -> return (a, map T.pack as)+ argsquery <- either fail (return . fst) $ parseQueryList d querystring let- (apat:queryargs) = args' acct = headDef (error' $ show apat++" did not match any account") -- PARTIAL: . filterAccts $ journalAccountNames j filterAccts = case toRegexCI apat of@@ -87,14 +87,17 @@ -- gather report options inclusive = True -- tree_ ropts thisacctq = Acct $ (if inclusive then accountNameToAccountRegex else accountNameToAccountOnlyRegex) acct- ropts' = ropts{- query_=unwords $ map quoteIfNeeded $ queryargs- -- remove a depth limit for reportq, as in RegisterScreen, I forget why XXX- ,depth_=Nothing- -- always show historical balance- ,balancetype_= HistoricalBalance+ rspec' = rspec{ rsQuery=simplifyQuery $ And [queryFromFlags ropts, argsquery]+ , rsOpts=ropts'+ }+ ropts' = ropts+ { -- remove a depth limit for reportq, as in RegisterScreen, I forget why XXX+ depth_=Nothing+ -- always show historical balance+ , balancetype_= HistoricalBalance }- reportq = And [queryFromOpts d ropts', excludeforecastq (isJust $ forecast_ ropts)]+ ropts = rsOpts rspec+ reportq = And [rsQuery rspec', excludeforecastq (isJust $ forecast_ ropts')] where -- As in RegisterScreen, why ? XXX -- Except in forecast mode, exclude future/forecast transactions.@@ -106,7 +109,7 @@ ] -- run the report -- TODO: need to also pass the queries so we can choose which date to render - move them into the report ?- (balancelabel,items) = accountTransactionsReport ropts' j reportq thisacctq+ (balancelabel,items) = accountTransactionsReport rspec' j reportq thisacctq items' = (if empty_ ropts then id else filter (not . mixedAmountLooksZero . fifth6)) $ reverse items -- select renderer@@ -140,15 +143,14 @@ -- | Render a register report as plain text suitable for console output. accountTransactionsReportAsText :: CliOpts -> Query -> Query -> AccountTransactionsReport -> String accountTransactionsReportAsText- copts@CliOpts{reportopts_=ReportOpts{no_elide_}} reportq thisacctq (_balancelabel,items)+ copts@CliOpts{reportspec_=ReportSpec{rsOpts=ReportOpts{no_elide_}}} reportq thisacctq (_balancelabel,items) = unlines $ title : map (accountTransactionsReportItemAsText copts reportq thisacctq amtwidth balwidth) items where- amtwidth = maximumStrict $ 12 : map (strWidth . showamt . itemamt) items- balwidth = maximumStrict $ 12 : map (strWidth . showamt . itembal) items- showamt- | no_elide_ = showMixedAmountOneLineWithoutPrice False -- color_- | otherwise = showMixedAmountElided False+ amtwidth = maximumStrict $ 12 : map (snd . showamt . itemamt) items+ balwidth = maximumStrict $ 12 : map (snd . showamt . itembal) items+ showamt = showMixedOneLine showAmountWithoutPrice (Just 12) mmax False -- color_+ where mmax = if no_elide_ then Nothing else Just 32 itemamt (_,_,_,_,a,_) = a itembal (_,_,_,_,_,a) = a -- show a title indicating which account was picked, which can be confusing otherwise@@ -173,7 +175,7 @@ -- accountTransactionsReportItemAsText :: CliOpts -> Query -> Query -> Int -> Int -> AccountTransactionsReportItem -> String accountTransactionsReportItemAsText- copts@CliOpts{reportopts_=ReportOpts{color_,no_elide_}}+ copts@CliOpts{reportspec_=ReportSpec{rsOpts=ReportOpts{color_}}} reportq thisacctq preferredamtwidth preferredbalwidth (t@Transaction{tdescription}, _, _issplit, otheracctsstr, change, balance) -- Transaction -- the transaction, unmodified@@ -190,15 +192,15 @@ ," " ,fitString (Just acctwidth) (Just acctwidth) True True accts ," "- ,fitString (Just amtwidth) (Just amtwidth) True False amtfirstline+ ,amtfirstline ," "- ,fitString (Just balwidth) (Just balwidth) True False balfirstline+ ,balfirstline ] : [concat [spacer- ,fitString (Just amtwidth) (Just amtwidth) True False a+ ,a ," "- ,fitString (Just balwidth) (Just balwidth) True False b+ ,b ] | (a,b) <- zip amtrest balrest ]@@ -226,19 +228,16 @@ desc = T.unpack tdescription accts = -- T.unpack $ elideAccountName acctwidth $ T.pack otheracctsstr- showamt- | no_elide_ = showMixedAmountOneLineWithoutPrice color_- | otherwise = showMixedAmountElided color_- amt = showamt change- bal = showamt balance+ amt = fst $ showMixed showAmountWithoutPrice (Just amtwidth) (Just balwidth) color_ change+ bal = fst $ showMixed showAmountWithoutPrice (Just balwidth) (Just balwidth) color_ balance -- alternate behaviour, show null amounts as 0 instead of blank -- amt = if null amt' then "0" else amt' -- bal = if null bal' then "0" else bal' (amtlines, ballines) = (lines amt, lines bal) (amtlen, ballen) = (length amtlines, length ballines) numlines = max 1 (max amtlen ballen)- (amtfirstline:amtrest) = take numlines $ amtlines ++ repeat "" -- posting amount is top-aligned- (balfirstline:balrest) = take numlines $ replicate (numlines - ballen) "" ++ ballines -- balance amount is bottom-aligned+ (amtfirstline:amtrest) = take numlines $ amtlines ++ repeat (replicate amtwidth ' ') -- posting amount is top-aligned+ (balfirstline:balrest) = take numlines $ replicate (numlines - ballen) (replicate balwidth ' ') ++ ballines -- balance amount is bottom-aligned spacer = replicate (totalwidth - (amtwidth + 2 + balwidth)) ' ' -- tests
Hledger/Cli/Commands/Balance.hs view
@@ -232,12 +232,13 @@ -} -{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE CPP #-} {-# LANGUAGE ExtendedDefaultRules #-}-{-# LANGUAGE RecordWildCards #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE TemplateHaskell #-}-{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-} module Hledger.Cli.Commands.Balance ( balancemode@@ -253,17 +254,20 @@ ,tests_Balance ) where -import Data.List-import Data.Maybe+import Data.Default (def)+import Data.List (intercalate, transpose)+import Data.Maybe (fromMaybe, maybeToList) --import qualified Data.Map as Map+#if !(MIN_VERSION_base(4,11,0))+import Data.Semigroup ((<>))+#endif import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.Time (fromGregorian) import System.Console.CmdArgs.Explicit as C import Lucid as L-import Text.Printf (printf) import Text.Tabular as T---import Text.Tabular.AsciiWide+import Text.Tabular.AsciiWide as T import Hledger import Hledger.Cli.CliOptions@@ -286,7 +290,7 @@ ,flagNone ["average","A"] (setboolopt "average") "show a row average column (in multicolumn reports)" ,flagNone ["row-total","T"] (setboolopt "row-total") "show a row total column (in multicolumn reports)" ,flagNone ["no-total","N"] (setboolopt "no-total") "omit the final total row"- ,flagNone ["no-elide"] (setboolopt "no-elide") "don't squash boring parent accounts (in tree mode)"+ ,flagNone ["no-elide"] (setboolopt "no-elide") "don't squash boring parent accounts (in tree mode); don't show only 2 commodities per amount" ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format (in simple reports)" ,flagNone ["pretty-tables"] (setboolopt "pretty-tables") "use unicode to display prettier tables" ,flagNone ["sort-amount","S"] (setboolopt "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."@@ -304,46 +308,48 @@ -- | The balance command, prints a balance report. balance :: CliOpts -> Journal -> IO ()-balance opts@CliOpts{rawopts_=rawopts,reportopts_=ropts@ReportOpts{..}} j = do- d <- getCurrentDay- case lineFormatFromOpts ropts of- Left err -> error' $ unlines [err] -- PARTIAL:- Right _ -> do- let budget = boolopt "budget" rawopts- multiperiod = interval_ /= NoInterval- fmt = outputFormatFromOpts opts+balance opts@CliOpts{rawopts_=rawopts,reportspec_=rspec} j = do+ let ropts@ReportOpts{..} = rsOpts rspec+ budget = boolopt "budget" rawopts+ multiperiod = interval_ /= NoInterval+ fmt = outputFormatFromOpts opts - if budget then do -- single or multi period budget report- reportspan <- reportSpan j ropts- let budgetreport = dbg4 "budgetreport" $ budgetReport ropts assrt reportspan d j- where- assrt = not $ ignore_assertions_ $ inputopts_ opts+ if budget then do -- single or multi period budget report+ let reportspan = reportSpan j rspec+ budgetreport = budgetReport rspec assrt reportspan j+ where+ assrt = not $ ignore_assertions_ $ inputopts_ opts+ render = case fmt of+ "txt" -> budgetReportAsText ropts+ "json" -> (++"\n") . TL.unpack . toJsonText+ "csv" -> (++"\n") . printCSV . budgetReportAsCsv ropts+ _ -> const $ error' $ unsupportedOutputFormatError fmt+ writeOutput opts $ render budgetreport++ else+ if multiperiod then do -- multi period balance report+ let report = multiBalanceReport rspec j render = case fmt of- "txt" -> budgetReportAsText ropts+ "txt" -> multiBalanceReportAsText ropts+ "csv" -> (++"\n") . printCSV . multiBalanceReportAsCsv ropts+ "html" -> (++"\n") . TL.unpack . L.renderText . multiBalanceReportAsHtml ropts "json" -> (++"\n") . TL.unpack . toJsonText- _ -> const $ error' $ unsupportedOutputFormatError fmt- writeOutput opts $ render budgetreport+ _ -> const $ error' $ unsupportedOutputFormatError fmt -- PARTIAL:+ writeOutput opts $ render report - else- if multiperiod then do -- multi period balance report- let report = multiBalanceReport d ropts j- render = case fmt of- "txt" -> multiBalanceReportAsText ropts- "csv" -> (++"\n") . printCSV . multiBalanceReportAsCsv ropts- "html" -> (++"\n") . TL.unpack . L.renderText . multiBalanceReportAsHtml ropts- "json" -> (++"\n") . TL.unpack . toJsonText- _ -> const $ error' $ unsupportedOutputFormatError fmt- writeOutput opts $ render report+ else do -- single period simple balance report+ let report = balanceReport rspec j -- simple Ledger-style balance report+ render = case fmt of+ "txt" -> balanceReportAsText+ "csv" -> \ropts r -> (++ "\n") $ printCSV $ balanceReportAsCsv ropts r+ "json" -> const $ (++"\n") . TL.unpack . toJsonText+ _ -> const $ error' $ unsupportedOutputFormatError fmt -- PARTIAL:+ writeOutput opts $ render ropts report - else do -- single period simple balance report- let report = balanceReport ropts (queryFromOpts d ropts) j -- simple Ledger-style balance report- render = case fmt of- "txt" -> balanceReportAsText- "csv" -> \ropts r -> (++ "\n") $ printCSV $ balanceReportAsCsv ropts r- "json" -> const $ (++"\n") . TL.unpack . toJsonText- _ -> const $ error' $ unsupportedOutputFormatError fmt- writeOutput opts $ render ropts report +-- XXX should all the per-report, per-format rendering code live in the command module,+-- like the below, or in the report module, like budgetReportAsText/budgetReportAsCsv ?+ -- rendering single-column balance reports -- | Render a single-column balance report as CSV.@@ -358,28 +364,17 @@ -- | Render a single-column balance report as plain text. balanceReportAsText :: ReportOpts -> BalanceReport -> String-balanceReportAsText opts ((items, total)) = unlines $ concat lines ++ t+balanceReportAsText opts ((items, total)) = unlines $+ concat lines ++ if no_total_ opts then [] else overline : totallines where- fmt = lineFormatFromOpts opts- lines = case fmt of- Right fmt -> map (balanceReportItemAsText opts fmt) items- Left err -> [[err]]- t = if no_total_ opts- then []- else- case fmt of- Right fmt ->- let- -- abuse renderBalanceReportItem to render the total with similar format- acctcolwidth = maximum' [T.length fullname | (fullname, _, _, _) <- items]- totallines = map rstrip $ renderBalanceReportItem opts fmt (T.replicate (acctcolwidth+1) " ", 0, total)- -- with a custom format, extend the line to the full report width;- -- otherwise show the usual 20-char line for compatibility- overlinewidth | isJust (format_ opts) = maximum' $ map length $ concat lines- | otherwise = defaultTotalFieldWidth- overline = replicate overlinewidth '-'- in overline : totallines- Left _ -> []+ lines = map (balanceReportItemAsText opts) items+ -- abuse renderBalanceReportItem to render the total with similar format+ acctcolwidth = maximum' [T.length fullname | (fullname, _, _, _) <- items]+ totallines = map rstrip $ renderBalanceReportItem opts (T.replicate (acctcolwidth+1) " ", 0, total)+ -- with a custom format, extend the line to the full report width;+ -- otherwise show the usual 20-char line for compatibility+ overlinewidth = fromMaybe (maximum' . map length $ concat lines) . overlineWidth $ format_ opts+ overline = replicate overlinewidth '-' {- :r@@ -396,28 +391,25 @@ -- whatever string format is specified). Note, prices will not be rendered, and -- differently-priced quantities of the same commodity will appear merged. -- The output will be one or more lines depending on the format and number of commodities.-balanceReportItemAsText :: ReportOpts -> StringFormat -> BalanceReportItem -> [String]-balanceReportItemAsText opts fmt (_, accountName, depth, amt) =- renderBalanceReportItem opts fmt (+balanceReportItemAsText :: ReportOpts -> BalanceReportItem -> [String]+balanceReportItemAsText opts (_, accountName, depth, amt) =+ renderBalanceReportItem opts ( accountName, depth, normaliseMixedAmountSquashPricesForDisplay amt ) -- | Render a balance report item using the given StringFormat, generating one or more lines of text.-renderBalanceReportItem :: ReportOpts -> StringFormat -> (AccountName, Int, MixedAmount) -> [String]-renderBalanceReportItem opts fmt (acctname, depth, total) =- lines $- case fmt of- OneLine comps -> concatOneLine $ render1 comps- TopAligned comps -> concatBottomPadded $ render comps- BottomAligned comps -> concatTopPadded $ render comps+renderBalanceReportItem :: ReportOpts -> (AccountName, Int, MixedAmount) -> [String]+renderBalanceReportItem opts (acctname, depth, total) =+ lines $ case format_ opts of+ OneLine _ comps -> concatOneLine $ render1 comps+ TopAligned _ comps -> concatBottomPadded $ render comps+ BottomAligned _ comps -> concatTopPadded $ render comps where render1 = map (renderComponent1 opts (acctname, depth, total)) render = map (renderComponent opts (acctname, depth, total)) -defaultTotalFieldWidth = 20- -- | Render one StringFormat component for a balance report item. renderComponent :: ReportOpts -> (AccountName, Int, MixedAmount) -> StringFormatComponent -> String renderComponent _ _ (FormatLiteral s) = s@@ -427,7 +419,7 @@ Just m -> depth * m Nothing -> depth AccountField -> formatString ljust min max (T.unpack acctname)- TotalField -> fitStringMulti min max True False $ showMixedAmountWithoutPrice (color_ opts) total+ TotalField -> fst $ showMixed showAmountWithoutPrice min max (color_ opts) total _ -> "" -- | Render one StringFormat component for a balance report item.@@ -442,9 +434,7 @@ -- better to indent the account name here rather than use a DepthField component -- so that it complies with width spec. Uses a fixed indent step size. indented = ((replicate (depth*2) ' ')++)- TotalField -> fitStringMulti min max True False $ ((intercalate ", " . map strip . lines) (showamt total))- where- showamt = showMixedAmountWithoutPrice (color_ opts)+ TotalField -> fst $ showMixedOneLine showAmountWithoutPrice min max (color_ opts) total _ -> "" -- rendering multi-column balance reports@@ -495,7 +485,7 @@ multiBalanceReportHtmlRows :: ReportOpts -> MultiBalanceReport -> (Html (), [Html ()], Maybe (Html ())) multiBalanceReportHtmlRows ropts mbr = let- headingsrow:rest | transpose_ ropts = error' "Sorry, --transpose is not supported with HTML output yet" -- PARTIAL:+ headingsrow:rest | transpose_ ropts = error' "Sorry, --transpose with HTML output is not yet supported" -- PARTIAL: | otherwise = multiBalanceReportAsCsv ropts mbr (bodyrows, mtotalsrow) | no_total_ ropts = (rest, Nothing) | otherwise = (init rest, Just $ last rest)@@ -573,24 +563,32 @@ multiBalanceReportAsText ropts@ReportOpts{..} r = title ++ "\n\n" ++ (balanceReportTableAsText ropts $ balanceReportAsTable ropts r) where- multiperiod = interval_ /= NoInterval- title = printf "%s in %s%s:"- (case balancetype_ of- PeriodChange -> "Balance changes"- CumulativeChange -> "Ending balances (cumulative)"- HistoricalBalance -> "Ending balances (historical)")- (showDateSpan $ periodicReportSpan r)- (case value_ of- Just (AtCost _mc) -> ", valued at cost"- Just (AtThen _mc) -> error' unsupportedValueThenError -- TODO -- ", valued at period ends" -- handled like AtEnd for now -- PARTIAL:- Just (AtEnd _mc) -> ", valued at period ends"- Just (AtNow _mc) -> ", current value"+ title = mtitle <> " in " <> showDateSpan (periodicReportSpan r) <> valuationdesc <> ":"++ mtitle = case balancetype_ of+ PeriodChange | changingValuation -> "Period-end value changes"+ PeriodChange -> "Balance changes"+ CumulativeChange -> "Ending balances (cumulative)"+ HistoricalBalance -> "Ending balances (historical)"+ valuationdesc = case value_ of+ Just (AtCost _mc) -> ", valued at cost"+ Just (AtThen _mc) -> error' unsupportedValueThenError -- TODO -- ", valued at period ends" -- handled like AtEnd for now -- PARTIAL:+ Just (AtEnd _mc) | changingValuation -> ""+ Just (AtEnd _mc) -> ", valued at period ends"+ Just (AtNow _mc) -> ", current value" -- XXX duplicates the above- Just (AtDefault _mc) | multiperiod -> ", valued at period ends"+ Just (AtDefault _mc) | changingValuation -> ""+ Just (AtDefault _mc) | multiperiod -> ", valued at period ends" Just (AtDefault _mc) -> ", current value"- Just (AtDate d _mc) -> ", valued at "++showDate d- Nothing -> "")+ Just (AtDate d _mc) -> ", valued at "++showDate d+ Nothing -> "" + multiperiod = interval_ /= NoInterval+ changingValuation+ | PeriodChange <- balancetype_, Just (AtEnd _mc) <- value_ = multiperiod+ | PeriodChange <- balancetype_, Just (AtDefault _mc) <- value_ = multiperiod+ | otherwise = False+ -- | Build a 'Table' from a multi-column balance report. balanceReportAsTable :: ReportOpts -> MultiBalanceReport -> Table String String MixedAmount balanceReportAsTable opts@ReportOpts{average_, row_total_, balancetype_}@@ -626,11 +624,12 @@ -- console output. Amounts with more than two commodities will be elided -- unless --no-elide is used. balanceReportTableAsText :: ReportOpts -> Table String String MixedAmount -> String-balanceReportTableAsText ropts@ReportOpts{..} = tableAsText ropts showamt+balanceReportTableAsText ReportOpts{..} =+ T.renderTable def{tableBorders=False, prettyTable=pretty_tables_}+ (T.alignCell TopLeft) (T.alignCell TopRight) showamt where- showamt- | no_elide_ = showMixedAmountOneLineWithoutPrice color_- | otherwise = showMixedAmountElided color_+ showamt = Cell TopRight . pure . showMixedOneLine showAmountWithoutPrice Nothing mmax color_+ mmax = if no_elide_ then Nothing else Just 32 tests_Balance = tests "Balance" [@@ -638,8 +637,8 @@ tests "balanceReportAsText" [ test "unicode in balance layout" $ do j <- readJournal' "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n"- let opts = defreportopts- balanceReportAsText opts (balanceReport opts (queryFromOpts (fromGregorian 2008 11 26) opts) j)+ let rspec = defreportspec+ balanceReportAsText (rsOpts rspec) (balanceReport rspec{rsToday=fromGregorian 2008 11 26} j) @?= unlines [" -100 актив:наличные"
Hledger/Cli/Commands/Balance.txt view
@@ -45,9 +45,8 @@ 0 By default, accounts are displayed hierarchically, with subaccounts-indented below their parent. At each level of the tree, accounts are-sorted by account code if any, then by account name. Or with--S/--sort-amount, by their balance amount, largest first.+indented below their parent, with accounts at each level of the tree+sorted by declaration order if declared, then by account name. "Boring" accounts, which contain a single interesting subaccount and no balance of their own, are elided into the following line for more@@ -186,6 +185,18 @@ accounts. If there are mixed commodity accounts in the report be sure to use -V or -B to coerce the report into using a single commodity. +Sorting by amount++With -S/--sort-amount, accounts with the largest (most positive)+balances are shown first. For example, hledger bal expenses -MAS shows+your biggest averaged monthly expenses first.++Revenues and liability balances are typically negative, however, so -S+shows these in reverse order. To work around this, you can add --invert+to flip the signs. Or, use one of the sign-flipping reports like+balancesheet or incomestatement, which also support -S. Eg:+hledger is -MAS.+ Multicolumn balance report Multicolumn or tabular balance reports are a very useful hledger@@ -415,8 +426,48 @@ ----------------------++---------------------------------------------------- || 0 [ 0] 0 [ 0] -For more examples, see Budgeting and Forecasting.+For more examples and notes, see Budgeting. +Budget report start date++This might be a bug, but for now: when making budget reports, it's a+good idea to explicitly set the report's start date to the first day of+a reporting period, because a periodic rule like ~ monthly generates its+transactions on the 1st of each month, and if your journal has no+regular transactions on the 1st, the default report start date could+exclude that budget goal, which can be a little surprising. Eg here the+default report period is just the day of 2020-01-15:++~ monthly in 2020+ (expenses:food) $500++2020-01-15+ expenses:food $400+ assets:checking++$ hledger bal expenses --budget+Budget performance in 2020-01-15:++ || 2020-01-15 +==============++============+ <unbudgeted> || $400 +--------------++------------+ || $400 ++To avoid this, specify the budget report's period, or at least the start+date, with -b/-e/-p/date:, to ensure it includes the budget goal+transactions (periodic transactions) that you want. Eg, adding+-b 2020/1/1 to the above:++$ hledger bal expenses --budget -b 2020/1/1+Budget performance in 2020-01-01..2020-01-15:++ || 2020-01-01..2020-01-15 +===============++========================+ expenses:food || $400 [80% of $500] +---------------++------------------------+ || $400 [80% of $500] + Nested budgets You can add budgets to any account in your account hierarchy. If you@@ -505,5 +556,5 @@ Output format This command also supports the output destination and output format-options The output formats supported are txt, csv, (multicolumn-non-budget reports only) html, and (experimental) json.+options The output formats supported are (in most modes): txt, csv,+html, and json.
Hledger/Cli/Commands/Balancesheet.hs view
@@ -24,13 +24,15 @@ CBCSubreportSpec{ cbcsubreporttitle="Assets" ,cbcsubreportquery=journalAssetAccountQuery- ,cbcsubreportnormalsign=NormallyPositive+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyPositive})+ ,cbcsubreporttransform=id ,cbcsubreportincreasestotal=True } ,CBCSubreportSpec{ cbcsubreporttitle="Liabilities" ,cbcsubreportquery=journalLiabilityAccountQuery- ,cbcsubreportnormalsign=NormallyNegative+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyNegative})+ ,cbcsubreporttransform=fmap negate ,cbcsubreportincreasestotal=False } ],
Hledger/Cli/Commands/Balancesheetequity.hs view
@@ -24,19 +24,22 @@ CBCSubreportSpec{ cbcsubreporttitle="Assets" ,cbcsubreportquery=journalAssetAccountQuery- ,cbcsubreportnormalsign=NormallyPositive+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyPositive})+ ,cbcsubreporttransform=id ,cbcsubreportincreasestotal=True } ,CBCSubreportSpec{ cbcsubreporttitle="Liabilities" ,cbcsubreportquery=journalLiabilityAccountQuery- ,cbcsubreportnormalsign=NormallyNegative+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyNegative})+ ,cbcsubreporttransform=fmap negate ,cbcsubreportincreasestotal=False } ,CBCSubreportSpec{ cbcsubreporttitle="Equity" ,cbcsubreportquery=journalEquityAccountQuery- ,cbcsubreportnormalsign=NormallyNegative+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyNegative})+ ,cbcsubreporttransform=fmap negate ,cbcsubreportincreasestotal=False } ],
Hledger/Cli/Commands/Cashflow.hs view
@@ -27,7 +27,8 @@ CBCSubreportSpec{ cbcsubreporttitle="Cash flows" ,cbcsubreportquery=journalCashAccountQuery- ,cbcsubreportnormalsign=NormallyPositive+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_= Just NormallyPositive})+ ,cbcsubreporttransform=id ,cbcsubreportincreasestotal=True } ],
+ Hledger/Cli/Commands/Check.hs view
@@ -0,0 +1,88 @@+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Check (+ checkmode+ ,check+) where++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Commands.Checkdupes (checkdupes)+import Hledger.Cli.Commands.Checkdates (checkdates)+import System.Console.CmdArgs.Explicit+import Data.Either (partitionEithers)+import Data.Char (toUpper)+import Safe (readMay)+import Control.Monad (forM_)++checkmode :: Mode RawOpts+checkmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Check.txt")+ []+ [generalflagsgroup1]+ hiddenflags+ ([], Just $ argsFlag "[CHECKS]")++check :: CliOpts -> Journal -> IO ()+check copts@CliOpts{rawopts_} j = do+ let + args = listofstringopt "args" rawopts_+ -- reset the report spec that was generated by argsToCliOpts,+ -- since we are not using arguments as a query in the usual way+ copts' = cliOptsUpdateReportSpec (\ropts -> ropts{querystring_=[]}) copts++ case partitionEithers (map parseCheckArgument args) of+ (unknowns@(_:_), _) -> error' $ "These checks are unknown: "++unwords unknowns+ ([], checks) -> forM_ checks $ runCheck copts' j+ +-- | A type of error check that we can perform on the data.+data Check =+ Ordereddates+ | Uniqueleafnames+ deriving (Read,Show,Eq)++-- | Parse the name of an error check, or return the name unparsed.+-- Names are conventionally all lower case, but this parses case insensitively.+parseCheck :: String -> Either String Check+parseCheck s = maybe (Left s) Right $ readMay $ capitalise s++capitalise :: String -> String+capitalise (c:cs) = toUpper c : cs+capitalise s = s++-- | Parse a check argument: a string which is the lower-case name of an error check,+-- followed by zero or more space-separated arguments for that check.+parseCheckArgument :: String -> Either String (Check,[String])+parseCheckArgument s =+ dbg3 "check argument" $+ ((,checkargs)) <$> parseCheck checkname+ where+ (checkname:checkargs) = words' s++-- | Run the named error check, possibly with some arguments, +-- on this journal with these options.+runCheck :: CliOpts -> Journal -> (Check,[String]) -> IO ()+runCheck copts@CliOpts{rawopts_} j (check,args) = + case check of+ Ordereddates -> checkdates copts' j+ Uniqueleafnames -> checkdupes copts' j+ where+ -- Hack: append the provided args to the raw opts,+ -- in case the check can use them (like checkdates --unique). + -- Does not bother to regenerate the derived data (ReportOpts, ReportSpec..), + -- so those may be inconsistent.+ copts' = copts{rawopts_=appendopts (map (,"") args) rawopts_}++-- | Regenerate this CliOpts' report specification, after updating its+-- underlying report options with the given update function.+-- This can raise an error if there is a problem eg due to missing or+-- unparseable options data. See also updateReportSpecFromOpts.+cliOptsUpdateReportSpec :: (ReportOpts -> ReportOpts) -> CliOpts -> CliOpts+cliOptsUpdateReportSpec roptsupdate copts@CliOpts{reportspec_} =+ case updateReportSpecFromOpts roptsupdate reportspec_ of+ Left e -> error' e -- PARTIAL:+ Right rs -> copts{reportspec_=rs}
+ Hledger/Cli/Commands/Check.txt view
@@ -0,0 +1,64 @@+check+Check for various kinds of errors in your data. experimental++_FLAGS++hledger provides a number of built-in error checks to help prevent+problems in your data. Some of these are run automatically; or, you can+use this check command to run them on demand, with no output and a zero+exit code if all is well. Some examples:++hledger check # basic checks+hledger check -s # basic + strict checks+hledger check ordereddates uniqueleafnames # basic + specified checks++Here are the checks currently available:++Basic checks++These are always run by this command and other commands:++- parseable - data files are well-formed and can be successfully+ parsed++- autobalanced - all transactions are balanced, inferring missing+ amounts where necessary, and possibly converting commodities using+ transaction prices or automatically-inferred transaction prices++- assertions - all balance assertions in the journal are passing.+ (This check can be disabled with -I/--ignore-assertions.)++Strict checks++These are always run by this and other commands when -s/--strict is used+(strict mode):++- accounts - all account names used by transactions have been declared++- commodities - all commodity symbols used have been declared++Other checks++These checks can be run by specifying their names as arguments to the+check command:++- ordereddates - transactions are ordered by date (similar to the old+ check-dates command)++- uniqueleafnames - all account leaf names are unique (similar to the+ old check-dupes command)++Addon checks++Some checks are not yet integrated with this command, but are available+as add-on commands in+https://github.com/simonmichael/hledger/tree/master/bin:++- hledger-check-tagfiles - all tag values containing / (a forward+ slash) exist as file paths++- hledger-check-fancyassertions - more complex balance assertions are+ passing++You could make your own similar scripts to perform custom checks;+Cookbook -> Scripting may be helpful.
Hledger/Cli/Commands/Checkdates.hs view
@@ -15,38 +15,36 @@ checkdatesmode :: Mode RawOpts checkdatesmode = hledgerCommandMode $(embedFileRelative "Hledger/Cli/Commands/Checkdates.txt")- [flagNone ["strict"] (setboolopt "strict") "makes date comparing strict"]+ [flagNone ["unique"] (setboolopt "unique") "require that dates are unique"] [generalflagsgroup1] hiddenflags ([], Just $ argsFlag "[QUERY]") checkdates :: CliOpts -> Journal -> IO ()-checkdates CliOpts{rawopts_=rawopts,reportopts_=ropts} j = do- d <- getCurrentDay- let ropts_ = ropts{accountlistmode_=ALFlat}- let q = queryFromOpts d ropts_- let ts = filter (q `matchesTransaction`) $+checkdates CliOpts{rawopts_=rawopts,reportspec_=rspec} j = do+ let ropts = (rsOpts rspec){accountlistmode_=ALFlat}+ let ts = filter (rsQuery rspec `matchesTransaction`) $ jtxns $ journalSelectingAmountFromOpts ropts j- let strict = boolopt "strict" rawopts+ -- pprint rawopts+ let unique = boolopt "--unique" rawopts -- TEMP: it's this for hledger check dates+ || boolopt "unique" rawopts -- and this for hledger check-dates (for some reason) let date = transactionDateFn ropts let compare a b =- if strict+ if unique then date a < date b else date a <= date b case checkTransactions compare ts of- FoldAcc{fa_previous=Nothing} -> putStrLn "ok (empty journal)" >> exitSuccess- FoldAcc{fa_error=Nothing} -> putStrLn "ok" >> exitSuccess- FoldAcc{fa_error=Just error, fa_previous=Just previous} ->- (putStrLn $ printf ("ERROR: transaction out of%s date order"- ++ "\nPrevious date: %s"- ++ "\nDate: %s"- ++ "\nLocation: %s"- ++ "\nTransaction:\n\n%s")- (if strict then " STRICT" else "")- (show $ date previous)- (show $ date error)- (show $ tsourcepos error)- (showTransaction error)) >> exitFailure+ FoldAcc{fa_previous=Nothing} -> return ()+ FoldAcc{fa_error=Nothing} -> return ()+ FoldAcc{fa_error=Just error, fa_previous=Just previous} -> do+ putStrLn $ printf + ("Error: transaction's date is not in date order%s,\n"+ ++ "at %s:\n\n%sPrevious transaction's date was: %s")+ (if unique then " and/or not unique" else "")+ (showGenericSourcePos $ tsourcepos error)+ (showTransaction error)+ (show $ date previous)+ exitFailure data FoldAcc a b = FoldAcc { fa_error :: Maybe a
Hledger/Cli/Commands/Checkdupes.hs view
@@ -14,6 +14,8 @@ import Hledger.Cli.CliOptions import System.Console.CmdArgs.Explicit import Text.Printf+import System.Exit (exitFailure)+import Control.Monad (when) checkdupesmode :: Mode RawOpts checkdupesmode = hledgerCommandMode@@ -23,7 +25,11 @@ hiddenflags ([], Nothing) -checkdupes _opts j = mapM_ render $ checkdupes' $ accountsNames j+checkdupes _opts j = do+ let dupes = checkdupes' $ accountsNames j+ when (not $ null dupes) $ do+ mapM_ render dupes+ exitFailure accountsNames :: Journal -> [(String, AccountName)] accountsNames j = map leafAndAccountName as
Hledger/Cli/Commands/Close.hs view
@@ -46,8 +46,8 @@ ([], Just $ argsFlag "[QUERY]") -- debugger, beware: close is incredibly devious. simple rules combine to make a horrid maze.--- tests are in tests/close.test.-close CliOpts{rawopts_=rawopts, reportopts_=ropts} j = do+-- tests are in hledger/test/close.test.+close CliOpts{rawopts_=rawopts, reportspec_=rspec} j = do today <- getCurrentDay let -- show opening entry, closing entry, or (default) both ?@@ -72,8 +72,9 @@ (Nothing, Nothing) -> (T.pack defclosingacct, T.pack defopeningacct) -- dates of the closing and opening transactions- ropts_ = ropts{balancetype_=HistoricalBalance, accountlistmode_=ALFlat}- q = queryFromOpts today ropts_+ rspec_ = rspec{rsOpts=ropts}+ ropts = (rsOpts rspec){balancetype_=HistoricalBalance, accountlistmode_=ALFlat}+ q = rsQuery rspec openingdate = fromMaybe today $ queryEndDate False q closingdate = addDays (-1) openingdate @@ -86,7 +87,7 @@ False -> normaliseMixedAmount . mixedAmountStripPrices -- the balances to close- (acctbals,_) = balanceReport ropts_ q j+ (acctbals,_) = balanceReport rspec_ j totalamt = sum $ map (\(_,_,_,b) -> normalise b) acctbals -- since balance assertion amounts are required to be exact, the
Hledger/Cli/Commands/Codes.hs view
@@ -32,11 +32,8 @@ -- | The codes command. codes :: CliOpts -> Journal -> IO ()-codes CliOpts{reportopts_=ropts@ReportOpts{empty_}} j = do- d <- getCurrentDay- let q = queryFromOpts d ropts- ts = entriesReport ropts q j- codes = (if empty_ then id else filter (not . T.null)) $+codes CliOpts{reportspec_=rspec} j = do+ let ts = entriesReport rspec j+ codes = (if empty_ (rsOpts rspec) then id else filter (not . T.null)) $ map tcode ts- mapM_ T.putStrLn codes
Hledger/Cli/Commands/Descriptions.hs view
@@ -31,10 +31,8 @@ -- | The descriptions command. descriptions :: CliOpts -> Journal -> IO ()-descriptions CliOpts{reportopts_=ropts} j = do- d <- getCurrentDay- let q = queryFromOpts d ropts- ts = entriesReport ropts q j+descriptions CliOpts{reportspec_=rspec} j = do+ let ts = entriesReport rspec j descriptions = nubSort $ map tdescription ts mapM_ T.putStrLn descriptions
Hledger/Cli/Commands/Diff.hs view
@@ -102,11 +102,11 @@ -- | The diff command. diff :: CliOpts -> Journal -> IO ()-diff CliOpts{file_=[f1, f2], reportopts_=ReportOpts{query_=acctName}} _ = do+diff CliOpts{file_=[f1, f2], reportspec_=ReportSpec{rsQuery=Acct acctRe}} _ = do j1 <- readJournalFile' f1 j2 <- readJournalFile' f2 - let acct = T.pack acctName+ let acct = T.pack $ reString acctRe let pp1 = matchingPostings acct j1 let pp2 = matchingPostings acct j2
Hledger/Cli/Commands/Import.hs view
@@ -32,7 +32,7 @@ inputstr = intercalate ", " $ map quoteIfNeeded inputfiles catchup = boolopt "catchup" rawopts dryrun = boolopt "dry-run" rawopts- iopts' = iopts{new_=True, new_save_=not dryrun}+ iopts' = iopts{new_=True, new_save_=not dryrun, commoditystyles_=Just $ journalCommodityStyles j} case inputfiles of [] -> error' "please provide one or more input files as arguments" -- PARTIAL: fs -> do
Hledger/Cli/Commands/Import.txt view
@@ -33,3 +33,8 @@ (If you think import should leave amounts implicit like print does, please test it and send a pull request.)++Commodity display styles++Imported amounts will be formatted according to the canonical commodity+styles (declared or inferred) in the main journal file.
Hledger/Cli/Commands/Incomestatement.hs view
@@ -23,13 +23,15 @@ CBCSubreportSpec{ cbcsubreporttitle="Revenues" ,cbcsubreportquery=journalRevenueAccountQuery- ,cbcsubreportnormalsign=NormallyNegative+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyNegative})+ ,cbcsubreporttransform=fmap negate ,cbcsubreportincreasestotal=True } ,CBCSubreportSpec{ cbcsubreporttitle="Expenses" ,cbcsubreportquery=journalExpenseAccountQuery- ,cbcsubreportnormalsign=NormallyPositive+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyPositive})+ ,cbcsubreporttransform=id ,cbcsubreportincreasestotal=False } ],
Hledger/Cli/Commands/Notes.hs view
@@ -32,10 +32,7 @@ -- | The notes command. notes :: CliOpts -> Journal -> IO ()-notes CliOpts{reportopts_=ropts} j = do- d <- getCurrentDay- let q = queryFromOpts d ropts- ts = entriesReport ropts q j+notes CliOpts{reportspec_=rspec} j = do+ let ts = entriesReport rspec j notes = nubSort $ map transactionNote ts- mapM_ T.putStrLn notes
Hledger/Cli/Commands/Payees.hs view
@@ -32,10 +32,7 @@ -- | The payees command. payees :: CliOpts -> Journal -> IO ()-payees CliOpts{reportopts_=ropts} j = do- d <- getCurrentDay- let q = queryFromOpts d ropts- ts = entriesReport ropts q j+payees CliOpts{reportspec_=rspec} j = do+ let ts = entriesReport rspec j payees = nubSort $ map transactionPayee ts- mapM_ T.putStrLn payees
Hledger/Cli/Commands/Prices.hs view
@@ -25,10 +25,9 @@ -- XXX the original hledger-prices script always ignored assertions prices opts j = do- d <- getCurrentDay let styles = journalCommodityStyles j- q = queryFromOpts d (reportopts_ opts)+ q = rsQuery $ reportspec_ opts ps = filter (matchesPosting q) $ allPostings j mprices = jpricedirectives j cprices = map (stylePriceDirectiveExceptPrecision styles) $ concatMap postingsPriceDirectivesFromCosts ps
Hledger/Cli/Commands/Print.hs view
@@ -53,17 +53,15 @@ Just desc -> printMatch opts j $ T.pack desc printEntries :: CliOpts -> Journal -> IO ()-printEntries opts@CliOpts{reportopts_=ropts} j = do- d <- getCurrentDay- let q = queryFromOpts d ropts- fmt = outputFormatFromOpts opts+printEntries opts@CliOpts{reportspec_=rspec} j = do+ let fmt = outputFormatFromOpts opts render = case fmt of "txt" -> entriesReportAsText opts "csv" -> (++"\n") . printCSV . entriesReportAsCsv "json" -> (++"\n") . TL.unpack . toJsonText "sql" -> entriesReportAsSql _ -> const $ error' $ unsupportedOutputFormatError fmt -- PARTIAL:- writeOutput opts $ render $ entriesReport ropts q j+ writeOutput opts $ render $ entriesReport rspec j entriesReportAsText :: CliOpts -> EntriesReport -> String entriesReportAsText opts = concatMap (showTransaction . whichtxn)@@ -75,7 +73,7 @@ -- Because of #551, and because of print -V valuing only one -- posting when there's an implicit txn price. -- So -B/-V/-X/--value implies -x. Is this ok ?- || (isJust $ value_ $ reportopts_ opts) = id+ || (isJust . value_ . rsOpts $ reportspec_ opts) = id -- By default, use the original as-written-in-the-journal txn. | otherwise = originalTransaction @@ -184,12 +182,10 @@ -- | Print the transaction most closely and recently matching a description -- (and the query, if any). printMatch :: CliOpts -> Journal -> Text -> IO ()-printMatch CliOpts{reportopts_=ropts} j desc = do- d <- getCurrentDay- let q = queryFromOpts d ropts- case similarTransaction' j q desc of- Nothing -> putStrLn "no matches found."- Just t -> putStr $ showTransaction t+printMatch CliOpts{reportspec_=rspec} j desc = do+ case similarTransaction' j (rsQuery rspec) desc of+ Nothing -> putStrLn "no matches found."+ Just t -> putStr $ showTransaction t where -- Identify the closest recent match for this description in past transactions.
Hledger/Cli/Commands/Register.hs view
@@ -23,7 +23,6 @@ -- import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as TL-import Data.Time (fromGregorian) import System.Console.CmdArgs.Explicit import Hledger.Read.CsvReader (CSV, CsvRecord, printCSV) @@ -59,14 +58,13 @@ -- | Print a (posting) register report. register :: CliOpts -> Journal -> IO ()-register opts@CliOpts{reportopts_=ropts} j = do- d <- getCurrentDay+register opts@CliOpts{reportspec_=rspec} j = do let fmt = outputFormatFromOpts opts render | fmt=="txt" = postingsReportAsText | fmt=="csv" = const ((++"\n") . printCSV . postingsReportAsCsv) | fmt=="json" = const ((++"\n") . TL.unpack . toJsonText) | otherwise = const $ error' $ unsupportedOutputFormatError fmt -- PARTIAL:- writeOutput opts $ render opts $ postingsReport ropts (queryFromOpts d ropts) j+ writeOutput opts . render opts $ postingsReport rspec j postingsReportAsCsv :: PostingsReport -> CSV postingsReportAsCsv (_,is) =@@ -94,8 +92,8 @@ postingsReportAsText :: CliOpts -> PostingsReport -> String postingsReportAsText opts (_,items) = unlines $ map (postingsReportItemAsText opts amtwidth balwidth) items where- amtwidth = maximumStrict $ 12 : map (strWidth . showMixedAmount . itemamt) items- balwidth = maximumStrict $ 12 : map (strWidth . showMixedAmount . itembal) items+ amtwidth = maximumStrict $ map (snd . showMixed showAmount (Just 12) Nothing False . itemamt) items+ balwidth = maximumStrict $ map (snd . showMixed showAmount (Just 12) Nothing False . itembal) items itemamt (_,_,_,Posting{pamount=a},_) = a itembal (_,_,_,_,a) = a @@ -132,15 +130,15 @@ ," " ,fitString (Just acctwidth) (Just acctwidth) True True acct ," "- ,fitString (Just amtwidth) (Just amtwidth) True False amtfirstline+ ,amtfirstline ," "- ,fitString (Just balwidth) (Just balwidth) True False balfirstline+ ,balfirstline ] : [concat [spacer- ,fitString (Just amtwidth) (Just amtwidth) True False a+ ,a ," "- ,fitString (Just balwidth) (Just balwidth) True False b+ ,b ] | (a,b) <- zip amtrest balrest ]@@ -180,17 +178,16 @@ BalancedVirtualPosting -> (\s -> "["++s++"]", acctwidth-2) VirtualPosting -> (\s -> "("++s++")", acctwidth-2) _ -> (id,acctwidth)- showamt = showMixedAmountWithoutPrice (color_ $ reportopts_ opts)- amt = showamt $ pamount p- bal = showamt b+ amt = fst $ showMixed showAmountWithoutPrice (Just amtwidth) (Just amtwidth) (color_ . rsOpts $ reportspec_ opts) $ pamount p+ bal = fst $ showMixed showAmountWithoutPrice (Just balwidth) (Just balwidth) (color_ . rsOpts $ reportspec_ opts) b -- alternate behaviour, show null amounts as 0 instead of blank -- amt = if null amt' then "0" else amt' -- bal = if null bal' then "0" else bal' (amtlines, ballines) = (lines amt, lines bal) (amtlen, ballen) = (length amtlines, length ballines) numlines = max 1 (max amtlen ballen)- (amtfirstline:amtrest) = take numlines $ amtlines ++ repeat "" -- posting amount is top-aligned- (balfirstline:balrest) = take numlines $ replicate (numlines - ballen) "" ++ ballines -- balance amount is bottom-aligned+ (amtfirstline:amtrest) = take numlines $ amtlines ++ repeat (replicate amtwidth ' ') -- posting amount is top-aligned+ (balfirstline:balrest) = take numlines $ replicate (numlines - ballen) (replicate balwidth ' ') ++ ballines -- balance amount is bottom-aligned spacer = replicate (totalwidth - (amtwidth + 2 + balwidth)) ' ' -- tests@@ -200,8 +197,8 @@ tests "postingsReportAsText" [ test "unicode in register layout" $ do j <- readJournal' "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n"- let opts = defreportopts- (postingsReportAsText defcliopts $ postingsReport opts (queryFromOpts (fromGregorian 2008 11 26) opts) j)+ let rspec = defreportspec+ (postingsReportAsText defcliopts $ postingsReport rspec j) @?= unlines ["2009-01-01 медвежья шкура расходы:покупки 100 100"
Hledger/Cli/Commands/Registermatch.hs view
@@ -22,13 +22,10 @@ ([], Just $ argsFlag "DESC") registermatch :: CliOpts -> Journal -> IO ()-registermatch opts@CliOpts{rawopts_=rawopts,reportopts_=ropts} j = do- let args' = listofstringopt "args" rawopts- case args' of+registermatch opts@CliOpts{rawopts_=rawopts,reportspec_=rspec} j =+ case listofstringopt "args" rawopts of [desc] -> do- d <- getCurrentDay- let q = queryFromOptsOnly d ropts- (_,pris) = postingsReport ropts q j+ let (_,pris) = postingsReport rspec j ps = [p | (_,_,_,p,_) <- pris] case similarPosting ps desc of Nothing -> putStrLn "no matches found."
Hledger/Cli/Commands/Rewrite.hs view
@@ -9,7 +9,7 @@ where #if !(MIN_VERSION_base(4,11,0))-import Control.Monad.Writer+import Control.Monad.Writer hiding (Any) #endif import Data.Functor.Identity import Data.List (sortOn, foldl')@@ -36,21 +36,21 @@ -- TODO interpolating match groups in replacement -- TODO allow using this on unbalanced entries, eg to rewrite while editing -rewrite opts@CliOpts{rawopts_=rawopts,reportopts_=ropts} j@Journal{jtxns=ts} = do+rewrite opts@CliOpts{rawopts_=rawopts,reportspec_=rspec} j@Journal{jtxns=ts} = do -- rewrite matched transactions d <- getCurrentDay let modifiers = transactionModifierFromOpts opts : jtxnmodifiers j let j' = j{jtxns=either error' id $ modifyTransactions d modifiers ts} -- PARTIAL: -- run the print command, showing all transactions, or show diffs- printOrDiff rawopts opts{reportopts_=ropts{query_=""}} j j'+ printOrDiff rawopts opts{reportspec_=rspec{rsQuery=Any}} j j' -- | Build a 'TransactionModifier' from any query arguments and --add-posting flags -- provided on the command line, or throw a parse error. transactionModifierFromOpts :: CliOpts -> TransactionModifier-transactionModifierFromOpts CliOpts{rawopts_=rawopts,reportopts_=ropts} =- TransactionModifier{tmquerytxt=q, tmpostingrules=ps}+transactionModifierFromOpts CliOpts{rawopts_=rawopts} =+ TransactionModifier{tmquerytxt=q, tmpostingrules=ps} where- q = T.pack $ query_ ropts+ q = T.pack . unwords . map quoteIfNeeded $ listofstringopt "args" rawopts ps = map (parseposting . T.pack) $ listofstringopt "add-posting" rawopts parseposting t = either (error' . errorBundlePretty) id ep -- PARTIAL: where
Hledger/Cli/Commands/Roi.hs view
@@ -19,6 +19,7 @@ import Data.List import Numeric.RootFinding import Data.Decimal+import qualified Data.Text as T import System.Console.CmdArgs.Explicit as CmdArgs import Text.Tabular as Tbl@@ -47,18 +48,25 @@ Quantity -- value of investment at the beginning of day on spanBegin_ Quantity -- value of investment at the end of day on spanEnd_ [(Day,Quantity)] -- all deposits and withdrawals (but not changes of value) in the DateSpan [spanBegin_,spanEnd_)+ [(Day,Quantity)] -- all PnL changes of the value of investment in the DateSpan [spanBegin_,spanEnd_) deriving (Show) roi :: CliOpts -> Journal -> IO ()-roi CliOpts{rawopts_=rawopts, reportopts_=ropts} j = do+roi CliOpts{rawopts_=rawopts, reportspec_=rspec} j = do d <- getCurrentDay let- investmentsQuery = queryFromOpts d $ ropts{query_ = stringopt "investment" rawopts,period_=PeriodAll}- pnlQuery = queryFromOpts d $ ropts{query_ = stringopt "pnl" rawopts,period_=PeriodAll}- showCashFlow = boolopt "cashflow" rawopts- prettyTables = pretty_tables_ ropts+ ropts = rsOpts rspec+ showCashFlow = boolopt "cashflow" rawopts+ prettyTables = pretty_tables_ ropts+ makeQuery flag = do+ q <- either usageError (return . fst) . parseQuery d . T.pack $ stringopt flag rawopts+ return . simplifyQuery $ And [queryFromFlags ropts{period_=PeriodAll}, q] + investmentsQuery <- makeQuery "investment"+ pnlQuery <- makeQuery "pnl"++ let trans = dbg3 "investments" $ jtxns $ filterJournalTransactions investmentsQuery j journalSpan =@@ -96,8 +104,13 @@ , Not pnlQuery , Date (DateSpan (Just spanBegin) (Just spanEnd)) ] ) + pnl =+ calculateCashFlow trans (And [ Not investmentsQuery+ , pnlQuery+ , Date (DateSpan (Just spanBegin) (Just spanEnd)) ] )+ thisSpan = dbg3 "processing span" $- OneSpan spanBegin spanEnd valueBefore valueAfter cashFlow+ OneSpan spanBegin spanEnd valueBefore valueAfter cashFlow pnl irr <- internalRateOfReturn showCashFlow prettyTables thisSpan twr <- timeWeightedReturn showCashFlow prettyTables investmentsQuery trans thisSpan@@ -122,34 +135,47 @@ putStrLn $ Ascii.render prettyTables id id id table -timeWeightedReturn showCashFlow prettyTables investmentsQuery trans (OneSpan spanBegin spanEnd valueBefore valueAfter cashFlow) = do+timeWeightedReturn showCashFlow prettyTables investmentsQuery trans (OneSpan spanBegin spanEnd valueBefore valueAfter cashFlow pnl) = do let initialUnitPrice = 100 let initialUnits = valueBefore / initialUnitPrice- let cashflow =+ let changes =+ -- If cash flow and PnL changes happen on the same day, this+ -- will sort PnL changes to come before cash flows (on any+ -- given day), so that we will have better unit price computed+ -- first for processing cash flow. This is why pnl changes are Left+ -- and cashflows are Right+ sort+ $ (++) (map (\(date,amt) -> (date,Left (-amt))) pnl ) -- Aggregate all entries for a single day, assuming that intraday interest is negligible- map (\date_cash -> let (dates, cash) = unzip date_cash in (head dates, sum cash))+ $ map (\date_cash -> let (dates, cash) = unzip date_cash in (head dates, Right (sum cash))) $ groupBy ((==) `on` fst) $ sortOn fst $ map (\(d,a) -> (d, negate a))- $ filter ((/=0).snd) cashFlow+ $ cashFlow let units = tail $ scanl- (\(_, _, _, unitBalance) (date, amt) ->+ (\(_, _, unitPrice, unitBalance) (date, amt) -> let valueOnDate = total trans (And [investmentsQuery, Date (DateSpan Nothing (Just date))])- unitPrice =- if unitBalance == 0.0- then initialUnitPrice- else valueOnDate / unitBalance- unitsBoughtOrSold = amt / unitPrice- in (valueOnDate, unitsBoughtOrSold, unitPrice, unitBalance + unitsBoughtOrSold))- (0, 0, 0, initialUnits)- cashflow+ in+ case amt of+ Right amt ->+ -- we are buying or selling+ let unitsBoughtOrSold = amt / unitPrice+ in (valueOnDate, unitsBoughtOrSold, unitPrice, unitBalance + unitsBoughtOrSold)+ Left pnl ->+ -- PnL change+ let valueAfterDate = valueOnDate + pnl+ unitPrice' = valueAfterDate/unitBalance+ in (valueOnDate, 0, unitPrice', unitBalance))+ (0, 0, initialUnitPrice, initialUnits)+ changes let finalUnitBalance = if null units then initialUnits else let (_,_,_,u) = last units in u finalUnitPrice = if finalUnitBalance == 0 then initialUnitPrice else valueAfter / finalUnitBalance+ -- Technically, totalTWR should be (100*(finalUnitPrice - initialUnitPrice) / initialUnitPrice), but initalUnitPrice is 100, so 100/100 == 1 totalTWR = roundTo 2 $ (finalUnitPrice - initialUnitPrice) years = fromIntegral (diffDays spanEnd spanBegin) / 365 :: Double annualizedTWR = 100*((1+(realToFrac totalTWR/100))**(1/years)-1) :: Double@@ -157,11 +183,14 @@ let s d = show $ roundTo 2 d when showCashFlow $ do printf "\nTWR cash flow for %s - %s\n" (showDate spanBegin) (showDate (addDays (-1) spanEnd))- let (dates', amounts') = unzip cashflow+ let (dates', amounts) = unzip changes+ cashflows' = map (either (\_ -> 0) id) amounts+ pnls' = map (either id (\_ -> 0)) amounts (valuesOnDate',unitsBoughtOrSold', unitPrices', unitBalances') = unzip4 units add x lst = if valueBefore/=0 then x:lst else lst dates = add spanBegin dates'- amounts = add valueBefore amounts'+ cashflows = add valueBefore cashflows'+ pnls = add 0 pnls' unitsBoughtOrSold = add initialUnits unitsBoughtOrSold' unitPrices = add initialUnitPrice unitPrices' unitBalances = add initialUnits unitBalances'@@ -171,22 +200,23 @@ (Table (Tbl.Group NoLine (map (Header . showDate) dates)) (Tbl.Group DoubleLine [ Tbl.Group SingleLine [Header "Portfolio value", Header "Unit balance"]- , Tbl.Group SingleLine [Header "Cash", Header "Unit price", Header "Units"]+ , Tbl.Group SingleLine [Header "Pnl", Header "Cashflow", Header "Unit price", Header "Units"] , Tbl.Group SingleLine [Header "New Unit Balance"]])- [ [value, oldBalance, amt, prc, udelta, balance]+ [ [value, oldBalance, pnl, cashflow, prc, udelta, balance] | value <- map s valuesOnDate | oldBalance <- map s (0:unitBalances) | balance <- map s unitBalances- | amt <- map s amounts+ | pnl <- map s pnls+ | cashflow <- map s cashflows | prc <- map s unitPrices | udelta <- map s unitsBoughtOrSold ]) - printf "Final unit price: %s/%s=%s U.\nTotal TWR: %s%%.\nPeriod: %.2f years.\nAnnualized TWR: %.2f%%\n\n" (s valueAfter) (s finalUnitBalance) (s finalUnitPrice) (s totalTWR) years annualizedTWR+ printf "Final unit price: %s/%s units = %s\nTotal TWR: %s%%.\nPeriod: %.2f years.\nAnnualized TWR: %.2f%%\n\n" (s valueAfter) (s finalUnitBalance) (s finalUnitPrice) (s totalTWR) years annualizedTWR return annualizedTWR -internalRateOfReturn showCashFlow prettyTables (OneSpan spanBegin spanEnd valueBefore valueAfter cashFlow) = do+internalRateOfReturn showCashFlow prettyTables (OneSpan spanBegin spanEnd valueBefore valueAfter cashFlow _pnl) = do let prefix = (spanBegin, negate valueBefore) postfix = (spanEnd, valueAfter)@@ -209,8 +239,10 @@ (0.000000000001,10000) (interestSum spanEnd totalCF) of Root rate -> return ((rate-1)*100)- NotBracketed -> error' "Error: No solution -- not bracketed." -- PARTIAL:- SearchFailed -> error' "Error: Failed to find solution."+ NotBracketed -> error' $ "Error (NotBracketed): No solution for Internal Rate of Return (IRR).\n"+ ++ " Possible causes: IRR is huge (>1000000%), balance of investment becomes negative at some point in time."+ SearchFailed -> error' $ "Error (SearchFailed): Failed to find solution for Internal Rate of Return (IRR).\n"+ ++ " Either search does not converge to a solution, or converges too slowly." type CashFlow = [(Day, Quantity)] @@ -220,16 +252,15 @@ calculateCashFlow :: [Transaction] -> Query -> CashFlow-calculateCashFlow trans query = map go trans+calculateCashFlow trans query = filter ((/=0).snd) $ map go trans where go t = (transactionDate2 t, total [t] query) total :: [Transaction] -> Query -> Quantity-total trans query = unMix $ sumPostings $ filter (matchesPosting query) $ concatMap realPostings trans+total trans query = unMix $ sumPostings $ filter (matchesPosting query) $ concatMap realPostings trans unMix :: MixedAmount -> Quantity unMix a = case (normaliseMixedAmount $ mixedAmountCost a) of (Mixed [a]) -> aquantity a _ -> error' "MixedAmount failed to normalize" -- PARTIAL:-
Hledger/Cli/Commands/Roi.txt view
@@ -17,7 +17,234 @@ name) to select your investments with --inv, and another query to identify your profit and loss transactions with --pnl. -It will compute and display the internalized rate of return (IRR) and-time-weighted rate of return (TWR) for your investments for the time-period requested. Both rates of return are annualized before display,-regardless of the length of reporting interval.+This command will compute and display the internalized rate of return+(IRR) and time-weighted rate of return (TWR) for your investments for+the time period requested. Both rates of return are annualized before+display, regardless of the length of reporting interval.++Note, in some cases this report can fail, for these reasons:++- Error (NotBracketed): No solution for Internal Rate of Return (IRR).+ Possible causes: IRR is huge (>1000000%), balance of investment+ becomes negative at some point in time.+- Error (SearchFailed): Failed to find solution for Internal Rate of+ Return (IRR). Either search does not converge to a solution, or+ converges too slowly.++Examples:++- Using roi to report unrealised gains:+ https://github.com/simonmichael/hledger/blob/master/examples/roi-unrealised.ledger++More background:++"ROI" stands for "return on investment". Traditionally this was computed+as a difference between current value of investment and its initial+value, expressed in percentage of the initial value.++However, this approach is only practical in simple cases, where+investments receives no in-flows or out-flows of money, and where 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.++Internal rate of return, or "IRR" (also called "money-weighted rate of+return") takes into account effects of in-flows and out-flows. Naively,+if you are withdrawing from your investment, your future gains would be+smaller (in absolute numbers), and will be a smaller percentage of your+initial investment, and if you are adding to your investment, you will+receive bigger absolute gains (but probably at the same rate of return).+IRR is a way to compute rate of return for each period between in-flow+or out-flow of money, and then combine them in a way that gives you an+annual rate of return that investment is expected to generate.++As mentioned before, in-flows and out-flows would be any cash that you+personally put in or withdraw, and for the "roi" command, these are+transactions that involve account(s) matching --inv argument and NOT+involve account(s) matching --pnl argument.++Presumably, you will also record changes in the value of your+investment, and balance them against "profit and loss" (or "unrealized+gains") account. Note that in order for IRR to compute the precise+effect of your in-flows and out-flows on the rate of return, you will+need to record the value of your investement on or close to the days+when in- or out-flows occur.++Implementation of IRR in hledger should match the XIRR formula in Excel.++Second way to compute rate of return that roi command implements is+called "time-weighted rate of return" or "TWR". Like IRR, it will also+break the history of your investment into periods between in-flows and+out-flows to compute rate of return per each period and then a compound+rate of return. However, internal workings of TWR are quite different.++In technical terms, IRR uses the same approach as computation of net+present value, and tries to find a discount rate that makes net present+value of all the cash flows of your investment to add up to zero. This+could be hard to wrap your head around, especially if you haven't done+discounted cash flow analysis before.++TWR represents your investment as an imaginary "unit fund" where+in-flows/ out-flows lead to buying or selling "units" of your investment+and changes in its value change the value of "investment unit". Change+in "unit price" over the reporting period gives you rate of return of+your investment.++References: * Explanation of rate of return * Explanation of IRR *+Explanation of TWR * Examples of computing IRR and TWR and discussion of+the limitations of both metrics++More examples:++Lets say that we found an investment in Snake Oil that is proising to+give us 10% annually:++2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-12-24 Recording the growth of Snake Oil+ investment:snake oil = $110+ equity:unrealized gains++For now, basic computation of the rate of return, as well as IRR and+TWR, gives us the expected 10%:++$ hledger roi -Y --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+-----++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 110 | 10 || 10.00% | 10.00% |++---++------------+------------++---------------+----------+-------------+-----++--------+--------+++However, lets say that shorty after investing in the Snake Oil we+started to have second thoughs, so we prompty withdrew $90, leaving only+$10 in. Before Christmas, though, we started to get the "fear of mission+out", so we put the $90 back in. So for most of the year, our investment+was just $10 dollars, and it gave us just $1 in growth:++2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil+ +2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil = $101+ equity:unrealized gains++Now IRR and TWR are drastically different:++$ hledger roi -Y --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+-----++-------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++=======+=======++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101 | 1 || 9.32% | 1.00% |++---++------------+------------++---------------+----------+-------------+-----++-------+-------+++Here, IRR tells us that we made close to 10% on the $10 dollars that we+had in the account most of the time. And TWR is ... just 1%? Why?++Based on the transactions in our journal, TWR "think" that we are buying+back $90 worst of Snake Oil at the same price that it had at the+beginning of they year, and then after that our $100 investment gets $1+increase in value, or 1% of $100. Let's take a closer look at what is+happening here by asking for quarterly reports instead of annual:++$ hledger roi -Q --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+-----++--------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+=======++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10 | 0 || 0.00% | 0.00% |+| 2 || 2019-04-01 | 2019-06-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 3 || 2019-07-01 | 2019-09-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 4 || 2019-10-01 | 2019-12-31 || 10 | 90 | 101 | 1 || 37.80% | 4.03% |++---++------------+------------++---------------+----------+-------------+-----++--------+-------+++Now both IRR and TWR are thrown off by the fact that all of the growth+for our investment happens in Q4 2019. This happes because IRR+computation is still yielding 9.32% and TWR is still 1%, but this time+these are rates for three month period instead of twelve, so in order to+get an annual rate they should be multiplied by four!++Let's try to keep a better record of how Snake Oil grew in value:++2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil++2019-02-28 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-06-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-09-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++Would our quartery report look better now? Almost:++$ hledger roi -Q --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 1.00% |++---++------------+------------++---------------+----------+-------------+------++--------+--------+++Something is still wrong with TWR computation for Q4, and if you have+been paying attention you know what it is already: big $90 buy-back is+recorded prior to the only transaction that captures the change of value+of Snake Oil that happened in this time period. Lets combine+transactions from 30th and 31st of Dec into one:++2019-12-30 Fear of missing out and growth of Snake Oil+ assets:cash -$90+ investment:snake oil+ equity:unrealized gains -$0.25++Now growth of investment properly affects its price at the time of+buy-back:++$ hledger roi -Q --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 9.57% |++---++------------+------------++---------------+----------+-------------+------++--------+--------+++And for annual report, TWR now reports the exact profitability of our+investment:++$ hledger roi -Y --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+------++-------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++=======+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101.00 | 1.00 || 9.32% | 10.00% |++---++------------+------------++---------------+----------+-------------+------++-------+--------+
Hledger/Cli/Commands/Stats.hs view
@@ -42,12 +42,12 @@ -- like Register.summarisePostings -- | Print various statistics for the journal. stats :: CliOpts -> Journal -> IO ()-stats opts@CliOpts{reportopts_=reportopts_} j = do+stats opts@CliOpts{reportspec_=rspec} j = do d <- getCurrentDay- let q = queryFromOpts d reportopts_+ let q = rsQuery rspec l = ledgerFromJournal q j reportspan = (ledgerDateSpan l) `spanDefaultsFrom` (queryDateSpan False q)- intervalspans = splitSpan (interval_ reportopts_) reportspan+ intervalspans = splitSpan (interval_ $ rsOpts rspec) reportspan showstats = showLedgerStats l d s = intercalate "\n" $ map showstats intervalspans writeOutput opts s
Hledger/Cli/Commands/Tags.hs view
@@ -26,18 +26,20 @@ ([], Just $ argsFlag "[TAGREGEX [QUERY...]]") tags :: CliOpts -> Journal -> IO ()-tags CliOpts{rawopts_=rawopts,reportopts_=ropts} j = do+tags CliOpts{rawopts_=rawopts,reportspec_=rspec} j = do d <- getCurrentDay- let- args = listofstringopt "args" rawopts+ let args = listofstringopt "args" rawopts mtagpat <- mapM (either Fail.fail pure . toRegexCI) $ headMay args let- queryargs = drop 1 args- values = boolopt "values" rawopts- parsed = boolopt "parsed" rawopts- empty = empty_ ropts- q = queryFromOpts d $ ropts{query_ = unwords $ map quoteIfNeeded queryargs}- txns = filter (q `matchesTransaction`) $ jtxns $ journalSelectingAmountFromOpts ropts j+ querystring = map T.pack $ drop 1 args+ values = boolopt "values" rawopts+ parsed = boolopt "parsed" rawopts+ empty = empty_ $ rsOpts rspec++ argsquery <- either usageError (return . fst) $ parseQueryList d querystring+ let+ q = simplifyQuery $ And [queryFromFlags $ rsOpts rspec, argsquery]+ txns = filter (q `matchesTransaction`) $ jtxns $ journalSelectingAmountFromOpts (rsOpts rspec) j tagsorvalues = (if parsed then id else nubSort) [ r
Hledger/Cli/CompoundBalanceCommand.hs view
@@ -41,11 +41,11 @@ -- it should be added to or subtracted from the grand total. -- data CompoundBalanceCommandSpec = CompoundBalanceCommandSpec {- cbcdoc :: CommandDoc, -- ^ the command's name(s) and documentation- cbctitle :: String, -- ^ overall report title- cbcqueries :: [CBCSubreportSpec], -- ^ subreport details- cbctype :: BalanceType -- ^ the "balance" type (change, cumulative, historical)- -- this report shows (overrides command line flags)+ cbcdoc :: CommandDoc, -- ^ the command's name(s) and documentation+ cbctitle :: String, -- ^ overall report title+ cbcqueries :: [CBCSubreportSpec DisplayName], -- ^ subreport details+ cbctype :: BalanceType -- ^ the "balance" type (change, cumulative, historical)+ -- this report shows (overrides command line flags) } -- | Generate a cmdargs option-parsing mode from a compound balance command@@ -70,7 +70,7 @@ ,flagNone ["average","A"] (setboolopt "average") "show a row average column (in multicolumn reports)" ,flagNone ["row-total","T"] (setboolopt "row-total") "show a row total column (in multicolumn reports)" ,flagNone ["no-total","N"] (setboolopt "no-total") "omit the final total row"- ,flagNone ["no-elide"] (setboolopt "no-elide") "don't squash boring parent accounts (in tree mode)"+ ,flagNone ["no-elide"] (setboolopt "no-elide") "don't squash boring parent accounts (in tree mode); don't show only 2 commodities per amount" ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format (in simple reports)" ,flagNone ["pretty-tables"] (setboolopt "pretty-tables") "use unicode when displaying tables" ,flagNone ["sort-amount","S"] (setboolopt "sort-amount") "sort by amount instead of account code/name"@@ -88,9 +88,9 @@ -- | Generate a runnable command from a compound balance command specification. compoundBalanceCommand :: CompoundBalanceCommandSpec -> (CliOpts -> Journal -> IO ())-compoundBalanceCommand CompoundBalanceCommandSpec{..} opts@CliOpts{reportopts_=ropts@ReportOpts{..}, rawopts_=rawopts} j = do- today <- getCurrentDay+compoundBalanceCommand CompoundBalanceCommandSpec{..} opts@CliOpts{reportspec_=rspec, rawopts_=rawopts} j = do let+ ropts@ReportOpts{..} = rsOpts rspec -- use the default balance type for this report, unless the user overrides mBalanceTypeOverride = choiceopt parse rawopts where@@ -121,29 +121,36 @@ _ -> showDateSpan requestedspan where enddates = map (addDays (-1)) . mapMaybe spanEnd $ cbrDates cbr -- these spans will always have a definite end date- requestedspan = queryDateSpan date2_ (queryFromOpts today ropts')+ requestedspan = queryDateSpan date2_ (rsQuery rspec) `spanDefaultsFrom` journalDateSpan date2_ j -- when user overrides, add an indication to the report title- mtitleclarification = flip fmap mBalanceTypeOverride $ \t ->- case t of- PeriodChange -> "(Balance Changes)"- CumulativeChange -> "(Cumulative Ending Balances)"- HistoricalBalance -> "(Historical Ending Balances)"+ mtitleclarification = flip fmap mBalanceTypeOverride $ \case+ PeriodChange | changingValuation -> "(Period-End Value Changes)"+ PeriodChange -> "(Balance Changes)"+ CumulativeChange -> "(Cumulative Ending Balances)"+ HistoricalBalance -> "(Historical Ending Balances)" valuationdesc = case value_ of Just (AtCost _mc) -> ", valued at cost" Just (AtThen _mc) -> error' unsupportedValueThenError -- TODO+ Just (AtEnd _mc) | changingValuation -> "" Just (AtEnd _mc) -> ", valued at period ends" Just (AtNow _mc) -> ", current value"- Just (AtDefault _mc) | multiperiod -> ", valued at period ends"+ Just (AtDefault _mc) | changingValuation -> ""+ Just (AtDefault _mc) | multiperiod -> ", valued at period ends" Just (AtDefault _mc) -> ", current value" Just (AtDate today _mc) -> ", valued at "++showDate today Nothing -> ""- where multiperiod = interval_ /= NoInterval + multiperiod = interval_ /= NoInterval+ changingValuation+ | PeriodChange <- balancetype_, Just (AtEnd _mc) <- value_ = multiperiod+ | PeriodChange <- balancetype_, Just (AtDefault _mc) <- value_ = multiperiod+ | otherwise = False+ -- make a CompoundBalanceReport.- cbr' = compoundBalanceReport today ropts' j cbcqueries+ cbr' = compoundBalanceReport rspec{rsOpts=ropts'} j cbcqueries cbr = cbr'{cbrTitle=title} -- render appropriately@@ -186,7 +193,7 @@ Total || 1 1 1 -}-compoundBalanceReportAsText :: ReportOpts -> CompoundBalanceReport -> String+compoundBalanceReportAsText :: ReportOpts -> CompoundPeriodicReport DisplayName MixedAmount -> String compoundBalanceReportAsText ropts (CompoundPeriodicReport title _colspans subreports (PeriodicReportRow _ coltotals grandtotal grandavg)) = title ++ "\n\n" ++@@ -225,7 +232,7 @@ -- Subreports' CSV is concatenated, with the headings rows replaced by a -- subreport title row, and an overall title row, one headings row, and an -- optional overall totals row is added.-compoundBalanceReportAsCsv :: ReportOpts -> CompoundBalanceReport -> CSV+compoundBalanceReportAsCsv :: ReportOpts -> CompoundPeriodicReport DisplayName MixedAmount -> CSV compoundBalanceReportAsCsv ropts (CompoundPeriodicReport title colspans subreports (PeriodicReportRow _ coltotals grandtotal grandavg)) = addtotals $ padRow title :@@ -262,7 +269,7 @@ ]) -- | Render a compound balance report as HTML.-compoundBalanceReportAsHtml :: ReportOpts -> CompoundBalanceReport -> Html ()+compoundBalanceReportAsHtml :: ReportOpts -> CompoundPeriodicReport DisplayName MixedAmount -> Html () compoundBalanceReportAsHtml ropts cbr = let CompoundPeriodicReport title colspans subreports (PeriodicReportRow _ coltotals grandtotal grandavg) = cbr
Hledger/Cli/Main.hs view
@@ -19,7 +19,7 @@ or ghci: > $ ghci hledger-> > j <- readJournalFile def "examples/sample.journal"+> > Right j <- readJournalFile definputopts "examples/sample.journal" > > register [] ["income","expenses"] j > 2008/01/01 income income:salary $-1 $-1 > 2008/06/01 gift income:gifts $-1 $-2@@ -30,9 +30,9 @@ > $2 expenses > $-2 income > $1 liabilities-> > l <- myLedger+> > j <- defaultJournal -See "Hledger.Data.Ledger" for more examples.+etc. -} @@ -151,12 +151,11 @@ dbgIO "isInternalCommand" isInternalCommand dbgIO "isExternalCommand" isExternalCommand dbgIO "isBadCommand" isBadCommand- d <- getCurrentDay- dbgIO "period from opts" (period_ $ reportopts_ opts)- dbgIO "interval from opts" (interval_ $ reportopts_ opts)- dbgIO "query from opts & args" (queryFromOpts d $ reportopts_ opts)+ dbgIO "period from opts" (period_ . rsOpts $ reportspec_ opts)+ dbgIO "interval from opts" (interval_ . rsOpts $ reportspec_ opts)+ dbgIO "query from opts & args" (rsQuery $ reportspec_ opts) let- journallesserror = error "journal-less command tried to use the journal"+ journallesserror = error $ cmd++" tried to read the journal but is not supposed to" runHledgerCommand -- high priority flags and situations. -h, then --help, then --info are highest priority. | hasHelpFlag argsbeforecmd = dbgIO "" "-h before command, showing general usage" >> printUsage
Hledger/Cli/Utils.hs view
@@ -18,33 +18,31 @@ journalReload, journalReloadIfChanged, journalFileIsNewer,- journalSpecifiedFileIsNewer,- fileModificationTime, openBrowserOn, writeFileWithBackup, writeFileWithBackupIfChanged, readFileStrictly, pivotByOpts, anonymiseByOpts,+ utcTimeToClockTime, tests_Cli_Utils, ) where import Control.Exception as C-import Control.Monad import Data.List import Data.Maybe import qualified Data.Text as T import qualified Data.Text.IO as T-import Data.Time (Day, addDays)+import Data.Time (UTCTime, Day, addDays) import Safe (readMay) import System.Console.CmdArgs-import System.Directory (getModificationTime, getDirectoryContents, copyFile)+import System.Directory (getModificationTime, getDirectoryContents, copyFile, doesFileExist) import System.Exit import System.FilePath ((</>), splitFileName, takeDirectory) import System.Info (os) import System.Process (readProcessWithExitCode)-import System.Time (ClockTime, getClockTime, diffClockTimes, TimeDiff(TimeDiff))+import System.Time (diffClockTimes, TimeDiff(TimeDiff)) import Text.Printf import Text.Regex.TDFA ((=~)) @@ -57,10 +55,11 @@ import Hledger.Read import Hledger.Reports import Hledger.Utils+import Control.Monad (when) -- | Standard error message for a bad output format specified with -O/-o. unsupportedOutputFormatError :: String -> String-unsupportedOutputFormatError fmt = "Sorry, output format \""++fmt++"\" is unrecognised or not yet implemented for this report or report mode."+unsupportedOutputFormatError fmt = "Sorry, output format \""++fmt++"\" is unrecognised or not yet supported for this kind of report." -- | Parse the user's specified journal file(s) as a Journal, maybe apply some -- transformations according to options, and run a hledger command with it.@@ -71,9 +70,9 @@ -- it's stdin, or it doesn't exist and we are adding. We read it strictly -- to let the add command work. journalpaths <- journalFilePathFromOpts opts- readJournalFiles (inputopts_ opts) journalpaths- >>= mapM (journalTransform opts)- >>= either error' cmd -- PARTIAL:+ files <- readJournalFiles (inputopts_ opts) journalpaths+ let transformed = journalTransform opts <$> files+ either error' cmd transformed -- PARTIAL: -- | Apply some extra post-parse transformations to the journal, if -- specified by options. These happen after journal validation, but@@ -83,13 +82,13 @@ -- - pivoting account names (--pivot) -- - anonymising (--anonymise). ---journalTransform :: CliOpts -> Journal -> IO Journal-journalTransform opts@CliOpts{reportopts_=_ropts} =- journalAddForecast opts--- - converting amounts to market value (--value)- -- >=> journalApplyValue ropts- >=> return . pivotByOpts opts- >=> return . anonymiseByOpts opts+journalTransform :: CliOpts -> Journal -> Journal+journalTransform opts =+ anonymiseByOpts opts+ -- - converting amounts to market value (--value)+ -- . journalApplyValue ropts+ . pivotByOpts opts+ . journalAddForecast opts -- | Apply the pivot transformation on a journal, if option is present. pivotByOpts :: CliOpts -> Journal -> Journal@@ -115,38 +114,39 @@ -- The start & end date for generated periodic transactions are determined in -- a somewhat complicated way; see the hledger manual -> Periodic transactions. ---journalAddForecast :: CliOpts -> Journal -> IO Journal-journalAddForecast CliOpts{inputopts_=iopts, reportopts_=ropts} j = do- today <- getCurrentDay+journalAddForecast :: CliOpts -> Journal -> Journal+journalAddForecast CliOpts{inputopts_=iopts, reportspec_=rspec} j =+ case forecast_ ropts of+ Nothing -> j+ Just _ -> either (error') id . journalApplyCommodityStyles $ -- PARTIAL:+ journalBalanceTransactions' iopts j{ jtxns = concat [jtxns j, forecasttxns'] }+ where+ today = rsToday rspec+ ropts = rsOpts rspec - -- "They can start no earlier than: the day following the latest normal transaction in the journal (or today if there are none)."- let mjournalend = dbg2 "journalEndDate" $ journalEndDate False j -- ignore secondary dates- forecastbeginDefault = dbg2 "forecastbeginDefault" $ fromMaybe today mjournalend+ -- "They can start no earlier than: the day following the latest normal transaction in the journal (or today if there are none)."+ mjournalend = dbg2 "journalEndDate" $ journalEndDate False j -- ignore secondary dates+ forecastbeginDefault = dbg2 "forecastbeginDefault" $ fromMaybe today mjournalend - -- "They end on or before the specified report end date, or 180 days from today if unspecified."- mspecifiedend <- snd . dbg2 "specifieddates" <$> specifiedStartEndDates ropts- let forecastendDefault = dbg2 "forecastendDefault" $ fromMaybe (addDays 180 today) mspecifiedend- - let forecastspan = dbg2 "forecastspan" $- spanDefaultsFrom- (fromMaybe nulldatespan $ dbg2 "forecastspan flag" $ forecast_ ropts)- (DateSpan (Just forecastbeginDefault) (Just forecastendDefault))- - forecasttxns =- [ txnTieKnot t | pt <- jperiodictxns j- , t <- runPeriodicTransaction pt forecastspan- , spanContainsDate forecastspan (tdate t)- ]- -- With --auto enabled, transaction modifiers are also applied to forecast txns- forecasttxns' =- (if auto_ iopts then either error' id . modifyTransactions today (jtxnmodifiers j) else id) -- PARTIAL:- forecasttxns+ -- "They end on or before the specified report end date, or 180 days from today if unspecified."+ mspecifiedend = dbg2 "specifieddates" $ reportPeriodLastDay rspec+ forecastendDefault = dbg2 "forecastendDefault" $ fromMaybe (addDays 180 today) mspecifiedend - return $- case forecast_ ropts of- Just _ -> journalBalanceTransactions' iopts j{ jtxns = concat [jtxns j, forecasttxns'] }- Nothing -> j- where+ forecastspan = dbg2 "forecastspan" $+ spanDefaultsFrom+ (fromMaybe nulldatespan $ dbg2 "forecastspan flag" $ forecast_ ropts)+ (DateSpan (Just forecastbeginDefault) (Just forecastendDefault))++ forecasttxns =+ [ txnTieKnot t | pt <- jperiodictxns j+ , t <- runPeriodicTransaction pt forecastspan+ , spanContainsDate forecastspan (tdate t)+ ]+ -- With --auto enabled, transaction modifiers are also applied to forecast txns+ forecasttxns' =+ (if auto_ iopts then either error' id . modifyTransactions today (jtxnmodifiers j) else id) -- PARTIAL:+ forecasttxns+ journalBalanceTransactions' iopts j = let assrt = not . ignore_assertions_ $ iopts in@@ -163,15 +163,6 @@ -- readJournal :: CliOpts -> String -> IO Journal -- readJournal opts s = readJournal def Nothing s >>= either error' return --- | Re-read the journal file(s) specified by options, applying any--- transformations specified by options. Or return an error string.--- Reads the full journal, without filtering.-journalReload :: CliOpts -> IO (Either String Journal)-journalReload opts = do- journalpaths <- journalFilePathFromOpts opts- readJournalFiles (inputopts_ opts) journalpaths- >>= mapM (journalTransform opts)- -- | Re-read the option-specified journal file(s), but only if any of -- them has changed since last read. (If the file is standard input, -- this will either do nothing or give an error, not tested yet).@@ -180,43 +171,57 @@ -- the full journal, without filtering. journalReloadIfChanged :: CliOpts -> Day -> Journal -> IO (Either String Journal, Bool) journalReloadIfChanged opts _d j = do- let maybeChangedFilename f = do newer <- journalSpecifiedFileIsNewer j f+ let maybeChangedFilename f = do newer <- journalFileIsNewer j f return $ if newer then Just f else Nothing changedfiles <- catMaybes `fmap` mapM maybeChangedFilename (journalFilePaths j) if not $ null changedfiles then do- whenLoud $ printf "%s has changed, reloading\n" (head changedfiles)+ -- XXX not sure why we use cmdarg's verbosity here, but keep it for now+ verbose <- isLoud+ when (verbose || debugLevel >= 6) $ printf "%s has changed, reloading\n" (head changedfiles) ej <- journalReload opts return (ej, True) else return (Right j, False) --- | Has the journal's main data file changed since the journal was last--- read ?-journalFileIsNewer :: Journal -> IO Bool-journalFileIsNewer j@Journal{jlastreadtime=tread} = do- tmod <- fileModificationTime $ journalFilePath j- return $ diffClockTimes tmod tread > (TimeDiff 0 0 0 0 0 0 0)+-- | Re-read the journal file(s) specified by options, applying any+-- transformations specified by options. Or return an error string.+-- Reads the full journal, without filtering.+journalReload :: CliOpts -> IO (Either String Journal)+journalReload opts = do+ journalpaths <- dbg6 "reloading files" <$> journalFilePathFromOpts opts+ files <- readJournalFiles (inputopts_ opts) journalpaths+ return $ journalTransform opts <$> files --- | Has the specified file (presumably one of journal's data files)--- changed since journal was last read ?-journalSpecifiedFileIsNewer :: Journal -> FilePath -> IO Bool-journalSpecifiedFileIsNewer Journal{jlastreadtime=tread} f = do- tmod <- fileModificationTime f- return $ diffClockTimes tmod tread > (TimeDiff 0 0 0 0 0 0 0)+-- | Has the specified file changed since the journal was last read ?+-- Typically this is one of the journal's journalFilePaths. These are+-- not always real files, so the file's existence is tested first;+-- for non-files the answer is always no.+journalFileIsNewer :: Journal -> FilePath -> IO Bool+journalFileIsNewer Journal{jlastreadtime=tread} f = do+ mtmod <- maybeFileModificationTime f+ return $+ case mtmod of+ Just tmod -> diffClockTimes tmod tread > (TimeDiff 0 0 0 0 0 0 0)+ Nothing -> False --- | Get the last modified time of the specified file, or if it does not--- exist or there is some other error, the current time.-fileModificationTime :: FilePath -> IO ClockTime-fileModificationTime f- | null f = getClockTime- | otherwise = (do- utc <- getModificationTime f- let nom = utcTimeToPOSIXSeconds utc- let clo = TOD (read $ takeWhile (`elem` ("0123456789"::String)) $ show nom) 0 -- XXX read- return clo- )- `C.catch` \(_::C.IOException) -> getClockTime+-- | Get the last modified time of the specified file, if it exists.+maybeFileModificationTime :: FilePath -> IO (Maybe ClockTime)+maybeFileModificationTime f = do+ exists <- doesFileExist f+ if exists+ then do+ utc <- getModificationTime f+ return $ Just $ utcTimeToClockTime utc+ else+ return Nothing++utcTimeToClockTime :: UTCTime -> ClockTime+utcTimeToClockTime utc = TOD posixsecs picosecs+ where+ (posixsecs, frac) = properFraction $ utcTimeToPOSIXSeconds utc+ picosecs = round $ frac * 1e12+ -- | Attempt to open a web browser on the given url, all platforms. openBrowserOn :: String -> IO ExitCode openBrowserOn u = trybrowsers browsers u
embeddedfiles/hledger-ui.1 view
@@ -1,5 +1,5 @@ -.TH "hledger-ui" "1" "September 2020" "hledger-ui 1.18.99" "hledger User Manuals"+.TH "hledger-ui" "1" "November 2020" "hledger-ui 1.20" "hledger User Manuals" @@ -88,6 +88,9 @@ \f[B]\f[CB]-I --ignore-assertions\f[B]\f[R] disable balance assertion checks (note: does not disable balance assignments)+.TP+\f[B]\f[CB]-s --strict\f[B]\f[R]+do extra error checking (check that all posted accounts are declared) .PP hledger reporting options: .TP
embeddedfiles/hledger-ui.info view
@@ -3,8 +3,8 @@ File: hledger-ui.info, Node: Top, Next: OPTIONS, Up: (dir) -hledger-ui(1) hledger-ui 1.18.99-********************************+hledger-ui(1) hledger-ui 1.20+***************************** hledger-ui - terminal interface for the hledger accounting tool @@ -99,7 +99,11 @@ disable balance assertion checks (note: does not disable balance assignments)+'-s --strict' + do extra error checking (check that all posted accounts are+ declared)+ hledger reporting options: '-b --begin=DATE'@@ -515,26 +519,26 @@ Tag Table: Node: Top71-Node: OPTIONS1476-Ref: #options1573-Node: keys5545-Ref: #keys5640-Node: screens9972-Ref: #screens10077-Node: accounts screen10167-Ref: #accounts-screen10295-Node: Register screen12510-Ref: #register-screen12665-Node: Transaction screen14662-Ref: #transaction-screen14820-Node: Error screen15690-Ref: #error-screen15812-Node: ENVIRONMENT16056-Ref: #environment16170-Node: FILES16977-Ref: #files17076-Node: BUGS17289-Ref: #bugs17366+Node: OPTIONS1470+Ref: #options1567+Node: keys5634+Ref: #keys5729+Node: screens10061+Ref: #screens10166+Node: accounts screen10256+Ref: #accounts-screen10384+Node: Register screen12599+Ref: #register-screen12754+Node: Transaction screen14751+Ref: #transaction-screen14909+Node: Error screen15779+Ref: #error-screen15901+Node: ENVIRONMENT16145+Ref: #environment16259+Node: FILES17066+Ref: #files17165+Node: BUGS17378+Ref: #bugs17455 End Tag Table
embeddedfiles/hledger-ui.txt view
@@ -84,6 +84,10 @@ disable balance assertion checks (note: does not disable balance assignments) + -s --strict+ do extra error checking (check that all posted accounts are de-+ clared)+ hledger reporting options: -b --begin=DATE@@ -108,7 +112,7 @@ multiperiod/multicolumn report by year -p --period=PERIODEXP- set start date, end date, and/or reporting interval all at once+ set start date, end date, and/or reporting interval all at once using period expressions syntax --date2@@ -131,21 +135,21 @@ hide/aggregate accounts or postings more than NUM levels deep -E --empty- show items with zero amount, normally hidden (and vice-versa in+ show items with zero amount, normally hidden (and vice-versa in hledger-ui/hledger-web) -B --cost convert amounts to their cost/selling amount at transaction time -V --market- convert amounts to their market value in default valuation com-+ convert amounts to their market value in default valuation com- modities -X --exchange=COMM convert amounts to their market value in commodity COMM --value- convert amounts to cost or market value, more flexibly than+ convert amounts to cost or market value, more flexibly than -B/-V/-X --infer-value@@ -154,15 +158,15 @@ --auto apply automated posting rules to modify transactions. --forecast- generate future transactions from periodic transaction rules,- for the next 6 months or till report end date. In hledger-ui,+ generate future transactions from periodic transaction rules,+ for the next 6 months or till report end date. In hledger-ui, also make ordinary future transactions visible. --color=WHEN (or --colour=WHEN)- Should color-supporting commands use ANSI color codes in text- output. 'auto' (default): whenever stdout seems to be a color-- supporting terminal. 'always' or 'yes': always, useful eg when- piping output into 'less -R'. 'never' or 'no': never. A+ Should color-supporting commands use ANSI color codes in text+ output. 'auto' (default): whenever stdout seems to be a color-+ supporting terminal. 'always' or 'yes': always, useful eg when+ piping output into 'less -R'. 'never' or 'no': never. A NO_COLOR environment variable overrides this. When a reporting option appears more than once in the command line, the@@ -182,91 +186,91 @@ show debug output (levels 1-9, default: 1) a @file argument will be expanded to the contents of file, which should- contain one command line option/argument per line. (to prevent this,+ contain one command line option/argument per line. (to prevent this, insert a -- argument before.) keys- ? shows a help dialog listing all keys. (some of these also appear in+ ? shows a help dialog listing all keys. (some of these also appear in the quick help at the bottom of each screen.) press ? again (or escape, or left, or q) to close it. the following keys work on most screens: the cursor keys navigate: right (or enter) goes deeper, left returns to- the previous screen, up/down/page up/page down/home/end move up and+ the previous screen, up/down/page up/page down/home/end move up and down through lists. Emacs-style (ctrl-p/ctrl-n/ctrl-f/ctrl-b) movement- keys are also supported (but not vi-style keys, since hledger-1.19,- sorry!). A tip: movement speed is limited by your keyboard repeat- rate, to move faster you may want to adjust it. (If you're on a mac,+ keys are also supported (but not vi-style keys, since hledger-1.19,+ sorry!). A tip: movement speed is limited by your keyboard repeat+ rate, to move faster you may want to adjust it. (If you're on a mac, the karabiner app is one way to do that.) - with shift pressed, the cursor keys adjust the report period, limiting- the transactions to be shown (by default, all are shown). shift-- down/up steps downward and upward through these standard report period- durations: year, quarter, month, week, day. then, shift-left/right- moves to the previous/next period. T sets the report period to today.- with the --watch option, when viewing a "current" period (the current+ with shift pressed, the cursor keys adjust the report period, limiting+ the transactions to be shown (by default, all are shown). shift-+ down/up steps downward and upward through these standard report period+ durations: year, quarter, month, week, day. then, shift-left/right+ moves to the previous/next period. T sets the report period to today.+ with the --watch option, when viewing a "current" period (the current day, week, month, quarter, or year), the period will move automatically to track the current date. to set a non-standard period, you can use / and a date: query. - / lets you set a general filter query limiting the data shown, using- the same query terms as in hledger and hledger-web. while editing the- query, you can use ctrl-a/e/d/k, bs, cursor keys; press enter to set+ / lets you set a general filter query limiting the data shown, using+ the same query terms as in hledger and hledger-web. while editing the+ query, you can use ctrl-a/e/d/k, bs, cursor keys; press enter to set it, or escapeto cancel. there are also keys for quickly adjusting some- common filters like account depth and transaction status (see below).+ common filters like account depth and transaction status (see below). backspace or delete removes all filters, showing all transactions. - as mentioned above, by default hledger-ui hides future transactions -+ as mentioned above, by default hledger-ui hides future transactions - both ordinary transactions recorded in the journal, and periodic trans-- actions generated by rule. f toggles forecast mode, in which fu-+ actions generated by rule. f toggles forecast mode, in which fu- ture/forecasted transactions are shown. (experimental) - escape resets the UI state and jumps back to the top screen, restoring+ escape resets the UI state and jumps back to the top screen, restoring the app's initial state at startup. Or, it cancels minibuffer data en- try or the help dialog. ctrl-l redraws the screen and centers the selection if possible (selec-- tions near the top won't be centered, since we don't scroll above the+ tions near the top won't be centered, since we don't scroll above the top). - g reloads from the data file(s) and updates the current screen and any- previous screens. (with large files, this could cause a noticeable+ g reloads from the data file(s) and updates the current screen and any+ previous screens. (with large files, this could cause a noticeable pause.) - i toggles balance assertion checking. disabling balance assertions+ i toggles balance assertion checking. disabling balance assertions temporarily can be useful for troubleshooting. - a runs command-line hledger's add command, and reloads the updated+ a runs command-line hledger's add command, and reloads the updated file. this allows some basic data entry. - a is like a, but runs the hledger-iadd tool, which provides a terminal- interface. this key will be available if hledger-iadd is installed in+ a is like a, but runs the hledger-iadd tool, which provides a terminal+ interface. this key will be available if hledger-iadd is installed in $path. - e runs $hledger_ui_editor, or $editor, or a default (emacsclient -a ""- -nw) on the journal file. with some editors (emacs, vi), the cursor- will be positioned at the current transaction when invoked from the- register and transaction screens, and at the error location (if possi-+ e runs $hledger_ui_editor, or $editor, or a default (emacsclient -a ""+ -nw) on the journal file. with some editors (emacs, vi), the cursor+ will be positioned at the current transaction when invoked from the+ register and transaction screens, and at the error location (if possi- ble) when invoked from the error screen. - b toggles cost mode, showing amounts in their transaction price's com-+ b toggles cost mode, showing amounts in their transaction price's com- modity (like toggling the -b/--cost flag). - v toggles value mode, showing amounts' current market value in their- default valuation commodity (like toggling the -v/--market flag).- note, "current market value" means the value on the report end date if- specified, otherwise today. to see the value on another date, you can- temporarily set that as the report end date. eg: to see a transaction- as it was valued on july 30, go to the accounts or register screen,+ v toggles value mode, showing amounts' current market value in their+ default valuation commodity (like toggling the -v/--market flag).+ note, "current market value" means the value on the report end date if+ specified, otherwise today. to see the value on another date, you can+ temporarily set that as the report end date. eg: to see a transaction+ as it was valued on july 30, go to the accounts or register screen, press /, and add date:-7/30 to the query. at most one of cost or value mode can be active at once. - there's not yet any visual reminder when cost or value mode is active;+ there's not yet any visual reminder when cost or value mode is active; for now pressing b b v should reliably reset to normal mode. - with --watch active, if you save an edit to the journal file while+ with --watch active, if you save an edit to the journal file while viewing the transaction screen in cost or value mode, the b/v keys will- stop working. to work around, press g to force a manual reload, or+ stop working. to work around, press g to force a manual reload, or exit the transaction screen. q quits the application.@@ -275,43 +279,43 @@ screens accounts screen- this is normally the first screen displayed. it lists accounts and- their balances, like hledger's balance command. by default, it shows- all accounts and their latest ending balances (including the balances- of subaccounts). if you specify a query on the command line, it shows+ this is normally the first screen displayed. it lists accounts and+ their balances, like hledger's balance command. by default, it shows+ all accounts and their latest ending balances (including the balances+ of subaccounts). if you specify a query on the command line, it shows just the matched accounts and the balances from matched transactions. - Account names are shown as a flat list by default; press t to toggle- tree mode. In list mode, account balances are exclusive of subac-- counts, except where subaccounts are hidden by a depth limit (see be-+ Account names are shown as a flat list by default; press t to toggle+ tree mode. In list mode, account balances are exclusive of subac-+ counts, except where subaccounts are hidden by a depth limit (see be- low). In tree mode, all account balances are inclusive of subaccounts. - To see less detail, press a number key, 1 to 9, to set a depth limit.+ To see less detail, press a number key, 1 to 9, to set a depth limit. Or use - to decrease and +/= to increase the depth limit. 0 shows even- less detail, collapsing all accounts to a single total. To remove the+ less detail, collapsing all accounts to a single total. To remove the depth limit, set it higher than the maximum account depth, or press ES- CAPE. H toggles between showing historical balances or period balances. His-- torical balances (the default) are ending balances at the end of the- report period, taking into account all transactions before that date- (filtered by the filter query if any), including transactions before- the start of the report period. In other words, historical balances- are what you would see on a bank statement for that account (unless- disturbed by a filter query). Period balances ignore transactions be-- fore the report start date, so they show the change in balance during+ torical balances (the default) are ending balances at the end of the+ report period, taking into account all transactions before that date+ (filtered by the filter query if any), including transactions before+ the start of the report period. In other words, historical balances+ are what you would see on a bank statement for that account (unless+ disturbed by a filter query). Period balances ignore transactions be-+ fore the report start date, so they show the change in balance during the report period. They are more useful eg when viewing a time log. U toggles filtering by unmarked status, including or excluding unmarked postings in the balances. Similarly, P toggles pending postings, and C- toggles cleared postings. (By default, balances include all postings;- if you activate one or two status filters, only those postings are in-+ toggles cleared postings. (By default, balances include all postings;+ if you activate one or two status filters, only those postings are in- cluded; and if you activate all three, the filter is removed.) R toggles real mode, in which virtual postings are ignored. - Z toggles nonzero mode, in which only accounts with nonzero balances- are shown (hledger-ui shows zero items by default, unlike command-line+ Z toggles nonzero mode, in which only accounts with nonzero balances+ are shown (hledger-ui shows zero items by default, unlike command-line hledger). Press right or enter to view an account's transactions register.@@ -320,63 +324,63 @@ This screen shows the transactions affecting a particular account, like a check register. Each line represents one transaction and shows: - o the other account(s) involved, in abbreviated form. (If there are- both real and virtual postings, it shows only the accounts affected+ o the other account(s) involved, in abbreviated form. (If there are+ both real and virtual postings, it shows only the accounts affected by real postings.) - o the overall change to the current account's balance; positive for an+ o the overall change to the current account's balance; positive for an inflow to this account, negative for an outflow. o the running historical total or period total for the current account,- after the transaction. This can be toggled with H. Similar to the- accounts screen, the historical total is affected by transactions- (filtered by the filter query) before the report start date, while+ after the transaction. This can be toggled with H. Similar to the+ accounts screen, the historical total is affected by transactions+ (filtered by the filter query) before the report start date, while the period total is not. If the historical total is not disturbed by- a filter query, it will be the running historical balance you would+ a filter query, it will be the running historical balance you would see on a bank register for the current account. - Transactions affecting this account's subaccounts will be included in+ Transactions affecting this account's subaccounts will be included in the register if the accounts screen is in tree mode, or if it's in list- mode but this account has subaccounts which are not shown due to a- depth limit. In other words, the register always shows the transac-- tions contributing to the balance shown on the accounts screen. Tree+ mode but this account has subaccounts which are not shown due to a+ depth limit. In other words, the register always shows the transac-+ tions contributing to the balance shown on the accounts screen. Tree mode/list mode can be toggled with t here also. - U toggles filtering by unmarked status, showing or hiding unmarked+ U toggles filtering by unmarked status, showing or hiding unmarked transactions. Similarly, P toggles pending transactions, and C toggles- cleared transactions. (By default, transactions with all statuses are- shown; if you activate one or two status filters, only those transac-+ cleared transactions. (By default, transactions with all statuses are+ shown; if you activate one or two status filters, only those transac- tions are shown; and if you activate all three, the filter is removed.) R toggles real mode, in which virtual postings are ignored. - Z toggles nonzero mode, in which only transactions posting a nonzero- change are shown (hledger-ui shows zero items by default, unlike com-+ Z toggles nonzero mode, in which only transactions posting a nonzero+ change are shown (hledger-ui shows zero items by default, unlike com- mand-line hledger). Press right (or enter) to view the selected transaction in detail. Transaction screen- This screen shows a single transaction, as a general journal entry,- similar to hledger's print command and journal format (hledger_jour-+ This screen shows a single transaction, as a general journal entry,+ similar to hledger's print command and journal format (hledger_jour- nal(5)). - The transaction's date(s) and any cleared flag, transaction code, de-- scription, comments, along with all of its account postings are shown.- Simple transactions have two postings, but there can be more (or in+ The transaction's date(s) and any cleared flag, transaction code, de-+ scription, comments, along with all of its account postings are shown.+ Simple transactions have two postings, but there can be more (or in certain cases, fewer). - up and down will step through all transactions listed in the previous- account register screen. In the title bar, the numbers in parentheses- show your position within that account register. They will vary de-+ up and down will step through all transactions listed in the previous+ account register screen. In the title bar, the numbers in parentheses+ show your position within that account register. They will vary de- pending on which account register you came from (remember most transac-- tions appear in multiple account registers). The #N number preceding+ tions appear in multiple account registers). The #N number preceding them is the transaction's position within the complete unfiltered jour- nal, which is a more stable id (at least until the next reload). Error screen- This screen will appear if there is a problem, such as a parse error,- when you press g to reload. Once you have fixed the problem, press g+ This screen will appear if there is a problem, such as a parse error,+ when you press g to reload. Once you have fixed the problem, press g again to reload and resume normal operation. (Or, you can press escape to cancel the reload attempt.) @@ -384,15 +388,15 @@ COLUMNS The screen width to use. Default: the full terminal width. LEDGER_FILE The journal file path when not specified with -f. Default:- ~/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.jour-+ ~/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.jour- nal). - A typical value is ~/DIR/YYYY.journal, where DIR is a version-con-- trolled finance directory and YYYY is the current year. Or ~/DIR/cur-+ A typical value is ~/DIR/YYYY.journal, where DIR is a version-con-+ trolled finance directory and YYYY is the current year. Or ~/DIR/cur- rent.journal, where current.journal is a symbolic link to YYYY.journal. On Mac computers, you can set this and other environment variables in a- more thorough way that also affects applications started from the GUI+ more thorough way that also affects applications started from the GUI (say, an Emacs dock icon). Eg on MacOS Catalina I have a ~/.MacOSX/en- vironment.plist file containing @@ -403,13 +407,13 @@ To see the effect you may need to killall Dock, or reboot. FILES- Reads data from one or more files in hledger journal, timeclock, time-- dot, or CSV format specified with -f, or $LEDGER_FILE, or- $HOME/.hledger.journal (on windows, perhaps+ Reads data from one or more files in hledger journal, timeclock, time-+ dot, or CSV format specified with -f, or $LEDGER_FILE, or+ $HOME/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.journal). BUGS- The need to precede options with -- when invoked from hledger is awk-+ The need to precede options with -- when invoked from hledger is awk- ward. -f- doesn't work (hledger-ui can't read from stdin).@@ -417,24 +421,24 @@ -V affects only the accounts screen. When you press g, the current and all previous screens are regenerated,- which may cause a noticeable pause with large files. Also there is no+ which may cause a noticeable pause with large files. Also there is no visual indication that this is in progress. - --watch is not yet fully robust. It works well for normal usage, but- many file changes in a short time (eg saving the file thousands of- times with an editor macro) can cause problems at least on OSX. Symp-- toms include: unresponsive UI, periodic resetting of the cursor posi-+ --watch is not yet fully robust. It works well for normal usage, but+ many file changes in a short time (eg saving the file thousands of+ times with an editor macro) can cause problems at least on OSX. Symp-+ toms include: unresponsive UI, periodic resetting of the cursor posi- tion, momentary display of parse errors, high CPU usage eventually sub- siding, and possibly a small but persistent build-up of CPU usage until the program is restarted. - Also, if you are viewing files mounted from another machine, --watch+ Also, if you are viewing files mounted from another machine, --watch requires that both machine clocks are roughly in step. REPORTING BUGS- Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel+ Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel or hledger mail list) @@ -448,7 +452,7 @@ SEE ALSO- hledger(1), hledger-ui(1), hledger-web(1), hledger-api(1),+ hledger(1), hledger-ui(1), hledger-web(1), hledger-api(1), hledger_csv(5), hledger_journal(5), hledger_timeclock(5), hledger_time- dot(5), ledger(1) @@ -456,4 +460,4 @@ -hledger-ui 1.18.99 September 2020 hledger-ui(1)+hledger-ui 1.20 November 2020 hledger-ui(1)
embeddedfiles/hledger-web.1 view
@@ -1,5 +1,5 @@ -.TH "hledger-web" "1" "September 2020" "hledger-web 1.18.99" "hledger User Manuals"+.TH "hledger-web" "1" "November 2020" "hledger-web 1.20" "hledger User Manuals" @@ -88,6 +88,10 @@ \f[B]\f[CB]--capabilities-header=HTTPHEADER\f[B]\f[R] read capabilities to enable from a HTTP header, like X-Sandstorm-Permissions (default: disabled)+.TP+\f[B]\f[CB]--test\f[B]\f[R]+run hledger-web\[aq]s tests and exit.+hspec test runner args may follow a --, eg: hledger-web --test -- --help .PP hledger input options: .TP@@ -114,6 +118,9 @@ \f[B]\f[CB]-I --ignore-assertions\f[B]\f[R] disable balance assertion checks (note: does not disable balance assignments)+.TP+\f[B]\f[CB]-s --strict\f[B]\f[R]+do extra error checking (check that all posted accounts are declared) .PP hledger reporting options: .TP@@ -349,6 +356,7 @@ .IP .nf \f[C]+/version /accountnames /transactions /prices
embeddedfiles/hledger-web.info view
@@ -3,8 +3,8 @@ File: hledger-web.info, Node: Top, Next: OPTIONS, Up: (dir) -hledger-web(1) hledger-web 1.18.99-**********************************+hledger-web(1) hledger-web 1.20+******************************* hledger-web - web interface for the hledger accounting tool @@ -97,7 +97,11 @@ read capabilities to enable from a HTTP header, like X-Sandstorm-Permissions (default: disabled)+'--test' + run hledger-web's tests and exit. hspec test runner args may+ follow a -, eg: hledger-web -test - -help+ hledger input options: '-f FILE --file=FILE'@@ -123,7 +127,11 @@ disable balance assertion checks (note: does not disable balance assignments)+'-s --strict' + do extra error checking (check that all posted accounts are+ declared)+ hledger reporting options: '-b --begin=DATE'@@ -355,6 +363,7 @@ You can get JSON data from these routes: +/version /accountnames /transactions /prices@@ -580,22 +589,22 @@ Tag Table: Node: Top72-Node: OPTIONS1752-Ref: #options1857-Node: PERMISSIONS8737-Ref: #permissions8876-Node: EDITING UPLOADING DOWNLOADING10088-Ref: #editing-uploading-downloading10269-Node: RELOADING11103-Ref: #reloading11237-Node: JSON API11670-Ref: #json-api11784-Node: ENVIRONMENT17265-Ref: #environment17381-Node: FILES18114-Ref: #files18214-Node: BUGS18427-Ref: #bugs18505+Node: OPTIONS1746+Ref: #options1851+Node: PERMISSIONS8950+Ref: #permissions9089+Node: EDITING UPLOADING DOWNLOADING10301+Ref: #editing-uploading-downloading10482+Node: RELOADING11316+Ref: #reloading11450+Node: JSON API11883+Ref: #json-api11997+Node: ENVIRONMENT17487+Ref: #environment17603+Node: FILES18336+Ref: #files18436+Node: BUGS18649+Ref: #bugs18727 End Tag Table
embeddedfiles/hledger-web.txt view
@@ -80,6 +80,9 @@ read capabilities to enable from a HTTP header, like X-Sand- storm-Permissions (default: disabled) + --test run hledger-web's tests and exit. hspec test runner args may+ follow a --, eg: hledger-web --test -- --help+ hledger input options: -f FILE --file=FILE@@ -87,7 +90,7 @@ $LEDGER_FILE or $HOME/.hledger.journal) --rules-file=RULESFILE- Conversion rules file to use when reading CSV (default:+ Conversion rules file to use when reading CSV (default: FILE.rules) --separator=CHAR@@ -105,6 +108,10 @@ disable balance assertion checks (note: does not disable balance assignments) + -s --strict+ do extra error checking (check that all posted accounts are de-+ clared)+ hledger reporting options: -b --begin=DATE@@ -314,6 +321,7 @@ You can get JSON data from these routes: + /version /accountnames /transactions /prices@@ -545,4 +553,4 @@ -hledger-web 1.18.99 September 2020 hledger-web(1)+hledger-web 1.20 November 2020 hledger-web(1)
embeddedfiles/hledger.1 view
@@ -1,6 +1,6 @@ .\"t -.TH "hledger" "1" "September 2020" "hledger 1.18.99" "hledger User Manuals"+.TH "hledger" "1" "November 2020" "hledger 1.20" "hledger User Manuals" @@ -566,6 +566,9 @@ \f[B]\f[CB]-I --ignore-assertions\f[B]\f[R] disable balance assertion checks (note: does not disable balance assignments)+.TP+\f[B]\f[CB]-s --strict\f[B]\f[R]+do extra error checking (check that all posted accounts are declared) .PP General reporting options: .TP@@ -1060,6 +1063,31 @@ .IP \[bu] 2 or concatenate the files into one before reading, eg: \f[C]cat a.journal b.journal | hledger -f- CMD\f[R].+.SS Strict mode+.PP+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[C]-s\f[R]/\f[C]--strict\f[R] flag, additional checks are+performed:+.IP \[bu] 2+Are all accounts posted to, declared with an \f[C]account\f[R] directive+?+(Account error checking)+.IP \[bu] 2+Are all commodities declared with a \f[C]commodity\f[R] directive ?+(Commodity error checking)+.PP+See also: https://hledger.org/checking-for-errors.html+.PP+\f[I]experimental.\f[R] .SS Output destination .PP hledger commands send their output to the terminal by default.@@ -1588,10 +1616,12 @@ If you want intervals that start on arbitrary day of your choosing and span a week, month or year, you need to use any of the following: .PP-\f[C]every Nth day of week\f[R], \f[C]every <weekday>\f[R],+\f[C]every Nth day of week\f[R], \f[C]every WEEKDAYNAME\f[R] (eg+\f[C]mon|tue|wed|thu|fri|sat|sun\f[R]), \f[C]every Nth day [of month]\f[R],-\f[C]every Nth weekday [of month]\f[R], \f[C]every MM/DD [of year]\f[R],-\f[C]every Nth MMM [of year]\f[R], \f[C]every MMM Nth [of year]\f[R].+\f[C]every Nth WEEKDAYNAME [of month]\f[R],+\f[C]every MM/DD [of year]\f[R], \f[C]every Nth MMM [of year]\f[R],+\f[C]every MMM Nth [of year]\f[R]. .PP Examples: .PP@@ -1761,7 +1791,7 @@ \[dq]today\[dq]. .PP For multiperiod reports, each column/period is valued on the last day of-the period.+the period, by default. .SS Market prices .PP \f[I](experimental)\f[R]@@ -1772,15 +1802,19 @@ .IP "1." 3 A \f[I]declared market price\f[R] or \f[I]inferred market price\f[R]: A\[aq]s latest market price in B on or before the valuation date as-declared by a P directive, or (if the \f[C]--infer-value\f[R] flag is-used) inferred from transaction prices.+declared by a P directive, or (with the \f[C]--infer-value\f[R] flag)+inferred from transaction prices. .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]chained market price\f[R]: a synthetic price formed by combining-the shortest chain of market prices (any of the above types) leading-from A to B.+A \f[I]a forward chain of market prices\f[R]: a synthetic price formed+by combining the shortest chain of \[dq]forward\[dq] (only 1 above)+market prices, leading from A to B.+.IP "4." 3+A \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. .PP Amounts for which no applicable market price can be found, are not converted.@@ -2113,7 +2147,7 @@ .PP .TS tab(@);-lw(11.7n) lw(11.2n) lw(11.9n) lw(13.1n) lw(12.4n) lw(9.8n).+lw(10.6n) lw(13.2n) lw(13.4n) lw(11.0n) lw(13.4n) lw(8.2n). T{ Report type T}@T{@@ -2150,7 +2184,7 @@ value at DATE/today T} T{-balance assertions / assignments+balance assertions/assignments T}@T{ unchanged T}@T{@@ -2178,7 +2212,7 @@ T}@T{ T} T{-starting balance (with -H)+starting balance (-H) T}@T{ cost T}@T{@@ -2191,7 +2225,7 @@ value at DATE/today T} T{-posting amounts (no report interval)+posting amounts T}@T{ cost T}@T{@@ -2204,7 +2238,7 @@ value at DATE/today T} T{-summary posting amounts (with report interval)+summary posting amounts with report interval T}@T{ summarised cost T}@T{@@ -2237,7 +2271,7 @@ T}@T{ T} T{-\f[B]balance (bs, bse, cf, is..)\f[R]+\f[B]balance (bs, bse, cf, is)\f[R] T}@T{ T}@T{ T}@T{@@ -2245,7 +2279,7 @@ T}@T{ T} T{-balances (no report interval)+balance changes T}@T{ sums of costs T}@T{@@ -2258,71 +2292,112 @@ value at DATE/today of sums of postings T} T{-balances (with report interval)+budget amounts (--budget) T}@T{-sums of costs+like balance changes T}@T{-value at period ends of sums of postings+like balance changes T}@T{ not supported T}@T{-value at period ends of sums of postings+like balances T}@T{-value at DATE/today of sums of postings+like balance changes T} T{-starting balances (with report interval and -H)+grand total T}@T{+sum of displayed values+T}@T{+sum of displayed values+T}@T{+not supported+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{-sums of postings before report start+value at report start of sums of all postings before report start T}@T{ not supported T}@T{-sums of postings before report start+value at report start of sums of all postings before report start T}@T{ sums of postings before report start T} T{-budget amounts with --budget+balance changes (bal, is, bs --change, cf --change) T}@T{-like balances+sums of costs of postings in period T}@T{-like balances+same as --value=end T}@T{ not supported T}@T{-like balances+balance change in each period, valued at period ends T}@T{-like balances+value at DATE/today of sums of postings T} T{-grand total (no report interval)+end balances (bal -H, is --H, bs, cf) T}@T{-sum of displayed values+sums of costs of postings from before report start to period end T}@T{-sum of displayed values+same as --value=end T}@T{ not supported T}@T{-sum of displayed values+period end balances, valued at period ends T}@T{-sum of displayed values+value at DATE/today of sums of postings T} T{-row totals/averages (with report interval)+budget amounts (--budget) T}@T{-sums/averages of displayed values+like balance changes/end balances T}@T{-sums/averages of displayed values+like balance changes/end balances T}@T{ not supported T}@T{-sums/averages of displayed values+like balances T}@T{-sums/averages of displayed values+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{+not supported+T}@T{+sums, averages of displayed values+T}@T{+sums, averages of displayed values+T}+T{ column totals T}@T{ sums of displayed values@@ -2336,17 +2411,17 @@ sums of displayed values T} T{-grand total/average+grand total, grand average T}@T{-sum/average of column totals+sum, average of column totals T}@T{-sum/average of column totals+sum, average of column totals T}@T{ not supported T}@T{-sum/average of column totals+sum, average of column totals T}@T{-sum/average of column totals+sum, average of column totals T} T{ T}@T{@@ -2357,6 +2432,9 @@ T} .TE .PP+\f[C]--cumulative\f[R] is omitted to save space, it works like+\f[C]-H\f[R] but with a zero starting balance.+.PP \f[B]Glossary:\f[R] .TP \f[I]cost\f[R]@@ -2680,11 +2758,8 @@ .fi .PP By default, accounts are displayed hierarchically, with subaccounts-indented below their parent.-At each level of the tree, accounts are sorted by account code if any,-then by account name.-Or with \f[C]-S/--sort-amount\f[R], by their balance amount, largest-first.+indented below their parent, with accounts at each level of the tree+sorted by declaration order if declared, then by account name. .PP \[dq]Boring\[dq] accounts, which contain a single interesting subaccount and no balance of their own, are elided into the following line for more@@ -2856,6 +2931,19 @@ If there are mixed commodity accounts in the report be sure to use \f[C]-V\f[R] or \f[C]-B\f[R] to coerce the report into using a single commodity.+.SS Sorting by amount+.PP+With \f[C]-S\f[R]/\f[C]--sort-amount\f[R], accounts with the largest+(most positive) balances are shown first.+For example, \f[C]hledger bal expenses -MAS\f[R] shows your biggest+averaged monthly expenses first.+.PP+Revenues and liability balances are typically negative, however, so+\f[C]-S\f[R] shows these in reverse order.+To work around this, you can add \f[C]--invert\f[R] to flip the signs.+Or, use one of the sign-flipping reports like \f[C]balancesheet\f[R] or+\f[C]incomestatement\f[R], which also support \f[C]-S\f[R].+Eg: \f[C]hledger is -MAS\f[R]. .SS Multicolumn balance report .PP Multicolumn or tabular balance reports are a very useful hledger@@ -3133,7 +3221,60 @@ \f[R] .fi .PP-For more examples, see Budgeting and Forecasting.+For more examples and notes, see Budgeting.+.SS Budget report start date+.PP+This might be a bug, but for now: when making budget reports, it\[aq]s a+good idea to explicitly set the report\[aq]s start date to the first day+of a reporting period, because a periodic rule like+\f[C]\[ti] monthly\f[R] generates its transactions on the 1st of each+month, and if your journal has no regular transactions on the 1st, the+default report start date could exclude that budget goal, which can be a+little surprising.+Eg here the default report period is just the day of 2020-01-15:+.IP+.nf+\f[C]+\[ti] monthly in 2020+ (expenses:food) $500++2020-01-15+ expenses:food $400+ assets:checking+\f[R]+.fi+.IP+.nf+\f[C]+$ hledger bal expenses --budget+Budget performance in 2020-01-15:++ || 2020-01-15 +==============++============+ <unbudgeted> || $400 +--------------++------------+ || $400 +\f[R]+.fi+.PP+To avoid this, specify the budget report\[aq]s period, or at least the+start date, with \f[C]-b\f[R]/\f[C]-e\f[R]/\f[C]-p\f[R]/\f[C]date:\f[R],+to ensure it includes the budget goal transactions (periodic+transactions) that you want.+Eg, adding \f[C]-b 2020/1/1\f[R] to the above:+.IP+.nf+\f[C]+$ hledger bal expenses --budget -b 2020/1/1+Budget performance in 2020-01-01..2020-01-15:++ || 2020-01-01..2020-01-15 +===============++========================+ expenses:food || $400 [80% of $500] +---------------++------------------------+ || $400 [80% of $500] +\f[R]+.fi .SS Nested budgets .PP You can add budgets to any account in your account hierarchy.@@ -3239,9 +3380,8 @@ .SS Output format .PP This command also supports the output destination and output format-options The output formats supported are \f[C]txt\f[R], \f[C]csv\f[R],-(multicolumn non-budget reports only) \f[C]html\f[R], and (experimental)-\f[C]json\f[R].+options The output formats supported are (in most modes): \f[C]txt\f[R],+\f[C]csv\f[R], \f[C]html\f[R], and \f[C]json\f[R]. .SS balancesheet .PP balancesheet, bs@@ -3396,28 +3536,79 @@ This command also supports the output destination and output format options The output formats supported are \f[C]txt\f[R], \f[C]csv\f[R], \f[C]html\f[R], and (experimental) \f[C]json\f[R].-.SS check-dates+.SS check .PP-check-dates+check .PD 0 .P .PD-Check that transactions are sorted by increasing date.-With --date2, checks secondary dates instead.-With --strict, dates must also be unique.-With a query, only matched transactions\[aq] dates are checked.-Reads the default journal file, or another specified with -f.-.SS check-dupes+Check for various kinds of errors in your data.+\f[I]experimental\f[R] .PP-check-dupes-.PD 0-.P-.PD-Reports account names having the same leaf but different prefixes.-In other words, two or more leaves that are categorized differently.-Reads the default journal file, or another specified as an argument.+hledger provides a number of built-in error checks to help prevent+problems in your data.+Some of these are run automatically; or, you can use this+\f[C]check\f[R] command to run them on demand, with no output and a zero+exit code if all is well.+Some examples:+.IP+.nf+\f[C]+hledger check # basic checks+hledger check -s # basic + strict checks+hledger check ordereddates uniqueleafnames # basic + specified checks+\f[R]+.fi .PP-An example: http://stefanorodighiero.net/software/hledger-dupes.html+Here are the checks currently available:+.SS Basic checks+.PP+These are always run by this command and other commands:+.IP \[bu] 2+\f[B]parseable\f[R] - data files are well-formed and can be successfully+parsed+.IP \[bu] 2+\f[B]autobalanced\f[R] - all transactions are balanced, inferring+missing amounts where necessary, and possibly converting commodities+using transaction prices or automatically-inferred transaction prices+.IP \[bu] 2+\f[B]assertions\f[R] - all balance assertions in the journal are+passing.+(This check can be disabled with+\f[C]-I\f[R]/\f[C]--ignore-assertions\f[R].)+.SS Strict checks+.PP+These are always run by this and other commands when+\f[C]-s\f[R]/\f[C]--strict\f[R] is used (strict mode):+.IP \[bu] 2+\f[B]accounts\f[R] - all account names used by transactions have been+declared+.IP \[bu] 2+\f[B]commodities\f[R] - all commodity symbols used have been declared+.SS Other checks+.PP+These checks can be run by specifying their names as arguments to the+check command:+.IP \[bu] 2+\f[B]ordereddates\f[R] - transactions are ordered by date (similar to+the old \f[C]check-dates\f[R] command)+.IP \[bu] 2+\f[B]uniqueleafnames\f[R] - all account leaf names are unique (similar+to the old \f[C]check-dupes\f[R] command)+.SS Addon checks+.PP+Some checks are not yet integrated with this command, but are available+as add-on commands in+https://github.com/simonmichael/hledger/tree/master/bin:+.IP \[bu] 2+\f[B]hledger-check-tagfiles\f[R] - all tag values containing / (a+forward slash) exist as file paths+.IP \[bu] 2+\f[B]hledger-check-fancyassertions\f[R] - more complex balance+assertions are passing+.PP+You could make your own similar scripts to perform custom checks;+Cookbook -> Scripting may be helpful. .SS close .PP close, equity@@ -3773,6 +3964,10 @@ .PP (If you think import should leave amounts implicit like print does, please test it and send a pull request.)+.SS Commodity display styles+.PP+Imported amounts will be formatted according to the canonical commodity+styles (declared or inferred) in the main journal file. .SS incomestatement .PP incomestatement, is@@ -4410,11 +4605,295 @@ name) to select your investments with \f[C]--inv\f[R], and another query to identify your profit and loss transactions with \f[C]--pnl\f[R]. .PP-It will compute and display the internalized rate of return (IRR) and-time-weighted rate of return (TWR) for your investments for the time-period requested.+This command will compute and display the internalized rate of return+(IRR) and time-weighted rate of return (TWR) for your investments for+the time period requested. Both rates of return are annualized before display, regardless of the length of reporting interval.+.PP+Note, in some cases this report can fail, for these reasons:+.IP \[bu] 2+Error (NotBracketed): 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+Error (SearchFailed): Failed to find solution for Internal Rate of+Return (IRR).+Either search does not converge to a solution, or converges too slowly.+.PP+Examples:+.IP \[bu] 2+Using roi to report unrealised gains:+https://github.com/simonmichael/hledger/blob/master/examples/roi-unrealised.ledger+.PP+More background:+.PP+\[dq]ROI\[dq] stands for \[dq]return 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+investments receives no in-flows or out-flows of money, and where 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+Internal rate of return, or \[dq]IRR\[dq] (also called+\[dq]money-weighted rate of return\[dq]) takes into account effects of+in-flows and out-flows.+Naively, if you are withdrawing from your investment, your future gains+would be smaller (in absolute numbers), and will be a smaller percentage+of your initial investment, and if you are adding to your investment,+you will receive bigger absolute gains (but probably at the same rate of+return).+IRR is a way to compute rate of return for each period between in-flow+or out-flow of money, and then combine them in a way that gives you an+annual rate of return that investment is expected to generate.+.PP+As mentioned before, in-flows and out-flows would be any cash that you+personally put in or withdraw, and for the \[dq]roi\[dq] command, these+are transactions that involve account(s) matching \f[C]--inv\f[R]+argument and NOT involve account(s) matching \f[C]--pnl\f[R] argument.+.PP+Presumably, you will also record changes in the value of your+investment, and balance them against \[dq]profit and loss\[dq] (or+\[dq]unrealized gains\[dq]) account.+Note that in order for IRR to compute the precise effect of your+in-flows and out-flows on the rate of return, you will need to record+the value of your investement on or close to the days when in- or+out-flows occur.+.PP+Implementation of IRR in hledger should match the \f[C]XIRR\f[R] formula+in Excel.+.PP+Second way to compute rate of return that \f[C]roi\f[R] command+implements is called \[dq]time-weighted rate of return\[dq] or+\[dq]TWR\[dq].+Like IRR, it will also break the history of your investment into periods+between in-flows and out-flows to compute rate of return per each period+and then a compound rate of return.+However, internal workings of TWR are quite different.+.PP+In technical terms, IRR uses the same approach as computation of net+present value, and tries to find a discount rate that makes net present+value of all the cash flows of your investment to add up to zero.+This could be hard to wrap your head around, especially if you+haven\[aq]t done discounted cash flow analysis before.+.PP+TWR represents your investment as an imaginary \[dq]unit fund\[dq] where+in-flows/ out-flows lead to buying or selling \[dq]units\[dq] of your+investment and changes in its value change the value of \[dq]investment+unit\[dq].+Change in \[dq]unit price\[dq] over the reporting period gives you rate+of return of your investment.+.PP+References: * Explanation of rate of return * Explanation of IRR *+Explanation of TWR * Examples of computing IRR and TWR and discussion of+the limitations of both metrics+.PP+More examples:+.PP+Lets say that we found an investment in Snake Oil that is proising to+give us 10% annually:+.IP+.nf+\f[C]+2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-12-24 Recording the growth of Snake Oil+ investment:snake oil = $110+ equity:unrealized gains+\f[R]+.fi+.PP+For now, basic computation of the rate of return, as well as IRR and+TWR, gives us the expected 10%:+.IP+.nf+\f[C]+$ hledger roi -Y --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+-----++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 110 | 10 || 10.00% | 10.00% |++---++------------+------------++---------------+----------+-------------+-----++--------+--------++\f[R]+.fi+.PP+However, lets say that shorty after investing in the Snake Oil we+started to have second thoughs, so we prompty withdrew $90, leaving only+$10 in.+Before Christmas, though, we started to get the \[dq]fear of mission+out\[dq], so we put the $90 back in.+So for most of the year, our investment was just $10 dollars, and it+gave us just $1 in growth:+.IP+.nf+\f[C]+2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil+ +2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil = $101+ equity:unrealized gains+\f[R]+.fi+.PP+Now IRR and TWR are drastically different:+.IP+.nf+\f[C]+$ hledger roi -Y --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+-----++-------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++=======+=======++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101 | 1 || 9.32% | 1.00% |++---++------------+------------++---------------+----------+-------------+-----++-------+-------++\f[R]+.fi+.PP+Here, IRR tells us that we made close to 10% on the $10 dollars that we+had in the account most of the time.+And TWR is ...+just 1%?+Why?+.PP+Based on the transactions in our journal, TWR \[dq]think\[dq] that we+are buying back $90 worst of Snake Oil at the same price that it had at+the beginning of they year, and then after that our $100 investment gets+$1 increase in value, or 1% of $100.+Let\[aq]s take a closer look at what is happening here by asking for+quarterly reports instead of annual:+.IP+.nf+\f[C]+$ hledger roi -Q --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+-----++--------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+=======++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10 | 0 || 0.00% | 0.00% |+| 2 || 2019-04-01 | 2019-06-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 3 || 2019-07-01 | 2019-09-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 4 || 2019-10-01 | 2019-12-31 || 10 | 90 | 101 | 1 || 37.80% | 4.03% |++---++------------+------------++---------------+----------+-------------+-----++--------+-------++\f[R]+.fi+.PP+Now both IRR and TWR are thrown off by the fact that all of the growth+for our investment happens in Q4 2019.+This happes because IRR computation is still yielding 9.32% and TWR is+still 1%, but this time these are rates for three month period instead+of twelve, so in order to get an annual rate they should be multiplied+by four!+.PP+Let\[aq]s try to keep a better record of how Snake Oil grew in value:+.IP+.nf+\f[C]+2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil++2019-02-28 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-06-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-09-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25+\f[R]+.fi+.PP+Would our quartery report look better now?+Almost:+.IP+.nf+\f[C]+$ hledger roi -Q --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 1.00% |++---++------------+------------++---------------+----------+-------------+------++--------+--------++\f[R]+.fi+.PP+Something is still wrong with TWR computation for Q4, and if you have+been paying attention you know what it is already: big $90 buy-back is+recorded prior to the only transaction that captures the change of value+of Snake Oil that happened in this time period.+Lets combine transactions from 30th and 31st of Dec into one:+.IP+.nf+\f[C]+2019-12-30 Fear of missing out and growth of Snake Oil+ assets:cash -$90+ investment:snake oil+ equity:unrealized gains -$0.25+\f[R]+.fi+.PP+Now growth of investment properly affects its price at the time of+buy-back:+.IP+.nf+\f[C]+$ hledger roi -Q --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 9.57% |++---++------------+------------++---------------+----------+-------------+------++--------+--------++\f[R]+.fi+.PP+And for annual report, TWR now reports the exact profitability of our+investment:+.IP+.nf+\f[C]+$ hledger roi -Y --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+------++-------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++=======+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101.00 | 1.00 || 9.32% | 10.00% |++---++------------+------------++---------------+----------+-------------+------++-------+--------++\f[R]+.fi .SS stats .PP stats
embeddedfiles/hledger.info view
@@ -3,4263 +3,4698 @@ File: hledger.info, Node: Top, Next: COMMON TASKS, Up: (dir) -hledger(1) hledger 1.18.99-**************************--hledger - a command-line accounting tool-- 'hledger [-f FILE] COMMAND [OPTIONS] [ARGS]'-'hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]'-'hledger'-- hledger is a reliable, 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).-- This is hledger's command-line interface (there are also terminal and-web interfaces). Its basic function is to read a plain text file-describing financial transactions (in accounting terms, a general-journal) and print useful reports on standard output, or export them as-CSV. hledger can also read some other file formats such as CSV files,-translating them to journal format. Additionally, hledger lists other-hledger-* executables found in the user's $PATH and can invoke them as-subcommands.-- hledger reads data from one or more files in hledger journal,-timeclock, timedot, or CSV format specified with '-f', or-'$LEDGER_FILE', or '$HOME/.hledger.journal' (on windows, perhaps-'C:/Users/USER/.hledger.journal'). If using '$LEDGER_FILE', note this-must be a real environment variable, not a shell variable. You can-specify standard input with '-f-'.-- Transactions are dated movements of money between two (or more) named-accounts, and are recorded with journal entries like this:--2015/10/16 bought food- expenses:food $10- assets:cash-- For more about this format, see hledger_journal(5).-- Most users use a text editor to edit the journal, usually with an-editor mode such as ledger-mode for added convenience. hledger's-interactive add command is another way to record new transactions.-hledger never changes existing transactions.-- To get started, you can either save some entries like the above in-'~/.hledger.journal', or run 'hledger add' and follow the prompts. Then-try some commands like 'hledger print' or 'hledger balance'. Run-'hledger' with no arguments for a list of commands.--* Menu:--* COMMON TASKS::-* OPTIONS::-* COMMANDS::-* ENVIRONMENT::-* FILES::-* LIMITATIONS::-* TROUBLESHOOTING::---File: hledger.info, Node: COMMON TASKS, Next: OPTIONS, Prev: Top, Up: Top--1 COMMON TASKS-**************--Here are some quick examples of how to do some basic tasks with hledger.-For more details, see the reference section below, the-hledger_journal(5) manual, or the more extensive docs at-https://hledger.org.--* Menu:--* Getting help::-* Constructing command lines::-* Starting a journal file::-* Setting opening balances::-* Recording transactions::-* Reconciling::-* Reporting::-* Migrating to a new file::---File: hledger.info, Node: Getting help, Next: Constructing command lines, Up: COMMON TASKS--1.1 Getting help-================--$ hledger # show available commands-$ hledger --help # show common options-$ hledger CMD --help # show common and command options, and command help-$ hledger help # show available manuals/topics-$ hledger help hledger # show hledger manual as info/man/text (auto-chosen)-$ hledger help journal --man # show the journal manual as a man page-$ hledger help --help # show more detailed help for the help command-- Find more docs, chat, mail list, reddit, issue tracker:-https://hledger.org#help-feedback---File: hledger.info, Node: Constructing command lines, Next: Starting a journal file, Prev: Getting help, Up: COMMON TASKS--1.2 Constructing command lines-==============================--hledger has an extensive and powerful command line interface. We strive-to keep it simple and ergonomic, but you may run into one of the-confusing real world details described in OPTIONS, below. If that-happens, here are some tips that may help:-- * command-specific options must go after the command (it's fine to- put all options there) ('hledger CMD OPTS ARGS')- * running add-on executables directly simplifies command line parsing- ('hledger-ui OPTS ARGS')- * enclose "problematic" args in single quotes- * if needed, also add a backslash to hide regular expression- metacharacters from the shell- * to see how a misbehaving command is being parsed, add '--debug=2'.---File: hledger.info, Node: Starting a journal file, Next: Setting opening balances, Prev: Constructing command lines, Up: COMMON TASKS--1.3 Starting a journal file-===========================--hledger looks for your accounting data in a journal file,-'$HOME/.hledger.journal' by default:--$ hledger stats-The hledger journal file "/Users/simon/.hledger.journal" was not found.-Please create it first, eg with "hledger add" or a text editor.-Or, specify an existing journal file with -f or LEDGER_FILE.-- You can override this by setting the 'LEDGER_FILE' environment-variable. It's a good practice to keep this important file under-version control, and to start a new file each year. So you could do-something like this:--$ mkdir ~/finance-$ cd ~/finance-$ git init-Initialized empty Git repository in /Users/simon/finance/.git/-$ touch 2020.journal-$ echo "export LEDGER_FILE=$HOME/finance/2020.journal" >> ~/.bashrc-$ source ~/.bashrc-$ hledger stats-Main file : /Users/simon/finance/2020.journal-Included files : -Transactions span : to (0 days)-Last transaction : none-Transactions : 0 (0.0 per day)-Transactions last 30 days: 0 (0.0 per day)-Transactions last 7 days : 0 (0.0 per day)-Payees/descriptions : 0-Accounts : 0 (depth 0)-Commodities : 0 ()-Market prices : 0 ()---File: hledger.info, Node: Setting opening balances, Next: Recording transactions, Prev: Starting a journal file, Up: COMMON TASKS--1.4 Setting opening balances-============================--Pick a starting date for which you can look up the balances of some-real-world assets (bank accounts, wallet..) and liabilities (credit-cards..).-- To avoid a lot of data entry, you may want to start with just one or-two accounts, like your checking account or cash wallet; and pick a-recent starting date, like today or the start of the week. You can-always come back later and add more accounts and older transactions, eg-going back to january 1st.-- Add an opening balances transaction to the journal, declaring the-balances on this date. Here are two ways to do it:-- * The first way: open the journal in any text editor and save an- entry like this:-- 2020-01-01 * opening balances- assets:bank:checking $1000 = $1000- assets:bank:savings $2000 = $2000- assets:cash $100 = $100- liabilities:creditcard $-50 = $-50- equity:opening/closing balances-- These are start-of-day balances, ie whatever was in the account at- the end of the previous day.-- The * after the date is an optional status flag. Here it means- "cleared & confirmed".-- The currency symbols are optional, but usually a good idea as- you'll be dealing with multiple currencies sooner or later.-- The = amounts are optional balance assertions, providing extra- error checking.-- * The second way: run 'hledger add' and follow the prompts to record- a similar transaction:-- $ hledger add- Adding transactions to journal file /Users/simon/finance/2020.journal- Any command line arguments will be used as defaults.- Use tab key to complete, readline keys to edit, enter to accept defaults.- An optional (CODE) may follow transaction dates.- An optional ; COMMENT may follow descriptions or amounts.- If you make a mistake, enter < at any prompt to go one step backward.- To end a transaction, enter . when prompted.- To quit, enter . at a date prompt or press control-d or control-c.- Date [2020-02-07]: 2020-01-01- Description: * opening balances- Account 1: assets:bank:checking- Amount 1: $1000- Account 2: assets:bank:savings- Amount 2 [$-1000]: $2000- Account 3: assets:cash- Amount 3 [$-3000]: $100- Account 4: liabilities:creditcard- Amount 4 [$-3100]: $-50- Account 5: equity:opening/closing balances- Amount 5 [$-3050]: - Account 6 (or . or enter to finish this transaction): .- 2020-01-01 * opening balances- assets:bank:checking $1000- assets:bank:savings $2000- assets:cash $100- liabilities:creditcard $-50- equity:opening/closing balances $-3050- - Save this transaction to the journal ? [y]: - Saved.- Starting the next transaction (. or ctrl-D/ctrl-C to quit)- Date [2020-01-01]: .-- If you're using version control, this could be a good time to commit-the journal. Eg:--$ git commit -m 'initial balances' 2020.journal---File: hledger.info, Node: Recording transactions, Next: Reconciling, Prev: Setting opening balances, Up: COMMON TASKS--1.5 Recording transactions-==========================--As you spend or receive money, you can record these transactions using-one of the methods above (text editor, hledger add) or by using the-hledger-iadd or hledger-web add-ons, or by using the import command to-convert CSV data downloaded from your bank.-- Here are some simple transactions, see the hledger_journal(5) manual-and hledger.org for more ideas:--2020/1/10 * gift received- assets:cash $20- income:gifts--2020.1.12 * farmers market- expenses:food $13- assets:cash--2020-01-15 paycheck- income:salary- assets:bank:checking $1000---File: hledger.info, Node: Reconciling, Next: Reporting, Prev: Recording transactions, Up: COMMON TASKS--1.6 Reconciling-===============--Periodically you should reconcile - compare your hledger-reported-balances against external sources of truth, like bank statements or your-bank's 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.-- A typical workflow:-- 1. Reconcile cash. Count what's in your wallet. Compare with what- hledger reports ('hledger bal cash'). 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- ('hledger reg cash'). If you can't find the error, add an- adjustment transaction. Eg if you have $105 after the above, and- can't explain the missing $2, it could be:-- 2020-01-16 * adjust cash- assets:cash $-2 = $105- expenses:misc-- 2. Reconcile checking. Log in to your bank's website. Compare- today's (cleared) balance with hledger's cleared balance ('hledger- bal checking -C'). 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 'hledger reg checking -C'. This will be- easier if you generally record transaction dates quite similar to- your bank's clearing dates.-- 3. Repeat for other asset/liability accounts.-- Tip: instead of the register command, use hledger-ui to see a-live-updating register while you edit the journal: 'hledger-ui --watch---register checking -C'-- After reconciling, it could be a good time to mark the reconciled-transactions' status as "cleared and confirmed", if you want to track-that, by adding the '*' marker. Eg in the paycheck transaction above,-insert '*' between '2020-01-15' and 'paycheck'-- If you're using version control, this can be another good time to-commit:--$ git commit -m 'txns' 2020.journal---File: hledger.info, Node: Reporting, Next: Migrating to a new file, Prev: Reconciling, Up: COMMON TASKS--1.7 Reporting-=============--Here are some basic reports.-- Show all transactions:--$ hledger print-2020-01-01 * opening balances- assets:bank:checking $1000- assets:bank:savings $2000- assets:cash $100- liabilities:creditcard $-50- equity:opening/closing balances $-3050--2020-01-10 * gift received- assets:cash $20- income:gifts--2020-01-12 * farmers market- expenses:food $13- assets:cash--2020-01-15 * paycheck- income:salary- assets:bank:checking $1000--2020-01-16 * adjust cash- assets:cash $-2 = $105- expenses:misc-- Show account names, and their hierarchy:--$ hledger accounts --tree-assets- bank- checking- savings- cash-equity- opening/closing balances-expenses- food- misc-income- gifts- salary-liabilities- creditcard-- Show all account totals:--$ hledger balance- $4105 assets- $4000 bank- $2000 checking- $2000 savings- $105 cash- $-3050 equity:opening/closing balances- $15 expenses- $13 food- $2 misc- $-1020 income- $-20 gifts- $-1000 salary- $-50 liabilities:creditcard---------------------- 0-- Show only asset and liability balances, as a flat list, limited to-depth 2:--$ hledger bal assets liabilities --flat -2- $4000 assets:bank- $105 assets:cash- $-50 liabilities:creditcard---------------------- $4055-- Show the same thing without negative numbers, formatted as a simple-balance sheet:--$ hledger bs --flat -2-Balance Sheet 2020-01-16-- || 2020-01-16 -========================++============- Assets || -------------------------++------------- assets:bank || $4000 - assets:cash || $105 -------------------------++------------- || $4105 -========================++============- Liabilities || -------------------------++------------- liabilities:creditcard || $50 -------------------------++------------- || $50 -========================++============- Net: || $4055 -- The final total is your "net worth" on the end date. (Or use 'bse'-for a full balance sheet with equity.)-- Show income and expense totals, formatted as an income statement:--hledger is -Income Statement 2020-01-01-2020-01-16-- || 2020-01-01-2020-01-16 -===============++=======================- Revenues || ----------------++------------------------ income:gifts || $20 - income:salary || $1000 ----------------++------------------------ || $1020 -===============++=======================- Expenses || ----------------++------------------------ expenses:food || $13 - expenses:misc || $2 ----------------++------------------------ || $15 -===============++=======================- Net: || $1005 -- The final total is your net income during this period.-- Show transactions affecting your wallet, with running total:--$ hledger register cash-2020-01-01 opening balances assets:cash $100 $100-2020-01-10 gift received assets:cash $20 $120-2020-01-12 farmers market assets:cash $-13 $107-2020-01-16 adjust cash assets:cash $-2 $105-- Show weekly posting counts as a bar chart:--$ hledger activity -W-2019-12-30 *****-2020-01-06 ****-2020-01-13 ****---File: hledger.info, Node: Migrating to a new file, Prev: Reporting, Up: COMMON TASKS--1.8 Migrating to a new file-===========================--At the end of the year, you may want to continue your journal in a new-file, so that old transactions don't slow down or clutter your reports,-and to help ensure the integrity of your accounting history. See the-close command.-- If using version control, don't forget to 'git add' the new file.---File: hledger.info, Node: OPTIONS, Next: COMMANDS, Prev: COMMON TASKS, Up: Top--2 OPTIONS-*********--* Menu:--* General options::-* Command options::-* Command arguments::-* Queries::-* Special characters in arguments and queries::-* Unicode characters::-* Input files::-* Output destination::-* Output format::-* Regular expressions::-* Smart dates::-* Report start & end date::-* Report intervals::-* Period expressions::-* Depth limiting::-* Pivoting::-* Valuation::---File: hledger.info, Node: General options, Next: Command options, Up: OPTIONS--2.1 General options-===================--To see general usage help, including general options which are supported-by most hledger commands, run 'hledger -h'.-- General help options:--'-h --help'-- show general usage (or after COMMAND, command usage)-'--version'-- show version-'--debug[=N]'-- show debug output (levels 1-9, default: 1)-- General input options:--'-f FILE --file=FILE'-- use a different input file. For stdin, use - (default:- '$LEDGER_FILE' or '$HOME/.hledger.journal')-'--rules-file=RULESFILE'-- Conversion rules file to use when reading CSV (default: FILE.rules)-'--separator=CHAR'-- Field separator to expect when reading CSV (default: ',')-'--alias=OLD=NEW'-- rename accounts named OLD to NEW-'--anon'-- anonymize accounts and payees-'--pivot FIELDNAME'-- use some other field or tag for the account name-'-I --ignore-assertions'-- disable balance assertion checks (note: does not disable balance- assignments)-- General reporting options:--'-b --begin=DATE'-- include postings/txns on or after this date-'-e --end=DATE'-- include postings/txns before this date-'-D --daily'-- multiperiod/multicolumn report by day-'-W --weekly'-- multiperiod/multicolumn report by week-'-M --monthly'-- multiperiod/multicolumn report by month-'-Q --quarterly'-- multiperiod/multicolumn report by quarter-'-Y --yearly'-- multiperiod/multicolumn report by year-'-p --period=PERIODEXP'-- set start date, end date, and/or reporting interval all at once- using period expressions syntax-'--date2'-- match the secondary date instead (see command help for other- effects)-'-U --unmarked'-- include only unmarked postings/txns (can combine with -P or -C)-'-P --pending'-- include only pending postings/txns-'-C --cleared'-- include only cleared postings/txns-'-R --real'-- include only non-virtual postings-'-NUM --depth=NUM'-- hide/aggregate accounts or postings more than NUM levels deep-'-E --empty'-- show items with zero amount, normally hidden (and vice-versa in- hledger-ui/hledger-web)-'-B --cost'-- convert amounts to their cost/selling amount at transaction time-'-V --market'-- convert amounts to their market value in default valuation- commodities-'-X --exchange=COMM'-- convert amounts to their market value in commodity COMM-'--value'-- convert amounts to cost or market value, more flexibly than- -B/-V/-X-'--infer-value'-- with -V/-X/-value, also infer market prices from transactions-'--auto'-- apply automated posting rules to modify transactions.-'--forecast'-- generate future transactions from periodic transaction rules, for- the next 6 months or till report end date. In hledger-ui, also- make ordinary future transactions visible.-'--color=WHEN (or --colour=WHEN)'-- Should color-supporting commands use ANSI color codes in text- output. 'auto' (default): whenever stdout seems to be a- color-supporting terminal. 'always' or 'yes': always, useful eg- when piping output into 'less -R'. 'never' or 'no': never. A- NO_COLOR environment variable overrides this.-- When a reporting option appears more than once in the command line,-the last one takes precedence.-- Some reporting options can also be written as query arguments.---File: hledger.info, Node: Command options, Next: Command arguments, Prev: General options, Up: OPTIONS--2.2 Command options-===================--To see options for a particular command, including command-specific-options, run: 'hledger COMMAND -h'.-- Command-specific options must be written after the command name, eg:-'hledger print -x'.-- Additionally, if the command is an addon, you may need to put its-options after a double-hyphen, eg: 'hledger ui -- --watch'. Or, you can-run the addon executable directly: 'hledger-ui --watch'.---File: hledger.info, Node: Command arguments, Next: Queries, Prev: Command options, Up: OPTIONS--2.3 Command arguments-=====================--Most hledger commands accept arguments after the command name, which are-often a query, filtering the data in some way.-- You can save a set of command line options/arguments in a file, and-then reuse them by writing '@FILENAME' as a command line argument. Eg:-'hledger bal @foo.args'. (To prevent this, eg if you have an argument-that begins with a literal '@', precede it with '--', eg: 'hledger bal--- @ARG').-- Inside the argument file, each line should contain just one option or-argument. Avoid the use of spaces, except inside quotes (or you'll see-a confusing error). Between a flag and its argument, use = (or-nothing). Bad:--assets depth:2--X USD-- Good:--assets-depth:2--X=USD-- For special characters (see below), use one less level of quoting-than you would at the command prompt. Bad:---X"$"-- Good:---X$-- See also: Save frequently used options.---File: hledger.info, Node: Queries, Next: Special characters in arguments and queries, Prev: Command arguments, Up: OPTIONS--2.4 Queries-===========--One of hledger's strengths is being able to quickly report on precise-subsets of your data. Most commands accept an optional query-expression, written as arguments after the command name, to filter the-data by date, account name or other criteria. The syntax is similar to-a web search: one or more space-separated search terms, quotes to-enclose whitespace, prefixes to match specific fields, a not: prefix to-negate the match.-- We do not yet support arbitrary boolean combinations of search terms;-instead most commands show transactions/postings/accounts which match-(or negatively match):-- * any of the description terms AND- * any of the account terms AND- * any of the status terms AND- * all the other terms.-- The print command instead shows transactions which:-- * match any of the description terms AND- * have any postings matching any of the positive account terms AND- * have no postings matching any of the negative account terms AND- * match all the other terms.-- The following kinds of search terms can be used. Remember these can-also be prefixed with *'not:'*, eg to exclude a particular subaccount.--*'REGEX', 'acct:REGEX'*-- match account names by this regular expression. (With no prefix,- 'acct:' is assumed.) same as above--*'amt:N, amt:<N, amt:<=N, amt:>N, amt:>=N'*-- match postings with a single-commodity amount that is equal to,- less than, or greater than N. (Multi-commodity amounts are not- tested, and will always match.) 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.-*'code:REGEX'*-- match by transaction code (eg check number)-*'cur:REGEX'*-- match postings or transactions including any amounts whose- currency/commodity symbol is fully matched by REGEX. (For a partial- match, use '.*REGEX.*'). Note, to match characters which are- regex-significant, like the dollar sign ('$'), you need to prepend- '\'. And when using the command line you need to add one more- level of quoting to hide it from the shell, so eg do: 'hledger- print cur:'\$'' or 'hledger print cur:\\$'.-*'desc:REGEX'*-- match transaction descriptions.-*'date:PERIODEXPR'*-- match dates within the specified period. PERIODEXPR is a period- expression (with no report interval). Examples: 'date:2016',- 'date:thismonth', 'date:2000/2/1-2/15', 'date:lastweek-'. If the- '--date2' command line flag is present, this matches secondary- dates instead.-*'date2:PERIODEXPR'*-- match secondary dates within the specified period.-*'depth:N'*-- match (or display, depending on command) accounts at or above this- depth-*'note:REGEX'*-- match transaction notes (part of description right of '|', or whole- description when there's no '|')-*'payee:REGEX'*-- match transaction payee/payer names (part of description left of- '|', or whole description when there's no '|')-*'real:, real:0'*-- match real or virtual postings respectively-*'status:, status:!, status:*'*-- match unmarked, pending, or cleared transactions respectively-*'tag:REGEX[=REGEX]'*-- match by tag name, and optionally also by tag value. Note a tag:- query is considered to match a transaction if it matches any of the- postings. Also remember that postings inherit the tags of their- parent transaction.-- The following special search term is used automatically in-hledger-web, only:--*'inacct:ACCTNAME'*-- tells hledger-web to show the transaction register for this- account. Can be filtered further with 'acct' etc.-- Some of these can also be expressed as command-line options (eg-'depth:2' is equivalent to '--depth 2'). Generally you can mix options-and query arguments, and the resulting query will be their intersection-(perhaps excluding the '-p/--period' option).---File: hledger.info, Node: Special characters in arguments and queries, Next: Unicode characters, Prev: Queries, Up: OPTIONS--2.5 Special characters in arguments and queries-===============================================--In shell command lines, option and argument values which contain-"problematic" characters, ie spaces, and also characters significant to-your shell such as '<', '>', '(', ')', '|' and '$', should be escaped by-enclosing them in quotes or by writing backslashes before the-characters. Eg:-- 'hledger register -p 'last year' "accounts receivable-(receivable|payable)" amt:\>100'.--* Menu:--* More escaping::-* Even more escaping::-* Less escaping::---File: hledger.info, Node: More escaping, Next: Even more escaping, Up: Special characters in arguments and queries--2.5.1 More escaping----------------------Characters significant both to the shell and in regular expressions may-need one extra level of escaping. These include parentheses, the pipe-symbol and the dollar sign. Eg, to match the dollar symbol, bash users-should do:-- 'hledger balance cur:'\$''-- or:-- 'hledger balance cur:\\$'---File: hledger.info, Node: Even more escaping, Next: Less escaping, Prev: More escaping, Up: Special characters in arguments and queries--2.5.2 Even more escaping---------------------------When hledger runs an addon executable (eg you type 'hledger ui', hledger-runs 'hledger-ui'), it de-escapes command-line options and arguments-once, so you might need to _triple_-escape. Eg in bash, running the ui-command and matching the dollar sign, it's:-- 'hledger ui cur:'\\$''-- or:-- 'hledger ui cur:\\\\$'-- If you asked why _four_ slashes above, this may help:--unescaped: '$'-escaped: '\$'-double-escaped: '\\$'-triple-escaped: '\\\\$'-- (The number of backslashes in fish shell is left as an exercise for-the reader.)-- You can always avoid the extra escaping for addons by running the-addon directly:-- 'hledger-ui cur:\\$'---File: hledger.info, Node: Less escaping, Prev: Even more escaping, Up: Special characters in arguments and queries--2.5.3 Less escaping----------------------Inside an argument file, or in the search field of hledger-ui or-hledger-web, or at a GHCI prompt, you need one less level of escaping-than at the command line. And backslashes may work better than quotes.-Eg:-- 'ghci> :main balance cur:\$'---File: hledger.info, Node: Unicode characters, Next: Input files, Prev: Special characters in arguments and queries, Up: OPTIONS--2.6 Unicode characters-======================--hledger is expected to handle non-ascii characters correctly:-- * they should be parsed correctly in input files and on the command- line, by all hledger tools (add, iadd, hledger-web's- search/add/edit forms, etc.)-- * they should be displayed correctly by all hledger tools, and- on-screen alignment should be preserved.-- This requires a well-configured environment. Here are some tips:-- * A system locale must be configured, and it must be one that can- decode the characters being used. In bash, you can set a locale- like this: 'export LANG=en_US.UTF-8'. There are some more details- in Troubleshooting. This step is essential - without it, hledger- will quit on encountering a non-ascii character (as with all- GHC-compiled programs).-- * your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)- must support unicode-- * the terminal must be using a font which includes the required- unicode glyphs-- * the terminal should be configured to display wide characters as- double width (for report alignment)-- * 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).---File: hledger.info, Node: Input files, Next: Output destination, Prev: Unicode characters, Up: OPTIONS--2.7 Input files-===============--hledger reads transactions from a data file (and the add command writes-to it). By default this file is '$HOME/.hledger.journal' (or on-Windows, something like 'C:/Users/USER/.hledger.journal'). You can-override this with the '$LEDGER_FILE' environment variable:--$ setenv LEDGER_FILE ~/finance/2016.journal-$ hledger stats-- or with the '-f/--file' option:--$ hledger -f /some/file stats-- The file name '-' (hyphen) means standard input:--$ cat some.journal | hledger -f--- Usually the data file is in hledger's journal format, but it can be-in any of the supported file formats, which currently are:--Reader: Reads: Used for file- extensions:----------------------------------------------------------------------------'journal'hledger journal files and some Ledger '.journal' '.j'- journals, for transactions '.hledger' '.ledger'-'timeclock'timeclock files, for precise time '.timeclock'- logging-'timedot'timedot files, for approximate time '.timedot'- logging-'csv' comma/semicolon/tab/other-separated '.csv' '.ssv' '.tsv'- values, for data import-- hledger detects the format automatically based on the file extensions-shown above. If it can't recognise the file extension, it assumes-'journal' format. So for non-journal files, it's important to use a-recognised file extension, so as to either read successfully or to show-relevant error messages.-- When you can't ensure the right file extension, not to worry: you can-force a specific reader/format by prefixing the file path with the-format and a colon. Eg to read a .dat file as csv:--$ hledger -f csv:/some/csv-file.dat stats-$ echo 'i 2009/13/1 08:00:00' | hledger print -ftimeclock:--- You can specify multiple '-f' options, to read multiple files as one-big journal. There are some limitations with this:-- * directives in one file will not affect the other files- * balance assertions will not see any account balances from previous- files-- If you need either of those things, you can-- * use a single parent file which includes the others- * or concatenate the files into one before reading, eg: 'cat- a.journal b.journal | hledger -f- CMD'.---File: hledger.info, Node: Output destination, Next: Output format, Prev: Input files, Up: OPTIONS--2.8 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:--$ hledger print > foo.txt-- Some commands (print, register, stats, the balance commands) also-provide the '-o/--output-file' option, which does the same thing without-needing the shell. Eg:--$ hledger print -o foo.txt-$ hledger print -o - # write to stdout (the default)---File: hledger.info, Node: Output format, Next: Regular expressions, Prev: Output destination, Up: OPTIONS--2.9 Output format-=================--Some commands (print, register, the balance commands) offer a choice of-output format. In addition to the usual plain text format ('txt'),-there are CSV ('csv'), HTML ('html'), JSON ('json') and SQL ('sql').-This is controlled by the '-O/--output-format' option:--$ hledger print -O csv-- or, by a file extension specified with '-o/--output-file':--$ hledger balancesheet -o foo.html # write HTML to foo.html-- The '-O' option can be used to override the file extension if needed:--$ hledger balancesheet -o foo.txt -O html # write HTML to foo.txt-- Some notes about JSON output:-- * This feature is marked experimental, and not yet much used; you- should expect our JSON to evolve. Real-world feedback is welcome.-- * Our JSON is rather large and verbose, as it is quite a faithful- representation of hledger's internal data types. To understand the- JSON, read the Haskell type definitions, which are mostly in- https://github.com/simonmichael/hledger/blob/master/hledger-lib/Hledger/Data/Types.hs.-- * hledger represents quantities as Decimal values storing up to 255- significant digits, eg for repeating decimals. Such numbers can- arise in practice (from automatically-calculated transaction- prices), and would break most JSON consumers. So in JSON, we show- quantities as simple Numbers with at most 10 decimal places. We- don't limit the number of integer digits, but that part is under- your control. We hope this approach will not cause problems in- practice; if you find otherwise, please let us know. (Cf #1195)-- Notes about SQL output:-- * SQL output is also marked experimental, and much like JSON could- use real-world feedback.-- * SQL output is expected to work with sqlite, MySQL and PostgreSQL-- * SQL output is structured with the expectations that statements will- be executed in the empty database. If you already have tables- created via SQL output of hledger, you would probably want to- either clear tables of existing data (via 'delete' or 'truncate'- SQL statements) or drop tables completely as otherwise your- postings will be duped.---File: hledger.info, Node: Regular expressions, Next: Smart dates, Prev: Output format, Up: OPTIONS--2.10 Regular expressions-========================--hledger uses regular expressions in a number of places:-- * query terms, on the command line and in the hledger-web search- form: 'REGEX', 'desc:REGEX', 'cur:REGEX', 'tag:...=REGEX'- * CSV rules conditional blocks: 'if REGEX ...'- * account alias directives and options: 'alias /REGEX/ =- REPLACEMENT', '--alias /REGEX/=REPLACEMENT'-- hledger's regular expressions come from the regex-tdfa library. If-they're not doing what you expect, it's important to know exactly what-they support:-- 1. they are case insensitive- 2. they are infix matching (they do not need to match the entire thing- being matched)- 3. they are POSIX ERE (extended regular expressions)- 4. they also support GNU word boundaries ('\b', '\B', '\<', '\>')- 5. they do not support backreferences; if you write '\1', it will- match the digit '1'. Except when doing text replacement, eg in- account aliases, where backreferences can be used in the- replacement string to reference capturing groups in the search- regexp.- 6. they do not support mode modifiers ('(?s)'), character classes- ('\w', '\d'), or anything else not mentioned above.-- Some things to note:-- * In the 'alias' directive and '--alias' option, regular expressions- must be enclosed in forward slashes ('/REGEX/'). Elsewhere in- hledger, these are not required.-- * In queries, to match a regular expression metacharacter like '$' as- a literal character, prepend a backslash. Eg to search for amounts- with the dollar sign in hledger-web, write 'cur:\$'.-- * On the command line, some metacharacters like '$' have a special- meaning to the shell and so must be escaped at least once more.- See Special characters.---File: hledger.info, Node: Smart dates, Next: Report start & end date, Prev: Regular expressions, Up: OPTIONS--2.11 Smart dates-================--hledger's user interfaces accept a flexible "smart date" syntax (unlike-dates in the journal file). Smart dates allow some english words, can-be relative to today's date, and can have less-significant date parts-omitted (defaulting to 1).-- Examples:--'2004/10/1', exact date, several separators allowed. Year-'2004-01-01', is 4+ digits, month is 1-12, day is 1-31-'2004.9.1'-'2004' start of year-'2004/10' start of month-'10/1' month and day in current year-'21' day in current month-'october, oct' start of month in current year-'yesterday, today, -1, 0, 1 days from today-tomorrow'-'last/this/next -1, 0, 1 periods from the current period-day/week/month/quarter/year'-'20181201' 8 digit YYYYMMDD with valid year month and- day-'201812' 6 digit YYYYMM with valid year and month-- Counterexamples - malformed digit sequences might give surprising-results:--'201813' 6 digits with an invalid month is parsed as start of- 6-digit year-'20181301' 8 digits with an invalid month is parsed as start of- 8-digit year-'20181232' 8 digits with an invalid day gives an error-'201801012' 9+ digits beginning with a valid YYYYMMDD gives an error---File: hledger.info, Node: Report start & end date, Next: Report intervals, Prev: Smart dates, Up: OPTIONS--2.12 Report start & end date-============================--Most hledger reports show the full span of time represented by the-journal data, by default. So, the effective report start and end dates-will be the earliest and latest transaction or posting dates found in-the journal.-- Often you will want to see a shorter time span, such as the current-month. You can specify a start and/or end date using '-b/--begin',-'-e/--end', '-p/--period' or a 'date:' query (described below). All of-these accept the smart date syntax.-- Some notes:-- * As in Ledger, end dates are exclusive, so you need to write the- date _after_ the last day you want to include.- * As noted in reporting options: among start/end dates specified with- _options_, the last (i.e. right-most) option takes precedence.- * The effective report start and end dates are the intersection of- the start/end dates from options and that from 'date:' queries.- That is, 'date:2019-01 date:2019 -p'2000 to 2030'' yields January- 2019, the smallest common time span.-- Examples:--'-b begin on St. Patrick's day 2016-2016/3/17'-'-e 12/1' end at the start of december 1st of the current year- (11/30 will be the last date included)-'-b all transactions on or after the 1st of the current month-thismonth'-'-p all transactions in the current month-thismonth'-'date:2016/3/17..'the above written as queries instead ('..' can also be- replaced with '-')-'date:..12/1'-'date:thismonth..'-'date:thismonth'---File: hledger.info, Node: Report intervals, Next: Period expressions, Prev: Report start & end date, Up: OPTIONS--2.13 Report intervals-=====================--A report interval can be specified so that commands like register,-balance and activity will divide their reports into multiple subperiods.-The basic intervals can be selected with one of '-D/--daily',-'-W/--weekly', '-M/--monthly', '-Q/--quarterly', or '-Y/--yearly'. More-complex intervals may be specified with a period expression. Report-intervals can not be specified with a query.---File: hledger.info, Node: Period expressions, Next: Depth limiting, Prev: Report intervals, Up: OPTIONS--2.14 Period expressions-=======================--The '-p/--period' option accepts period expressions, a shorthand way of-expressing a start date, end date, and/or report interval all at once.-- Here's a basic period expression specifying the first quarter of-2009. Note, hledger always treats start dates as inclusive and end-dates as exclusive:-- '-p "from 2009/1/1 to 2009/4/1"'-- Keywords like "from" and "to" are optional, and so are the spaces, as-long as you don't run two dates together. "to" can also be written as-".." or "-". These are equivalent to the above:--'-p "2009/1/1 2009/4/1"'-'-p2009/1/1to2009/4/1'-'-p2009/1/1..2009/4/1'-- Dates are smart dates, so if the current year is 2009, the above can-also be written as:--'-p "1/1 4/1"'-'-p "january-apr"'-'-p "this year to 4/1"'-- If you specify only one date, the missing start or end date will be-the earliest or latest transaction in your journal:--'-p "from 2009/1/1"' everything after january 1, 2009-'-p "from 2009/1"' the same-'-p "from 2009"' the same-'-p "to 2009"' everything before january 1, 2009-- A single date with no "from" or "to" defines both the start and end-date like so:--'-p "2009"' the year 2009; equivalent to “2009/1/1 to 2010/1/1”-'-p "2009/1"' the month of jan; equivalent to “2009/1/1 to 2009/2/1”-'-p "2009/1/1"' just that day; equivalent to “2009/1/1 to 2009/1/2”-- Or you can specify a single quarter like so:--'-p "2009Q1"' first quarter of 2009, equivalent to “2009/1/1 to 2009/4/1”-'-p "q4"' fourth quarter of the current year-- The argument of '-p' can also begin with, or be, a report interval-expression. The basic report intervals are 'daily', 'weekly',-'monthly', 'quarterly', or 'yearly', which have the same effect as the-'-D','-W','-M','-Q', or '-Y' flags. Between report interval and-start/end dates (if any), the word 'in' is optional. Examples:--'-p "weekly from 2009/1/1 to 2009/4/1"'-'-p "monthly in 2008"'-'-p "quarterly"'-- Note that 'weekly', 'monthly', 'quarterly' and 'yearly' intervals-will always start on the first day on week, month, quarter or year-accordingly, and will end on the last day of same period, even if-associated period expression specifies different explicit start and end-date.-- For example:--'-p "weekly from starts on 2008/12/29, closest preceding-2009/1/1 to 2009/4/1"' Monday-'-p "monthly in starts on 2018/11/01-2008/11/25"'-'-p "quarterly from starts on 2009/04/01, ends on 2009/06/30,-2009-05-05 to which are first and last days of Q2 2009-2009-06-01"'-'-p "yearly from starts on 2009/01/01, first day of 2009-2009-12-29"'-- The following more complex report intervals are also supported:-'biweekly', 'fortnightly', 'bimonthly', 'every-day|week|month|quarter|year', 'every N-days|weeks|months|quarters|years'.-- All of these will start on the first day of the requested period and-end on the last one, as described above.-- Examples:--'-p "bimonthly from periods will have boundaries on 2008/01/01,-2008"' 2008/03/01, ...-'-p "every 2 weeks"' starts on closest preceding Monday-'-p "every 5 month from periods will have boundaries on 2009/03/01,-2009/03"' 2009/08/01, ...-- If you want intervals that start on arbitrary day of your choosing-and span a week, month or year, you need to use any of the following:-- 'every Nth day of week', 'every <weekday>', 'every Nth day [of-month]', 'every Nth weekday [of month]', 'every MM/DD [of year]', 'every-Nth MMM [of year]', 'every MMM Nth [of year]'.-- Examples:--'-p "every 2nd day of periods will go from Tue to Tue-week"'-'-p "every Tue"' same-'-p "every 15th day"' period boundaries will be on 15th of each- month-'-p "every 2nd period boundaries will be on second Monday of-Monday"' each month-'-p "every 11/05"' yearly periods with boundaries on 5th of Nov-'-p "every 5th Nov"' same-'-p "every Nov 5th"' same-- Show historical balances at end of 15th each month (N is exclusive-end date):-- 'hledger balance -H -p "every 16th day"'-- Group postings from start of wednesday to end of next tuesday (N is-start date and exclusive end date):-- 'hledger register checking -p "every 3rd day of week"'---File: hledger.info, Node: Depth limiting, Next: Pivoting, Prev: Period expressions, Up: OPTIONS--2.15 Depth limiting-===================--With the '--depth N' option (short form: '-N'), commands like account,-balance and register will show only the uppermost accounts in the-account tree, down to level N. Use this when you want a summary with-less detail. This flag has the same effect as a 'depth:' query argument-(so '-2', '--depth=2' or 'depth:2' are equivalent).---File: hledger.info, Node: Pivoting, Next: Valuation, Prev: Depth limiting, Up: OPTIONS--2.16 Pivoting-=============--Normally hledger sums amounts, and organizes them in a hierarchy, based-on account name. The '--pivot FIELD' option causes it to sum and-organize hierarchy based on the value of some other field instead.-FIELD can be: 'code', 'description', 'payee', 'note', or the full name-(case insensitive) of any tag. As with account names, values containing-'colon:separated:parts' will be displayed hierarchically in reports.-- '--pivot' is a general option affecting all reports; you can think of-hledger transforming the journal before any other processing, replacing-every posting's account name with the value of the specified field on-that posting, inheriting it from the transaction or using a blank value-if it's not present.-- An example:--2016/02/16 Member Fee Payment- assets:bank account 2 EUR- income:member fees -2 EUR ; member: John Doe-- Normal balance report showing account names:--$ hledger balance- 2 EUR assets:bank account- -2 EUR income:member fees---------------------- 0-- Pivoted balance report, using member: tag values instead:--$ hledger balance --pivot member- 2 EUR- -2 EUR John Doe---------------------- 0-- One way to show only amounts with a member: value (using a query,-described below):--$ hledger balance --pivot member tag:member=.- -2 EUR John Doe---------------------- -2 EUR-- Another way (the acct: query matches against the pivoted "account-name"):--$ hledger balance --pivot member acct:.- -2 EUR John Doe---------------------- -2 EUR---File: hledger.info, Node: Valuation, Prev: Pivoting, Up: OPTIONS--2.17 Valuation-==============--Instead of reporting amounts in their original commodity, hledger can-convert them to cost/sale amount (using the conversion rate recorded in-the transaction), or to market value (using some market price on a-certain date). This is controlled by the '--value=TYPE[,COMMODITY]'-option, but we also provide the simpler '-B'/'-V'/'-X' flags, and-usually one of those is all you need.--* Menu:--* -B Cost::-* -V Value::-* -X Value in specified commodity::-* Valuation date::-* Market prices::-* --infer-value market prices from transactions::-* Valuation commodity::-* Simple valuation examples::-* --value Flexible valuation::-* More valuation examples::-* Effect of valuation on reports::---File: hledger.info, Node: -B Cost, Next: -V Value, Up: Valuation--2.17.1 -B: Cost------------------The '-B/--cost' flag converts amounts to their cost or sale amount at-transaction time, if they have a transaction price specified.---File: hledger.info, Node: -V Value, Next: -X Value in specified commodity, Prev: -B Cost, Up: Valuation--2.17.2 -V: Value-------------------The '-V/--market' flag converts amounts to market value in their default-_valuation commodity_, using the market prices in effect on the-_valuation date(s)_, if any. More on these in a minute.---File: hledger.info, Node: -X Value in specified commodity, Next: Valuation date, Prev: -V Value, Up: Valuation--2.17.3 -X: Value in specified commodity------------------------------------------The '-X/--exchange=COMM' option is like '-V', except you tell it which-currency you want to convert to, and it tries to convert everything to-that.---File: hledger.info, Node: Valuation date, Next: Market prices, Prev: -X Value in specified commodity, Up: Valuation--2.17.4 Valuation date------------------------Since market prices can change from day to day, market value reports-have a valuation date (or more than one), which determines which market-prices will be used.-- For single period reports, if an explicit report end date is-specified, that will be used as the valuation date; otherwise the-valuation date is "today".-- For multiperiod reports, each column/period is valued on the last day-of the period.---File: hledger.info, Node: Market prices, Next: --infer-value market prices from transactions, Prev: Valuation date, Up: Valuation--2.17.5 Market prices-----------------------_(experimental)_-- 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 :-- 1. A _declared market price_ or _inferred market price_: A's latest- market price in B on or before the valuation date as declared by a- P directive, or (if the '--infer-value' flag is used) inferred from- transaction prices.-- 2. A _reverse market price_: the inverse of a declared or inferred- market price from B to A.-- 3. A _chained market price_: a synthetic price formed by combining the- shortest chain of market prices (any of the above types) leading- from A to B.-- Amounts for which no applicable market price can be found, are not-converted.---File: hledger.info, Node: --infer-value market prices from transactions, Next: Valuation commodity, Prev: Market prices, Up: Valuation--2.17.6 -infer-value: market prices from transactions-------------------------------------------------------_(experimental)_-- 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 transaction prices as additional-market prices (as Ledger does) ? We could produce value reports without-needing P directives at all.-- Adding the '--infer-value' flag to '-V', '-X' or '--value' enables-this. So for example, 'hledger bs -V --infer-value' will get market-prices both from P directives and from transactions.-- 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 Valuation section carefully, and try adding-'--debug' or '--debug=2' to troubleshoot.-- '--infer-value' can infer market prices from:-- * multicommodity transactions with explicit prices ('@'/'@@')-- * multicommodity transactions with implicit prices (no '@', two- commodities, unbalanced). (With these, the order of postings- matters. 'hledger print -x' can be useful for troubleshooting.)-- * but not, currently, from "more correct" multicommodity transactions- (no '@', multiple commodities, balanced).---File: hledger.info, Node: Valuation commodity, Next: Simple valuation examples, Prev: --infer-value market prices from transactions, Up: Valuation--2.17.7 Valuation commodity-----------------------------_(experimental)_-- *When you specify a valuation commodity ('-X COMM' or '--value-TYPE,COMM'):*-hledger will convert all amounts to COMM, wherever it can find a-suitable market price (including by reversing or chaining prices).-- *When you leave the valuation commodity unspecified ('-V' or '--value-TYPE'):*-For each commodity A, hledger picks a default valuation commodity as-follows, in this order of preference:-- 1. The price commodity from the latest P-declared market price for A- on or before valuation date.-- 2. 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.)-- 3. If there are no P directives at all (any commodity or date) and the- '--infer-value' flag is used: the price commodity from the latest- transaction-inferred price for A on or before valuation date.-- This means:-- * If you have P directives, they determine which commodities '-V'- will convert, and to what.-- * If you have no P directives, and use the '--infer-value' flag,- transaction prices determine it.-- Amounts for which no valuation commodity can be found are not-converted.---File: hledger.info, Node: Simple valuation examples, Next: --value Flexible valuation, Prev: Valuation commodity, Up: Valuation--2.17.8 Simple valuation examples-----------------------------------Here are some quick examples of '-V':--; 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-- How many euros do I have ?--$ hledger -f t.j bal -N euros- €100 assets:euros-- What are they worth at end of nov 3 ?--$ hledger -f t.j bal -N euros -V -e 2016/11/4- $110.00 assets:euros-- What are they worth after 2016/12/21 ? (no report end date-specified, defaults to today)--$ hledger -f t.j bal -N euros -V- $103.00 assets:euros---File: hledger.info, Node: --value Flexible valuation, Next: More valuation examples, Prev: Simple valuation examples, Up: Valuation--2.17.9 -value: Flexible valuation------------------------------------'-B', '-V' and '-X' are special cases of the more general '--value'-option:-- --value=TYPE[,COMM] TYPE is cost, then, end, now or YYYY-MM-DD.- COMM is an optional commodity symbol.- Shows amounts converted to:- - cost commodity using transaction prices (then optionally to COMM using market prices at period end(s))- - 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-- The TYPE part selects cost or value and valuation date:--'--value=cost'-- Convert amounts to cost, using the prices recorded in transactions.-'--value=then'-- Convert amounts to their value in the default valuation commodity,- using market prices on each posting's date. This is currently- supported only by the print and register commands.-'--value=end'-- 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's end date); or in multiperiod reports,- market prices on the last day of each subperiod.-'--value=now'-- Convert amounts to their value in the default valuation commodity- using current market prices (as of when report is generated).-'--value=YYYY-MM-DD'-- Convert amounts to their value in the default valuation commodity- using market prices on this date.-- To select a different valuation commodity, add the optional ',COMM'-part: a comma, then the target commodity's symbol. Eg:-*'--value=now,EUR'*. hledger will do its best to convert amounts to-this commodity, deducing market prices as described above.---File: hledger.info, Node: More valuation examples, Next: Effect of valuation on reports, Prev: --value Flexible valuation, Up: Valuation--2.17.10 More valuation examples----------------------------------Here are some examples showing the effect of '--value', as seen with-'print':--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 @ 5 B--2000-02-01- (a) 1 A @ 6 B--2000-03-01- (a) 1 A @ 7 B-- Show the cost of each posting:--$ hledger -f- print --value=cost-2000-01-01- (a) 5 B--2000-02-01- (a) 6 B--2000-03-01- (a) 7 B-- Show the value as of the last day of the report period (2000-02-29):--$ hledger -f- print --value=end date:2000/01-2000/03-2000-01-01- (a) 2 B--2000-02-01- (a) 2 B-- With no report period specified, that shows the value as of the last-day of the journal (2000-03-01):--$ hledger -f- print --value=end-2000-01-01- (a) 3 B--2000-02-01- (a) 3 B--2000-03-01- (a) 3 B-- Show the current value (the 2000-04-01 price is still in effect-today):--$ hledger -f- print --value=now-2000-01-01- (a) 4 B--2000-02-01- (a) 4 B--2000-03-01- (a) 4 B-- Show the value on 2000/01/15:--$ 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-- You may need to explicitly set a commodity's display style, when-reverse prices are used. Eg this output might be surprising:--P 2000-01-01 A 2B--2000-01-01- a 1B- b--$ hledger print -x -X A-2000-01-01- a 0- b 0-- Explanation: because there's no amount or commodity directive-specifying a display style for A, 0.5A gets the default style, which-shows no decimal digits. Because the displayed amount looks like zero,-the commodity symbol and minus sign are not displayed either. Adding a-commodity directive sets a more useful display style for A:--P 2000-01-01 A 2B-commodity 0.00A--2000-01-01- a 1B- b--$ hledger print -X A-2000-01-01- a 0.50A- b -0.50A---File: hledger.info, Node: Effect of valuation on reports, Prev: More valuation examples, Up: Valuation--2.17.11 Effect of valuation on reports-----------------------------------------Here is a reference for how valuation is supposed to affect each part of-hledger's reports (and a glossary). (It's wide, you'll have to scroll-sideways.) It may be useful when troubleshooting. If you find-problems, please report them, ideally with a reproducible example.-Related: #329, #1083.--Report '-B', '-V', '-X' '--value=then' '--value=end' '--value=DATE',-type '--value=cost' '--value=now'---------------------------------------------------------------------------------*print*-posting cost value at value at value at value at-amounts report end posting date report or DATE/today- or today journal end-balance unchanged unchanged unchanged unchanged unchanged-assertions-/-assignments-*register*-starting cost value at not value at value at-balance day before supported day before DATE/today-(with -H) report or report or- journal journal- start start-posting cost value at value at value at value at-amounts report end posting date report or DATE/today-(no report or today journal end-interval)-summary summarised value at sum of value at value at-posting cost period postings in period ends DATE/today-amounts ends interval,-(with valued at-report interval-interval) start-running sum/average sum/average sum/average sum/average sum/average-total/averageof of of displayed of of- displayed displayed values displayed displayed- values values values values-*balance-(bs, bse,-cf, is..)*-balances sums of value at not value at value at-(no report costs report end supported report or DATE/today-interval) or today journal end of sums- of sums of of sums of of- postings postings postings-balances sums of value at not value at value at-(with costs period supported period ends DATE/today-report ends of of sums of of sums-interval) sums of postings of- postings postings-starting sums of sums of not sums of sums of-balances costs of postings supported postings postings-(with postings before before before-report before report report report-interval report start start start-and -H) start-budget like like not like like-amounts balances balances supported balances balances-with--budget-grand sum of sum of not sum of sum of-total (no displayed displayed supported displayed displayed-report values values values values-interval)-row sums/averagessums/averagesnot sums/averages sums/averages-totals/averagesof of supported of of-(with displayed displayed displayed displayed-report values values values values-interval)-column sums of sums of not sums of sums of-totals displayed displayed supported displayed displayed- values values values values-grand sum/average sum/average not sum/average sum/average-total/averageof column of column supported of column of- totals totals totals column- totals-- *Glossary:*--_cost_-- calculated using price(s) recorded in the transaction(s).-_value_-- market value using available market price declarations, or the- unchanged amount if no conversion rate can be found.-_report start_-- the first day of the report period specified with -b or -p or- date:, otherwise today.-_report or journal start_-- the first day of the report period specified with -b or -p or- date:, otherwise the earliest transaction date in the journal,- otherwise today.-_report end_-- the last day of the report period specified with -e or -p or date:,- otherwise today.-_report or journal end_-- the last day of the report period specified with -e or -p or date:,- otherwise the latest transaction date in the journal, otherwise- today.-_report interval_-- a flag (-D/-W/-M/-Q/-Y) or period expression that activates the- report's multi-period mode (whether showing one or many- subperiods).---File: hledger.info, Node: COMMANDS, Next: ENVIRONMENT, Prev: OPTIONS, Up: Top--3 COMMANDS-**********--hledger provides a number of subcommands; 'hledger' with no arguments-shows a list.-- If you install additional 'hledger-*' packages, or if you put-programs or scripts named 'hledger-NAME' in your PATH, these will also-be listed as subcommands.-- Run a subcommand by writing its name as first argument (eg 'hledger-incomestatement'). You can also write one of the standard short aliases-displayed in parentheses in the command list ('hledger b'), or any any-unambiguous prefix of a command name ('hledger inc').-- Here are all the builtin commands in alphabetical order. See also-'hledger' for a more organised command list, and 'hledger CMD -h' for-detailed command help.--* Menu:--* accounts::-* activity::-* add::-* aregister::-* balance::-* balancesheet::-* balancesheetequity::-* cashflow::-* check-dates::-* check-dupes::-* close::-* codes::-* commodities::-* descriptions::-* diff::-* files::-* help::-* import::-* incomestatement::-* notes::-* payees::-* prices::-* print::-* print-unique::-* register::-* register-match::-* rewrite::-* roi::-* stats::-* tags::-* test::-* Add-on commands::---File: hledger.info, Node: accounts, Next: activity, Up: COMMANDS--3.1 accounts-============--accounts, a-Show account names.-- This command lists account names, either declared with account-directives (-declared), posted to (-used), or both (the default). With-query arguments, only matched account names and account names referenced-by matched postings are shown. It shows a flat list by default. With-'--tree', it uses indentation to show the account hierarchy. In flat-mode you can add '--drop N' to omit the first few account name-components. Account names can be depth-clipped with 'depth:N' or-'--depth N' or '-N'.-- Examples:--$ hledger accounts-assets:bank:checking-assets:bank:saving-assets:cash-expenses:food-expenses:supplies-income:gifts-income:salary-liabilities:debts---File: hledger.info, Node: activity, Next: add, Prev: accounts, Up: COMMANDS--3.2 activity-============--activity-Show an ascii barchart of posting counts per interval.-- The activity command displays an ascii histogram showing transaction-counts by day, week, month or other reporting interval (by day is the-default). With query arguments, it counts only matched transactions.-- Examples:--$ hledger activity --quarterly-2008-01-01 **-2008-04-01 *******-2008-07-01 -2008-10-01 **---File: hledger.info, Node: add, Next: aregister, Prev: activity, Up: COMMANDS--3.3 add-=======--add-Prompt for transactions and add them to the journal. Any arguments will-be used as default inputs for the first N prompts.-- Many hledger users edit their journals directly with a text editor,-or generate them from CSV. For more interactive data entry, there is the-'add' command, which prompts interactively on the console for new-transactions, and appends them to the journal file (if there are-multiple '-f FILE' options, the first file is used.) Existing-transactions are not changed. This is the only hledger command that-writes to the journal file.-- To use it, just run 'hledger add' and follow the prompts. You can-add as many transactions as you like; when you are finished, enter '.'-or press control-d or control-c to exit.-- Features:-- * add tries to provide useful defaults, using the most similar (by- description) recent transaction (filtered by the query, if any) as- a template.- * You can also set the initial defaults with command line arguments.- * Readline-style edit keys can be used during data entry.- * The tab key will auto-complete whenever possible - accounts,- descriptions, dates ('yesterday', 'today', 'tomorrow'). If the- input area is empty, it will insert the default value.- * If the journal defines a default commodity, it will be added to any- bare numbers entered.- * A parenthesised transaction code may be entered following a date.- * Comments and tags may be entered following a description or amount.- * If you make a mistake, enter '<' at any prompt to go one step- backward.- * Input prompts are displayed in a different colour when the terminal- supports it.-- Example (see the tutorial for a detailed explanation):--$ hledger add-Adding transactions to journal file /src/hledger/examples/sample.journal-Any command line arguments will be used as defaults.-Use tab key to complete, readline keys to edit, enter to accept defaults.-An optional (CODE) may follow transaction dates.-An optional ; COMMENT may follow descriptions or amounts.-If you make a mistake, enter < at any prompt to go one step backward.-To end a transaction, enter . when prompted.-To quit, enter . at a date prompt or press control-d or control-c.-Date [2015/05/22]: -Description: supermarket-Account 1: expenses:food-Amount 1: $10-Account 2: assets:checking-Amount 2 [$-10.0]: -Account 3 (or . or enter to finish this transaction): .-2015/05/22 supermarket- expenses:food $10- assets:checking $-10.0--Save this transaction to the journal ? [y]: -Saved.-Starting the next transaction (. or ctrl-D/ctrl-C to quit)-Date [2015/05/22]: <CTRL-D> $-- On Microsoft Windows, the add command makes sure that no part of the-file path ends with a period, as that would cause problems (#1056).---File: hledger.info, Node: aregister, Next: balance, Prev: add, Up: COMMANDS--3.4 aregister-=============--aregister, areg-Show transactions affecting a particular account, and the account's-running balance.-- 'aregister' shows the transactions affecting a particular account-(and its subaccounts), from the point of view of that account. Each-line shows:-- * the transaction's (or posting's, see below) date- * the names of the other account(s) involved- * the net change to this account's balance- * the account's historical running balance (including balance from- transactions before the report start date).-- With 'aregister', each line represents a whole transaction - as in-hledger-ui, hledger-web, and your bank statement. By contrast, the-'register' command shows individual postings, across all accounts. You-might prefer 'aregister' for reconciling with real-world asset/liability-accounts, and 'register' for reviewing detailed revenues/expenses.-- An account must be specified as the first argument, which should be-the full account name or an account pattern (regular expression).-aregister will show transactions in this account (the first one matched)-and any of its subaccounts.-- Any additional arguments form a query which will filter the-transactions shown.-- Transactions making a net change of zero are not shown by default;-add the '-E/--empty' flag to show them.--* Menu:--* aregister and custom posting dates::-* Output format::---File: hledger.info, Node: aregister and custom posting dates, Next: , Up: aregister--3.4.1 aregister and custom posting dates-------------------------------------------Transactions whose date is outside the report period can still be shown,-if they have a posting to this account dated inside the report period.-(And in this case it's the posting date that is shown.) This ensures-that 'aregister' can show an accurate historical running balance,-matching the one shown by 'register -H' with the same arguments.-- To filter strictly by transaction date instead, add the '--txn-dates'-flag. If you use this flag and some of your postings have custom dates,-it's probably best to assume the running balance is wrong.--3.4.2 Output format----------------------This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', and 'json'.-- Examples:-- Show all transactions and historical running balance in the first-account whose name contains "checking":--$ hledger areg checking-- Show transactions and historical running balance in all asset-accounts during july:--$ hledger areg assets date:jul---File: hledger.info, Node: balance, Next: balancesheet, Prev: aregister, Up: COMMANDS--3.5 balance-===========--balance, bal, b-Show accounts and their balances.-- The balance command is hledger's most versatile command. Note,-despite the name, it is not always used for showing real-world account-balances; the more accounting-aware balancesheet and incomestatement may-be more convenient for that.-- By default, it displays all accounts, and each account's change in-balance during the entire period of the journal. Balance changes are-calculated by adding up the postings in each account. You can limit the-postings matched, by a query, to see fewer accounts, changes over a-different time period, changes from only cleared transactions, etc.-- If you include an account's complete history of postings in the-report, the balance change is equivalent to the account's current ending-balance. For a real-world account, typically you won't have all-transactions in the journal; instead you'll have all transactions after-a certain date, and an "opening balances" transaction setting the-correct starting balance on that date. Then the balance command will-show real-world account balances. In some cases the -H/-historical flag-is used to ensure this (more below).-- The balance command can produce several styles of report:--* Menu:--* Classic balance report::-* Customising the classic balance report::-* Colour support::-* Flat mode::-* Depth limited balance reports::-* Percentages::-* Multicolumn balance report::-* Budget report::-* Output format::---File: hledger.info, Node: Classic balance report, Next: Customising the classic balance report, Up: balance--3.5.1 Classic balance report-------------------------------This is the original balance report, as found in Ledger. It usually-looks like this:--$ hledger balance- $-1 assets- $1 bank:saving- $-2 cash- $2 expenses- $1 food- $1 supplies- $-2 income- $-1 gifts- $-1 salary- $1 liabilities:debts---------------------- 0-- By default, accounts are displayed hierarchically, with subaccounts-indented below their parent. At each level of the tree, accounts are-sorted by account code if any, then by account name. Or with-'-S/--sort-amount', by their balance amount, largest first.-- "Boring" accounts, which contain a single interesting subaccount and-no balance of their own, are elided into the following line for more-compact output. (Eg above, the "liabilities" account.) Use-'--no-elide' to prevent this.-- Account balances are "inclusive" - they include the balances of any-subaccounts.-- Accounts which have zero balance (and no non-zero subaccounts) are-omitted. Use '-E/--empty' to show them.-- A final total is displayed by default; use '-N/--no-total' to-suppress it, eg:--$ hledger balance -p 2008/6 expenses --no-total- $2 expenses- $1 food- $1 supplies---File: hledger.info, Node: Customising the classic balance report, Next: Colour support, Prev: Classic balance report, Up: balance--3.5.2 Customising the classic balance report-----------------------------------------------You can customise the layout of classic balance reports with '--format-FMT':--$ hledger balance --format "%20(account) %12(total)"- assets $-1- bank:saving $1- cash $-2- expenses $2- food $1- supplies $1- income $-2- gifts $-1- salary $-1- liabilities:debts $1----------------------------------- 0-- The FMT format string (plus a newline) specifies the formatting-applied to each account/balance pair. It may contain any suitable text,-with data fields interpolated like so:-- '%[MIN][.MAX](FIELDNAME)'-- * MIN pads with spaces to at least this width (optional)-- * MAX truncates at this width (optional)-- * FIELDNAME must be enclosed in parentheses, and can be one of:-- * 'depth_spacer' - a number of spaces equal to the account's- depth, or if MIN is specified, MIN * depth spaces.- * 'account' - the account's name- * 'total' - the account's balance/posted total, right justified-- Also, FMT can begin with an optional prefix to control how-multi-commodity amounts are rendered:-- * '%_' - render on multiple lines, bottom-aligned (the default)- * '%^' - render on multiple lines, top-aligned- * '%,' - render on one line, comma-separated-- There are some quirks. Eg in one-line mode, '%(depth_spacer)' has no-effect, instead '%(account)' has indentation built in. Experimentation-may be needed to get pleasing results.-- Some example formats:-- * '%(total)' - the account's total- * '%-20.20(account)' - the account's name, left justified, padded to- 20 characters and clipped at 20 characters- * '%,%-50(account) %25(total)' - account name padded to 50- characters, total padded to 20 characters, with multiple- commodities rendered on one line- * '%20(total) %2(depth_spacer)%-(account)' - the default format for- the single-column balance report---File: hledger.info, Node: Colour support, Next: Flat mode, Prev: Customising the classic balance report, Up: balance--3.5.3 Colour support-----------------------In terminal output, when colour is enabled, the balance command shows-negative amounts in red.---File: hledger.info, Node: Flat mode, Next: Depth limited balance reports, Prev: Colour support, Up: balance--3.5.4 Flat mode------------------To see a flat list instead of the default hierarchical display, use-'--flat'. In this mode, accounts (unless depth-clipped) show their full-names and "exclusive" balance, excluding any subaccount balances. In-this mode, you can also use '--drop N' to omit the first few account-name components.--$ hledger balance -p 2008/6 expenses -N --flat --drop 1- $1 food- $1 supplies---File: hledger.info, Node: Depth limited balance reports, Next: Percentages, Prev: Flat mode, Up: balance--3.5.5 Depth limited balance reports--------------------------------------With '--depth N' or 'depth:N' or just '-N', balance reports show-accounts only to the specified numeric depth. This is very useful to-summarise a complex set of accounts and get an overview.--$ hledger balance -N -1- $-1 assets- $2 expenses- $-2 income- $1 liabilities-- Flat-mode balance reports, which normally show exclusive balances,-show inclusive balances at the depth limit.---File: hledger.info, Node: Percentages, Next: Multicolumn balance report, Prev: Depth limited balance reports, Up: balance--3.5.6 Percentages--------------------With '-%' or '--percent', balance reports show each account's value-expressed as a percentage of the column's total. This is useful to get-an overview of the relative sizes of account balances. For example to-obtain an overview of expenses:--$ hledger balance expenses -%- 100.0 % expenses- 50.0 % food- 50.0 % supplies---------------------- 100.0 %-- Note that '--tree' does not have an effect on '-%'. The percentages-are always relative to the total sum of each column, they are never-relative to the parent account.-- Since the percentages are relative to the columns sum, it is usually-not useful to calculate percentages if the signs of the amounts are-mixed. Although the results are technically correct, they are most-likely useless. Especially in a balance report that sums up to zero (eg-'hledger balance -B') all percentage values will be zero.-- This flag does not work if the report contains any mixed commodity-accounts. If there are mixed commodity accounts in the report be sure-to use '-V' or '-B' to coerce the report into using a single commodity.---File: hledger.info, Node: Multicolumn balance report, Next: Budget report, Prev: Percentages, Up: balance--3.5.7 Multicolumn balance report-----------------------------------Multicolumn or tabular balance reports are a very useful hledger-feature, and usually the preferred style. They share many of the above-features, but they show the report as a table, with columns representing-time periods. This mode is activated by providing a reporting interval.-- There are three types of multicolumn balance report, showing-different information:-- 1. By default: each column shows the sum of postings in that period,- ie the account's change of balance in that period. This is useful- eg for a monthly income statement:-- $ hledger balance --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 -- 2. With '--cumulative': each column shows the ending balance for that- period, accumulating the changes across periods, starting from 0 at- the report start date:-- $ hledger balance --quarterly income expenses -E --cumulative- Ending balances (cumulative) in 2008:- - || 2008/03/31 2008/06/30 2008/09/30 2008/12/31 - ===================++=================================================- expenses:food || 0 $1 $1 $1 - expenses:supplies || 0 $1 $1 $1 - income:gifts || 0 $-1 $-1 $-1 - income:salary || $-1 $-1 $-1 $-1 - -------------------++-------------------------------------------------- || $-1 0 0 0 -- 3. With '--historical/-H': each column shows the actual historical- ending balance for that period, accumulating the changes across- periods, starting from the actual balance at the report start date.- This is useful eg for a multi-period balance sheet, and when you- are showing only the data after a certain start date:-- $ hledger balance ^assets ^liabilities --quarterly --historical --begin 2008/4/1- Ending balances (historical) in 2008/04/01-2008/12/31:- - || 2008/06/30 2008/09/30 2008/12/31 - ======================++=====================================- assets:bank:checking || $1 $1 0 - assets:bank:saving || $1 $1 $1 - assets:cash || $-2 $-2 $-2 - liabilities:debts || 0 0 $1 - ----------------------++-------------------------------------- || 0 0 0 -- Note that '--cumulative' or '--historical/-H' disable-'--row-total/-T', since summing end balances generally does not make-sense.-- Multicolumn balance reports display accounts in flat mode by default;-to see the hierarchy, use '--tree'.-- With a reporting interval (like '--quarterly' above), the report-start/end dates will be adjusted if necessary so that they encompass the-displayed report periods. This is so that the first and last periods-will be "full" and comparable to the others.-- The '-E/--empty' flag does two things in multicolumn balance reports:-first, the report will show all columns within the specified report-period (without -E, leading and trailing columns with all zeroes are not-shown). Second, all accounts which existed at the report start date-will be considered, not just the ones with activity during the report-period (use -E to include low-activity accounts which would otherwise-would be omitted).-- The '-T/--row-total' flag adds an additional column showing the total-for each row.-- The '-A/--average' flag adds a column showing the average value in-each row.-- Here's an example of all three:--$ hledger balance -Q income expenses --tree -ETA-Balance changes in 2008:-- || 2008q1 2008q2 2008q3 2008q4 Total Average -============++===================================================- expenses || 0 $2 0 0 $2 $1 - food || 0 $1 0 0 $1 0 - supplies || 0 $1 0 0 $1 0 - income || $-1 $-1 0 0 $-2 $-1 - gifts || 0 $-1 0 0 $-1 0 - salary || $-1 0 0 0 $-1 0 -------------++---------------------------------------------------- || $-1 $1 0 0 0 0 --(Average is rounded to the dollar here since all journal amounts are)-- The '--transpose' flag can be used to exchange the rows and columns-of a multicolumn report.-- When showing multicommodity amounts, multicolumn balance reports will-elide any amounts which have more than two commodities, since otherwise-columns could get very wide. The '--no-elide' flag disables this.-Hiding totals with the '-N/--no-total' flag can also help reduce the-width of multicommodity reports.-- When the report is still too wide, a good workaround is to pipe it-into 'less -RS' (-R for colour, -S to chop long lines). Eg: 'hledger-bal -D --color=yes | less -RS'.---File: hledger.info, Node: Budget report, Next: , Prev: Multicolumn balance report, Up: balance--3.5.8 Budget report----------------------With '--budget', extra columns are displayed showing budget goals for-each account and period, if any. Budget goals are defined by periodic-transactions. This is very useful for comparing planned and actual-income, expenses, time usage, etc. -budget is most often combined with-a report interval.-- For example, you can take average monthly expenses in the common-expense categories to construct a minimal monthly budget:--;; Budget-~ monthly- income $2000- expenses:food $400- expenses:bus $50- expenses:movies $30- assets:bank:checking--;; Two months worth of expenses-2017-11-01- income $1950- expenses:food $396- expenses:bus $49- expenses:movies $30- expenses:supplies $20- assets:bank:checking--2017-12-01- income $2100- expenses:food $412- expenses:bus $53- expenses:gifts $100- assets:bank:checking-- You can now see a monthly budget report:--$ hledger balance -M --budget-Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec -======================++====================================================- assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - expenses || $495 [ 103% of $480] $565 [ 118% of $480] - expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50] - expenses:food || $396 [ 99% of $400] $412 [ 103% of $400] - expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30] - income || $1950 [ 98% of $2000] $2100 [ 105% of $2000] -----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0] -- This is different from a normal balance report in several ways:-- * Only accounts with budget goals during the report period are shown,- by default.-- * In each column, in square brackets after the actual amount, budget- goal amounts are shown, and the actual/goal percentage. (Note:- budget goals should be in the same commodity as the actual amount.)-- * All parent accounts are always shown, even in flat mode. Eg- assets, assets:bank, and expenses above.-- * Amounts always include all subaccounts, budgeted or unbudgeted,- even in flat mode.-- This means that the numbers displayed will not always add up! Eg-above, the 'expenses' actual amount includes the gifts and supplies-transactions, but the 'expenses:gifts' and 'expenses:supplies' accounts-are not shown, as they have no budget amounts declared.-- This can be confusing. When you need to make things clearer, use the-'-E/--empty' flag, which will reveal all accounts including unbudgeted-ones, giving the full picture. Eg:--$ hledger balance -M --budget --empty-Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec -======================++====================================================- assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - expenses || $495 [ 103% of $480] $565 [ 118% of $480] - expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50] - expenses:food || $396 [ 99% of $400] $412 [ 103% of $400] - expenses:gifts || 0 $100 - expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30] - expenses:supplies || $20 0 - income || $1950 [ 98% of $2000] $2100 [ 105% of $2000] -----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0] -- You can roll over unspent budgets to next period with '--cumulative':--$ hledger balance -M --budget --cumulative-Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec -======================++====================================================- assets || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] - assets:bank || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] - assets:bank:checking || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] - expenses || $495 [ 103% of $480] $1060 [ 110% of $960] - expenses:bus || $49 [ 98% of $50] $102 [ 102% of $100] - expenses:food || $396 [ 99% of $400] $808 [ 101% of $800] - expenses:movies || $30 [ 100% of $30] $30 [ 50% of $60] - income || $1950 [ 98% of $2000] $4050 [ 101% of $4000] -----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0] -- For more examples, see Budgeting and Forecasting.--* Menu:--* Nested budgets::---File: hledger.info, Node: Nested budgets, Up: Budget report--3.5.8.1 Nested budgets-......................--You can add budgets to any account in your account hierarchy. If you-have budgets on both parent account and some of its children, then-budget(s) of the child account(s) would be added to the budget of their-parent, much like account balances behave.-- In the most simple case this means that once you add a budget to any-account, all its parents would have budget as well.-- To illustrate this, consider the following budget:--~ monthly from 2019/01- expenses:personal $1,000.00- expenses:personal:electronics $100.00- liabilities-- With this, monthly budget for electronics is defined to be $100 and-budget for personal expenses is an additional $1000, which implicitly-means that budget for both 'expenses:personal' and 'expenses' is $1100.-- Transactions in 'expenses:personal:electronics' will be counted both-towards its $100 budget and $1100 of 'expenses:personal' , and-transactions in any other subaccount of 'expenses:personal' would be-counted towards only towards the budget of 'expenses:personal'.-- For example, let's consider these transactions:--~ monthly from 2019/01- expenses:personal $1,000.00- expenses:personal:electronics $100.00- liabilities--2019/01/01 Google home hub- expenses:personal:electronics $90.00- liabilities $-90.00--2019/01/02 Phone screen protector- expenses:personal:electronics:upgrades $10.00- liabilities--2019/01/02 Weekly train ticket- expenses:personal:train tickets $153.00- liabilities--2019/01/03 Flowers- expenses:personal $30.00- liabilities-- As you can see, we have transactions in-'expenses:personal:electronics:upgrades' and 'expenses:personal:train-tickets', and since both of these accounts are without explicitly-defined budget, these transactions would be counted towards budgets of-'expenses:personal:electronics' and 'expenses:personal' accordingly:--$ hledger balance --budget -M-Budget performance in 2019/01:-- || Jan -===============================++===============================- expenses || $283.00 [ 26% of $1100.00] - expenses:personal || $283.00 [ 26% of $1100.00] - expenses:personal:electronics || $100.00 [ 100% of $100.00] - liabilities || $-283.00 [ 26% of $-1100.00] --------------------------------++-------------------------------- || 0 [ 0] -- And with '--empty', we can get a better picture of budget allocation-and consumption:--$ hledger balance --budget -M --empty-Budget performance in 2019/01:-- || Jan -========================================++===============================- expenses || $283.00 [ 26% of $1100.00] - expenses:personal || $283.00 [ 26% of $1100.00] - expenses:personal:electronics || $100.00 [ 100% of $100.00] - expenses:personal:electronics:upgrades || $10.00 - expenses:personal:train tickets || $153.00 - liabilities || $-283.00 [ 26% of $-1100.00] -----------------------------------------++-------------------------------- || 0 [ 0] --3.5.9 Output format----------------------This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', (multicolumn-non-budget reports only) 'html', and (experimental) 'json'.---File: hledger.info, Node: balancesheet, Next: balancesheetequity, Prev: balance, Up: COMMANDS--3.6 balancesheet-================--balancesheet, bs-This command displays a balance sheet, showing historical ending-balances of asset and liability accounts. (To see equity as well, use-the balancesheetequity command.) Amounts are shown with normal positive-sign, as in conventional financial statements.-- The asset and liability accounts shown are those accounts declared-with the 'Asset' or 'Cash' or 'Liability' type, or otherwise all-accounts under a top-level 'asset' or 'liability' account (case-insensitive, plurals allowed).-- Example:--$ hledger balancesheet-Balance Sheet--Assets:- $-1 assets- $1 bank:saving- $-2 cash---------------------- $-1--Liabilities:- $1 liabilities:debts---------------------- $1--Total:---------------------- 0-- With a reporting interval, multiple columns will be shown, one for-each report period. As with multicolumn balance reports, you can alter-the report mode with '--change'/'--cumulative'/'--historical'. Normally-balancesheet shows historical ending balances, which is what you need-for a balance sheet; note this means it ignores report begin dates (and-'-T/--row-total', since summing end balances generally does not make-sense). Instead of absolute values percentages can be displayed with-'-%'.-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', 'html', and-(experimental) 'json'.---File: hledger.info, Node: balancesheetequity, Next: cashflow, Prev: balancesheet, Up: COMMANDS--3.7 balancesheetequity-======================--balancesheetequity, bse-This command displays a balance sheet, showing historical ending-balances of asset, liability and equity accounts. Amounts are shown-with normal positive sign, as in conventional financial statements.-- The asset, liability and equity accounts shown are those accounts-declared with the 'Asset', 'Cash', 'Liability' or 'Equity' type, or-otherwise all accounts under a top-level 'asset', 'liability' or-'equity' account (case insensitive, plurals allowed).-- Example:--$ hledger balancesheetequity-Balance Sheet With Equity--Assets:- $-2 assets- $1 bank:saving- $-3 cash---------------------- $-2--Liabilities:- $1 liabilities:debts---------------------- $1--Equity:- $1 equity:owner---------------------- $1--Total:---------------------- 0-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', 'html', and-(experimental) 'json'.---File: hledger.info, Node: cashflow, Next: check-dates, Prev: balancesheetequity, Up: COMMANDS--3.8 cashflow-============--cashflow, cf-This command displays a cashflow statement, showing the inflows and-outflows affecting "cash" (ie, liquid) assets. Amounts are shown with-normal positive sign, as in conventional financial statements.-- The "cash" accounts shown are those accounts declared with the 'Cash'-type, or otherwise all accounts under a top-level 'asset' account (case-insensitive, plural allowed) which do not have 'fixed', 'investment',-'receivable' or 'A/R' in their name.-- Example:--$ hledger cashflow-Cashflow Statement--Cash flows:- $-1 assets- $1 bank:saving- $-2 cash---------------------- $-1--Total:---------------------- $-1-- With a reporting interval, multiple columns will be shown, one for-each report period. Normally cashflow shows changes in assets per-period, though as with multicolumn balance reports you can alter the-report mode with '--change'/'--cumulative'/'--historical'. Instead of-absolute values percentages can be displayed with '-%'.-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', 'html', and-(experimental) 'json'.---File: hledger.info, Node: check-dates, Next: check-dupes, Prev: cashflow, Up: COMMANDS--3.9 check-dates-===============--check-dates-Check that transactions are sorted by increasing date. With -date2,-checks secondary dates instead. With -strict, dates must also be-unique. With a query, only matched transactions' dates are checked.-Reads the default journal file, or another specified with -f.---File: hledger.info, Node: check-dupes, Next: close, Prev: check-dates, Up: COMMANDS--3.10 check-dupes-================--check-dupes-Reports account names having the same leaf but different prefixes. In-other words, two or more leaves that are categorized differently. Reads-the default journal file, or another specified as an argument.-- An example: http://stefanorodighiero.net/software/hledger-dupes.html---File: hledger.info, Node: close, Next: codes, Prev: check-dupes, Up: COMMANDS--3.11 close-==========--close, equity-Prints a "closing balances" transaction and an "opening balances"-transaction that bring account balances to and from zero, respectively.-These can be added to your journal file(s), eg to bring asset/liability-balances forward into a new journal file, or to close out-revenues/expenses to retained earnings at the end of a period.-- You can print just one of these transactions by using the '--close'-or '--open' flag. You can customise their descriptions with the-'--close-desc' and '--open-desc' options.-- One amountless posting to "equity:opening/closing balances" is added-to balance the transactions, by default. You can customise this account-name with '--close-acct' and '--open-acct'; if you specify only one of-these, it will be used for both.-- With '--x/--explicit', the equity posting's amount will be shown.-And if it involves multiple commodities, a posting for each commodity-will be shown, as with the print command.-- With '--interleaved', the equity postings are shown next to the-postings they balance, which makes troubleshooting easier.-- By default, transaction prices in the journal are ignored when-generating the closing/opening transactions. With '--show-costs', this-cost information is preserved ('balance -B' reports will be unchanged-after the transition). Separate postings are generated for each cost in-each commodity. Note this can generate very large journal entries, if-you have many foreign currency or investment transactions.--* Menu:--* close usage::---File: hledger.info, Node: close usage, Up: close--3.11.1 close usage---------------------If you split your journal files by time (eg yearly), you will typically-run this command at the end of the year, and save the closing-transaction as last entry of the old file, and the opening transaction-as the first entry of the new file. This makes the files self-contained, so that correct balances are reported no matter which of them-are loaded. Ie, if you load just one file, the balances are initialised-correctly; or if you load several files, the redundant closing/opening-transactions cancel each other out. (They will show up in print or-register reports; you can exclude them with a query like-'not:desc:'(opening|closing) balances''.)-- If you're running a business, you might also use this command to-"close the books" at the end of an accounting period, transferring-income statement account balances to retained earnings. (You may want-to change the equity account name to something like "equity:retained-earnings".)-- By default, the closing transaction is dated yesterday, the balances-are calculated as of end of yesterday, and the opening transaction is-dated today. To close on some other date, use: 'hledger close -e-OPENINGDATE'. Eg, to close/open on the 2018/2019 boundary, use '-e-2019'. You can also use -p or 'date:PERIOD' (any starting date is-ignored).-- Both transactions will include balance assertions for the-closed/reopened accounts. You probably shouldn't use status or realness-filters (like -C or -R or 'status:') with this command, or the generated-balance assertions will depend on these flags. Likewise, if you run-this command with -auto, the balance assertions will probably always-require -auto.-- Examples:-- Carrying asset/liability balances into a new file for 2019:--$ hledger close -f 2018.journal -e 2019 assets liabilities --open- # (copy/paste the output to the start of your 2019 journal file)-$ hledger close -f 2018.journal -e 2019 assets liabilities --close- # (copy/paste the output to the end of your 2018 journal file)-- Now:--$ hledger bs -f 2019.journal # one file - balances are correct-$ hledger bs -f 2018.journal -f 2019.journal # two files - balances still correct-$ hledger bs -f 2018.journal not:desc:closing # to see year-end balances, must exclude closing txn-- Transactions spanning the closing date can complicate matters,-breaking balance assertions:--2018/12/30 a purchase made in 2018, clearing the following year- expenses:food 5- assets:bank:checking -5 ; [2019/1/2]-- Here's one way to resolve that:--; in 2018.journal:-2018/12/30 a purchase made in 2018, clearing the following year- expenses:food 5- liabilities:pending--; in 2019.journal:-2019/1/2 clearance of last year's pending transactions- liabilities:pending 5 = 0- assets:checking---File: hledger.info, Node: codes, Next: commodities, Prev: close, Up: COMMANDS--3.12 codes-==========--codes-List the codes seen in transactions, in the order parsed.-- This command prints the value of each transaction's 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.-- Transactions aren't required to have a code, and missing or empty-codes will not be shown by default. With the '-E'/'--empty' flag, they-will be printed as blank lines.-- You can add a query to select a subset of transactions.-- Examples:--1/1 (123)- (a) 1--1/1 ()- (a) 1--1/1- (a) 1--1/1 (126)- (a) 1--$ hledger codes-123-124-126--$ hledger codes -E-123-124---126---File: hledger.info, Node: commodities, Next: descriptions, Prev: codes, Up: COMMANDS--3.13 commodities-================--commodities-List all commodity/currency symbols used or declared in the journal.---File: hledger.info, Node: descriptions, Next: diff, Prev: commodities, Up: COMMANDS--3.14 descriptions-=================--descriptions-List the unique descriptions that appear in transactions.-- This command lists the unique descriptions that appear in-transactions, in alphabetic order. You can add a query to select a-subset of transactions.-- Example:--$ hledger descriptions-Store Name-Gas Station | Petrol-Person A---File: hledger.info, Node: diff, Next: files, Prev: descriptions, Up: COMMANDS--3.15 diff-=========--diff-Compares a particular account's transactions in two input files. It-shows any transactions to this account which are in one file but not in-the other.-- More precisely, for each posting affecting this account in either-file, it looks for a corresponding posting in the other file which posts-the same amount to the same account (ignoring date, description, etc.)-Since postings not transactions are compared, this also works when-multiple bank transactions have been combined into a single journal-entry.-- This is useful eg if you have downloaded an account's 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.-- Examples:--$ 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:---File: hledger.info, Node: files, Next: help, Prev: diff, Up: COMMANDS--3.16 files-==========--files-List all files included in the journal. With a REGEX argument, only-file names matching the regular expression (case sensitive) are shown.---File: hledger.info, Node: help, Next: import, Prev: files, Up: COMMANDS--3.17 help-=========--help-Show any of the hledger manuals.-- The 'help' command displays any of the main hledger manuals, in one-of several ways. Run it with no argument to list the manuals, or-provide a full or partial manual name to select one.-- hledger manuals are available in several formats. hledger help will-use the first of these display methods that it finds: info, man, $PAGER,-less, stdout (or when non-interactive, just stdout). You can force a-particular viewer with the '--info', '--man', '--pager', '--cat' flags.-- Examples:--$ hledger help-Please choose a manual by typing "hledger help MANUAL" (a substring is ok).-Manuals: hledger hledger-ui hledger-web journal csv timeclock timedot--$ hledger help h --man--hledger(1) hledger User Manuals hledger(1)--NAME- hledger - a command-line accounting tool--SYNOPSIS- hledger [-f FILE] COMMAND [OPTIONS] [ARGS]- hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]- hledger--DESCRIPTION- hledger is a cross-platform program for tracking money, time, or any-...---File: hledger.info, Node: import, Next: incomestatement, Prev: help, Up: COMMANDS--3.18 import-===========--import-Read new transactions added to each FILE since last run, and add them to-the main journal file. Or with -dry-run, just print the transactions-that would be added. Or with -catchup, just mark all of the FILEs'-transactions as imported, without actually importing any.-- The input files are specified as arguments - no need to write -f-before each one. So eg to add new transactions from all CSV files to-the main journal, it's just: 'hledger import *.csv'-- New transactions are detected in the same way as print -new: by-assuming transactions are always added to the input files in increasing-date order, and by saving '.latest.FILE' state files.-- The -dry-run output is in journal format, so you can filter it, eg to-see only uncategorised transactions:--$ hledger import --dry ... | hledger -f- print unknown --ignore-assertions--* Menu:--* Importing balance assignments::---File: hledger.info, Node: Importing balance assignments, Up: import--3.18.1 Importing balance assignments---------------------------------------Entries added by import will have their posting amounts made explicit-(like 'hledger print -x'). This means that any balance assignments in-imported files must be evaluated; but, imported files don't get to see-the main file's account balances. As a result, importing entries with-balance assignments (eg from an institution that provides only balances-and not posting amounts) will probably generate incorrect posting-amounts. To avoid this problem, use print instead of import:--$ hledger print IMPORTFILE [--new] >> $LEDGER_FILE-- (If you think import should leave amounts implicit like print does,-please test it and send a pull request.)---File: hledger.info, Node: incomestatement, Next: notes, Prev: import, Up: COMMANDS--3.19 incomestatement-====================--incomestatement, is-- This command displays an income statement, showing revenues and-expenses during one or more periods. Amounts are shown with normal-positive sign, as in conventional financial statements.-- The revenue and expense accounts shown are those accounts declared-with the 'Revenue' or 'Expense' type, or otherwise all accounts under a-top-level 'revenue' or 'income' or 'expense' account (case insensitive,-plurals allowed).-- Example:--$ hledger incomestatement-Income Statement--Revenues:- $-2 income- $-1 gifts- $-1 salary---------------------- $-2--Expenses:- $2 expenses- $1 food- $1 supplies---------------------- $2--Total:---------------------- 0-- With a reporting interval, multiple columns will be shown, one for-each report period. Normally incomestatement shows revenues/expenses-per period, though as with multicolumn balance reports you can alter the-report mode with '--change'/'--cumulative'/'--historical'. Instead of-absolute values percentages can be displayed with '-%'.-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', 'html', and-(experimental) 'json'.---File: hledger.info, Node: notes, Next: payees, Prev: incomestatement, Up: COMMANDS--3.20 notes-==========--notes-List the unique notes that appear in transactions.-- 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).-- Example:--$ hledger notes-Petrol-Snacks---File: hledger.info, Node: payees, Next: prices, Prev: notes, Up: COMMANDS--3.21 payees-===========--payees-List the unique payee/payer names that appear in transactions.-- This command lists the unique payee/payer names that appear in-transactions, in alphabetic order. You can add a query to select a-subset of transactions. The payee/payer is the part of the transaction-description before a | character (or if there is no |, the whole-description).-- Example:--$ hledger payees-Store Name-Gas Station-Person A---File: hledger.info, Node: prices, Next: print, Prev: payees, Up: COMMANDS--3.22 prices-===========--prices-Print market price directives from the journal. With -costs, also print-synthetic market prices based on transaction prices. With--inverted-costs, also print inverse prices based on transaction prices.-Prices (and postings providing prices) can be filtered by a query.-Price amounts are always displayed with their full precision.---File: hledger.info, Node: print, Next: print-unique, Prev: prices, Up: COMMANDS--3.23 print-==========--print, txns, p-Show transaction journal entries, sorted by date.-- The print command displays full journal entries (transactions) from-the journal file in date order, tidily formatted. With -date2,-transactions are sorted by secondary date instead.-- print's output is always a valid hledger journal.-It preserves all transaction information, but it does not preserve-directives or inter-transaction comments--$ hledger print-2008/01/01 income- assets:bank:checking $1- income:salary $-1--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--2008/12/31 * pay off- liabilities:debts $1- assets:bank:checking $-1-- Normally, the journal entry's explicit or implicit amount style is-preserved. For example, when an amount is omitted in the journal, it-will not appear in the output. Similarly, when a transaction price is-implied but not written, it will not appear in the output. You can use-the '-x'/'--explicit' flag to make all amounts and transaction prices-explicit, which can be useful for troubleshooting or for making your-journal more readable and robust against data entry errors. '-x' is-also implied by using any of '-B','-V','-X','--value'.-- Note, '-x'/'--explicit' will cause postings with a multi-commodity-amount (these can arise when a multi-commodity transaction has an-implicit amount) to be split into multiple single-commodity postings,-keeping the output parseable.-- With '-B'/'--cost', amounts with transaction prices are converted to-cost using that price. This can be used for troubleshooting.-- With '-m'/'--match' and a STR argument, print will show at most one-transaction: the one one whose description is most similar to STR, and-is most recent. STR should contain at least two characters. If there-is no similar-enough match, no transaction will be shown.-- With '--new', for each FILE being read, hledger reads (and writes) a-special state file ('.latest.FILE' in the same directory), containing-the latest transaction date(s) that were seen last time FILE was read.-When this file is found, only transactions with newer dates (and new-transactions on the latest date) are printed. This is useful for-ignoring already-seen entries in import data, such as downloaded CSV-files. Eg:--$ hledger -f bank1.csv print --new-(shows transactions added since last print --new on this file)-- This assumes that transactions added to FILE always have same or-increasing dates, and that transactions on the same day do not get-reordered. See also the import command.-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', and-(experimental) 'json' and 'sql'.-- Here's an example of print's CSV output:--$ hledger print -Ocsv-"txnidx","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","posting-status","posting-comment"-"1","2008/01/01","","","","income","","assets:bank:checking","1","$","","1","",""-"1","2008/01/01","","","","income","","income:salary","-1","$","1","","",""-"2","2008/06/01","","","","gift","","assets:bank:checking","1","$","","1","",""-"2","2008/06/01","","","","gift","","income:gifts","-1","$","1","","",""-"3","2008/06/02","","","","save","","assets:bank:saving","1","$","","1","",""-"3","2008/06/02","","","","save","","assets:bank:checking","-1","$","1","","",""-"4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","","1","",""-"4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","","1","",""-"4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","2","","",""-"5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","","1","",""-"5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","1","","",""-- * There is one CSV record per posting, with the parent transaction's- fields repeated.- * The "txnidx" (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.)- * The amount is separated into "commodity" (the symbol) and "amount"- (numeric quantity) fields.- * The numeric amount is repeated in either the "credit" or "debit"- column, for convenience. (Those names are not accurate in the- accounting sense; it just puts negative amounts under credit and- zero or greater amounts under debit.)---File: hledger.info, Node: print-unique, Next: register, Prev: print, Up: COMMANDS--3.24 print-unique-=================--print-unique-Print transactions which do not reuse an already-seen description.-- Example:--$ cat unique.journal-1/1 test- (acct:one) 1-2/2 test- (acct:two) 2-$ LEDGER_FILE=unique.journal hledger print-unique-(-f option not supported)-2015/01/01 test- (acct:one) 1---File: hledger.info, Node: register, Next: register-match, Prev: print-unique, Up: COMMANDS--3.25 register-=============--register, reg, r-Show postings and their running total.-- The register command displays matched postings, across all accounts,-in date order, with their running total or running historical balance.-(See also the 'aregister' command, which shows matched transactions in a-specific account.)-- register normally shows line per posting, but note that-multi-commodity amounts will occupy multiple lines (one line per-commodity).-- It is typically used with a query selecting a particular account, to-see that account's activity:--$ 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-- With -date2, it shows and sorts by secondary date instead.-- The '--historical'/'-H' 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:--$ 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-- The '--depth' option limits the amount of sub-account detail-displayed.-- The '--average'/'-A' 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 '--empty' (see-below). It is affected by '--historical'. It works best when showing-just one account and one commodity.-- The '--related'/'-r' flag shows the _other_ postings in the-transactions of the postings which would normally be shown.-- The '--invert' flag negates all amounts. For example, it can be used-on an income account where amounts are normally displayed as negative-numbers. It's also useful to show postings on the checking account-together with the related account:--$ hledger register --related --invert assets:checking-- With a reporting interval, register shows summary postings, one per-interval, aggregating the postings to each account:--$ hledger register --monthly income-2008/01 income:salary $-1 $-1-2008/06 income:gifts $-1 $-2-- Periods with no activity, and summary postings with a zero amount,-are not shown by default; use the '--empty'/'-E' flag to see them:--$ 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-- Often, you'll want to see just one line per interval. The '--depth'-option helps with this, causing subaccounts to be aggregated:--$ hledger register --monthly assets --depth 1h-2008/01 assets $1 $1-2008/06 assets $-1 0-2008/12 assets $-1 $-1-- 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.--* Menu:--* Custom register output::---File: hledger.info, Node: Custom register output, Up: register--3.25.1 Custom register output--------------------------------register uses the full terminal width by default, except on windows.-You can override this by setting the 'COLUMNS' environment variable (not-a bash shell variable) or by using the '--width'/'-w' option.-- 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's argument, comma-separated:-'--width W,D' . Here's a diagram (won't display correctly in -help):--<--------------------------------- width (W) ---------------------------------->-date (10) description (D) account (W-41-D) amount (12) balance (12)-DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA-- and some examples:--$ hledger reg # use terminal width (or 80 on windows)-$ hledger reg -w 100 # use width 100-$ COLUMNS=100 hledger reg # set with one-time environment variable-$ export COLUMNS=100; hledger reg # set till session end (or window resize)-$ hledger reg -w 100,40 # set overall width 100, description width 40-$ hledger reg -w $COLUMNS,40 # use terminal width, & description width 40-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', and-(experimental) 'json'.---File: hledger.info, Node: register-match, Next: rewrite, Prev: register, Up: COMMANDS--3.26 register-match-===================--register-match-Print the one posting whose transaction description is closest to DESC,-in the style of the register command. If there are multiple equally-good matches, it shows the most recent. Query options (options, not-arguments) can be used to restrict the search space. Helps-ledger-autosync detect already-seen transactions when importing.---File: hledger.info, Node: rewrite, Next: roi, Prev: register-match, Up: COMMANDS--3.27 rewrite-============--rewrite-Print all transactions, rewriting the postings of matched transactions.-For now the only rewrite available is adding new postings, like print--auto.-- 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's first posting amount.-- Examples:--$ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'-$ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'-$ hledger-rewrite.hs -f rewrites.hledger-- rewrites.hledger may consist of entries like:--= ^income 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-- Note the single quotes to protect the dollar sign from bash, and the-two spaces between account and amount.-- More:--$ hledger rewrite -- [QUERY] --add-posting "ACCT AMTEXPR" ...-$ hledger rewrite -- ^income --add-posting '(liabilities:tax) *.33'-$ hledger rewrite -- expenses:gifts --add-posting '(budget:gifts) *-1"'-$ hledger rewrite -- ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'-- Argument for '--add-posting' option is a usual posting of transaction-with an exception for amount specification. More precisely, you can use-''*'' (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's-commodity.--* Menu:--* Re-write rules in a file::---File: hledger.info, Node: Re-write rules in a file, Up: rewrite--3.27.1 Re-write rules in a file----------------------------------During the run this tool will execute so called "Automated Transactions"-found in any journal it process. I.e instead of specifying this-operations in command line you can put them in a journal file.--$ rewrite-rules.journal-- Make contents look like this:--= ^income- (liabilities:tax) *.33--= expenses:gifts- budget:gifts *-1- assets:budget *1-- Note that ''='' (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.--$ hledger rewrite -- -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal-- This is something similar to the commands pipeline:--$ hledger rewrite -- -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \- | hledger rewrite -- -f - expenses:gifts --add-posting 'budget:gifts *-1' \- --add-posting 'assets:budget *1' \- > rewritten-tidy-output.journal-- It is important to understand that relative order of such entries in-journal is important. You can re-use result of previously added-postings.--* Menu:--* Diff output format::-* rewrite vs print --auto::---File: hledger.info, Node: Diff output format, Next: rewrite vs print --auto, Up: Re-write rules in a file--3.27.1.1 Diff output format-...........................--To use this tool for batch modification of your journal files you may-find useful output in form of unified diff.--$ hledger rewrite -- --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'-- Output might look like:----- /tmp/examples/sample.journal-+++ /tmp/examples/sample.journal-@@ -18,3 +18,4 @@- 2008/01/01 income-- assets:bank:checking $1-+ assets:bank:checking $1- income:salary-+ (liabilities:tax) 0-@@ -22,3 +23,4 @@- 2008/06/01 gift-- assets:bank:checking $1-+ assets:bank:checking $1- income:gifts-+ (liabilities:tax) 0-- If you'll pass this through 'patch' tool you'll 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 '--file' options and 'include' directives inside of these-files.-- Be careful. Whole transaction being re-formatted in a style of-output from 'hledger print'.-- See also:-- https://github.com/simonmichael/hledger/issues/99---File: hledger.info, Node: rewrite vs print --auto, Prev: Diff output format, Up: Re-write rules in a file--3.27.1.2 rewrite vs. print -auto-................................--This command predates print -auto, and currently does much the same-thing, but with these differences:-- * with multiple files, rewrite lets rules in any file affect all- other files. print -auto uses standard directive scoping; rules- affect only child files.-- * rewrite's query limits which transactions can be rewritten; all are- printed. print -auto's query limits which transactions are- printed.-- * rewrite applies rules specified on command line or in the journal.- print -auto applies rules specified in the journal.---File: hledger.info, Node: roi, Next: stats, Prev: rewrite, Up: COMMANDS--3.28 roi-========--roi-Shows the time-weighted (TWR) and money-weighted (IRR) rate of return on-your investments.-- This command assumes that you have account(s) that hold nothing but-your investments and whenever you record current appraisal/valuation of-these investments you offset unrealized profit and loss into account(s)-that, again, hold nothing but unrealized profit and loss.-- Any transactions affecting balance of investment account(s) and not-originating from unrealized profit and loss account(s) are assumed to be-your investments or withdrawals.-- At a minimum, you need to supply a query (which could be just an-account name) to select your investments with '--inv', and another query-to identify your profit and loss transactions with '--pnl'.-- It will compute and display the internalized rate of return (IRR) and-time-weighted rate of return (TWR) for your investments for the time-period requested. Both rates of return are annualized before display,-regardless of the length of reporting interval.---File: hledger.info, Node: stats, Next: tags, Prev: roi, Up: COMMANDS--3.29 stats-==========--stats-Show some journal statistics.-- The stats command displays summary information for the whole journal,-or a matched part of it. With a reporting interval, it shows a report-for each report period.-- Example:--$ hledger stats-Main journal file : /src/hledger/examples/sample.journal-Included journal files : -Transactions span : 2008-01-01 to 2009-01-01 (366 days)-Last transaction : 2008-12-31 (2333 days ago)-Transactions : 5 (0.0 per day)-Transactions last 30 days: 0 (0.0 per day)-Transactions last 7 days : 0 (0.0 per day)-Payees/descriptions : 5-Accounts : 8 (depth 3)-Commodities : 1 ($)-Market prices : 12 ($)-- This command also supports output destination and output format-selection.---File: hledger.info, Node: tags, Next: test, Prev: stats, Up: COMMANDS--3.30 tags-=========--tags-List the unique tag names used in the journal. With a TAGREGEX-argument, only tag names matching the regular expression (case-insensitive) are shown. With QUERY arguments, only transactions-matching the query are considered.-- With the -values flag, the tags' unique values are listed instead.-- With -parsed flag, all tags or values are shown in the order they are-parsed from the input data, including duplicates.-- With -E/-empty, any blank/empty values will also be shown, otherwise-they are omitted.---File: hledger.info, Node: test, Next: Add-on commands, Prev: tags, Up: COMMANDS--3.31 test-=========--test-Run built-in unit tests.-- This command runs the unit tests built in to hledger and hledger-lib,-printing the results on stdout. If any test fails, the exit code will-be non-zero.-- This is mainly used by hledger developers, but you can also use it to-sanity-check the installed hledger executable on your platform. All-tests are expected to pass - if you ever see a failure, please report as-a bug!-- This command also accepts tasty test runner options, written after a-- (double hyphen). Eg to run only the tests in Hledger.Data.Amount,-with ANSI colour codes disabled:--$ hledger test -- -pData.Amount --color=never-- For help on these, see https://github.com/feuerbach/tasty#options-('-- --help' currently doesn't show them).---File: hledger.info, Node: Add-on commands, Prev: test, Up: COMMANDS--3.32 Add-on commands-====================--hledger also searches for external add-on commands, and will include-these in the commands list. These are programs or scripts in your PATH-whose name starts with 'hledger-' and ends with a recognised file-extension (currently: no extension, 'bat','com','exe',-'hs','lhs','pl','py','rb','rkt','sh').-- Add-ons can be invoked like any hledger command, but there are a few-things to be aware of. Eg if the 'hledger-web' add-on is installed,-- * 'hledger -h web' shows hledger's help, while 'hledger web -h' shows- hledger-web's help.-- * Flags specific to the add-on must have a preceding '--' to hide- them from hledger. So 'hledger web --serve --port 9000' will be- rejected; you must use 'hledger web -- --serve --port 9000'.-- * You can always run add-ons directly if preferred: 'hledger-web- --serve --port 9000'.-- Add-ons are a relatively easy way to add local features or experiment-with new ideas. They can be written in any language, but haskell-scripts have a big advantage: they can use the same hledger (and-haskell) library functions that built-in commands do, for command-line-options, journal parsing, reporting, etc.-- Two important add-ons are the hledger-ui and hledger-web user-interfaces. These are maintained and released along with hledger:--* Menu:--* ui::-* web::-* iadd::-* interest::---File: hledger.info, Node: ui, Next: web, Up: Add-on commands--3.32.1 ui------------hledger-ui provides an efficient terminal interface.---File: hledger.info, Node: web, Next: iadd, Prev: ui, Up: Add-on commands--3.32.2 web-------------hledger-web provides a simple web interface.-- Third party add-ons, maintained separately from hledger, include:---File: hledger.info, Node: iadd, Next: interest, Prev: web, Up: Add-on commands--3.32.3 iadd--------------hledger-iadd is a more interactive, terminal UI replacement for the add-command.---File: hledger.info, Node: interest, Prev: iadd, Up: Add-on commands--3.32.4 interest------------------hledger-interest generates interest transactions for an account-according to various schemes.-- A few more experimental or old add-ons can be found in hledger's bin/-directory. These are typically prototypes and not guaranteed to work.---File: hledger.info, Node: ENVIRONMENT, Next: FILES, Prev: COMMANDS, Up: Top--4 ENVIRONMENT-*************--*LEDGER_FILE* The journal file path when not specified with '-f'.-Default: '~/.hledger.journal' (on windows, perhaps-'C:/Users/USER/.hledger.journal').-- A typical value is '~/DIR/YYYY.journal', where DIR is a-version-controlled finance directory and YYYY is the current year. Or-'~/DIR/current.journal', where current.journal is a symbolic link to-YYYY.journal.-- On Mac computers, you can set this and other environment variables in-a more thorough way that also affects applications started from the GUI-(say, an Emacs dock icon). Eg on MacOS Catalina I have a-'~/.MacOSX/environment.plist' file containing--{- "LEDGER_FILE" : "~/finance/current.journal"-}-- To see the effect you may need to 'killall Dock', or reboot.-- *COLUMNS* The screen width used by the register command. Default:-the full terminal width.-- *NO_COLOR* If this variable exists with any value, hledger will not-use ANSI color codes in terminal output. This overrides the--color/-colour option.---File: hledger.info, Node: FILES, Next: LIMITATIONS, Prev: ENVIRONMENT, Up: Top--5 FILES-*******--Reads data from one or more files in hledger journal, timeclock,-timedot, or CSV format specified with '-f', or '$LEDGER_FILE', or-'$HOME/.hledger.journal' (on windows, perhaps-'C:/Users/USER/.hledger.journal').---File: hledger.info, Node: LIMITATIONS, Next: TROUBLESHOOTING, Prev: FILES, Up: Top--6 LIMITATIONS-*************--The need to precede addon command options with '--' when invoked from-hledger is awkward.-- When input data contains non-ascii characters, a suitable system-locale must be configured (or there will be an unhelpful error). Eg on-POSIX, set LANG to something other than C.-- In a Microsoft Windows CMD window, non-ascii characters and colours-are not supported.-- On Windows, non-ascii characters may not display correctly when-running a hledger built in CMD in MSYS/CYGWIN, or vice-versa.-- In a Cygwin/MSYS/Mintty window, the tab key is not supported in-hledger add.-- Not all of Ledger's journal file syntax is supported. See file-format differences.-- On large data files, hledger is slower and uses more memory than-Ledger.---File: hledger.info, Node: TROUBLESHOOTING, Prev: LIMITATIONS, Up: Top--7 TROUBLESHOOTING-*****************--Here are some issues you might encounter when you run hledger (and-remember you can also seek help from the IRC channel, mail list or bug-tracker):-- *Successfully installed, but "No command 'hledger' found"*-stack and cabal install binaries into a special directory, which should-be added to your PATH environment variable. Eg on unix-like systems,-that is ~/.local/bin and ~/.cabal/bin respectively.-- *I set a custom LEDGER_FILE, but hledger is still using the default-file*-'LEDGER_FILE' should be a real environment variable, not just a shell-variable. The command 'env | grep LEDGER_FILE' should show it. You may-need to use 'export'. Here's an explanation.-- *Getting errors like "Illegal byte sequence" or "Invalid or-incomplete multibyte or wide character" or "commitAndReleaseBuffer:-invalid argument (invalid character)"*-Programs compiled with GHC (hledger, haskell build tools, etc.) need to-have a UTF-8-aware locale configured in the environment, otherwise they-will fail with these kinds of errors when they encounter non-ascii-characters.-- To fix it, set the LANG environment variable to some locale which-supports UTF-8. The locale you choose must be installed on your system.-- Here's an example of setting LANG temporarily, on Ubuntu GNU/Linux:--$ file my.journal-my.journal: UTF-8 Unicode text # the file is UTF8-encoded-$ echo $LANG-C # LANG is set to the default locale, which does not support UTF8-$ locale -a # which locales are installed ?-C-en_US.utf8 # here's a UTF8-aware one we can use-POSIX-$ LANG=en_US.utf8 hledger -f my.journal print # ensure it is used for this command-- If available, 'C.UTF-8' will also work. If your preferred locale-isn't listed by 'locale -a', you might need to install it. Eg on-Ubuntu/Debian:--$ apt-get install language-pack-fr-$ locale -a-C-en_US.utf8-fr_BE.utf8-fr_CA.utf8-fr_CH.utf8-fr_FR.utf8-fr_LU.utf8-POSIX-$ LANG=fr_FR.utf8 hledger -f my.journal print-- Here's how you could set it permanently, if you use a bash shell:--$ echo "export LANG=en_US.utf8" >>~/.bash_profile-$ bash --login-- Exact spelling and capitalisation may be important. Note the-difference on MacOS ('UTF-8', not 'utf8'). Some platforms (eg ubuntu)-allow variant spellings, but others (eg macos) require it to be exact:--$ locale -a | grep -iE en_us.*utf-en_US.UTF-8-$ LANG=en_US.UTF-8 hledger -f my.journal print---Tag Table:-Node: Top68-Node: COMMON TASKS2321-Ref: #common-tasks2433-Node: Getting help2840-Ref: #getting-help2972-Node: Constructing command lines3525-Ref: #constructing-command-lines3717-Node: Starting a journal file4414-Ref: #starting-a-journal-file4612-Node: Setting opening balances5800-Ref: #setting-opening-balances5996-Node: Recording transactions9137-Ref: #recording-transactions9317-Node: Reconciling9873-Ref: #reconciling10016-Node: Reporting12273-Ref: #reporting12413-Node: Migrating to a new file16412-Ref: #migrating-to-a-new-file16560-Node: OPTIONS16859-Ref: #options16966-Node: General options17336-Ref: #general-options17461-Node: Command options20767-Ref: #command-options20918-Node: Command arguments21316-Ref: #command-arguments21463-Node: Queries22343-Ref: #queries22498-Node: Special characters in arguments and queries26460-Ref: #special-characters-in-arguments-and-queries26688-Node: More escaping27139-Ref: #more-escaping27301-Node: Even more escaping27597-Ref: #even-more-escaping27791-Node: Less escaping28462-Ref: #less-escaping28624-Node: Unicode characters28869-Ref: #unicode-characters29051-Node: Input files30463-Ref: #input-files30606-Node: Output destination32905-Ref: #output-destination33057-Node: Output format33482-Ref: #output-format33632-Node: Regular expressions35799-Ref: #regular-expressions35956-Node: Smart dates37692-Ref: #smart-dates37843-Node: Report start & end date39204-Ref: #report-start-end-date39376-Node: Report intervals40873-Ref: #report-intervals41038-Node: Period expressions41428-Ref: #period-expressions41588-Node: Depth limiting45920-Ref: #depth-limiting46064-Node: Pivoting46396-Ref: #pivoting46519-Node: Valuation48195-Ref: #valuation48297-Node: -B Cost48986-Ref: #b-cost49090-Node: -V Value49223-Ref: #v-value49369-Node: -X Value in specified commodity49564-Ref: #x-value-in-specified-commodity49763-Node: Valuation date49912-Ref: #valuation-date50080-Node: Market prices50490-Ref: #market-prices50670-Node: --infer-value market prices from transactions51447-Ref: #infer-value-market-prices-from-transactions51696-Node: Valuation commodity52978-Ref: #valuation-commodity53187-Node: Simple valuation examples54413-Ref: #simple-valuation-examples54615-Node: --value Flexible valuation55274-Ref: #value-flexible-valuation55482-Node: More valuation examples57429-Ref: #more-valuation-examples57638-Node: Effect of valuation on reports59643-Ref: #effect-of-valuation-on-reports59831-Node: COMMANDS65352-Ref: #commands65460-Node: accounts66568-Ref: #accounts66666-Node: activity67365-Ref: #activity67475-Node: add67858-Ref: #add67959-Node: aregister70752-Ref: #aregister70864-Node: aregister and custom posting dates72237-Ref: #aregister-and-custom-posting-dates72410-Ref: #output-format-173003-Node: balance73408-Ref: #balance73525-Node: Classic balance report74983-Ref: #classic-balance-report75156-Node: Customising the classic balance report76540-Ref: #customising-the-classic-balance-report76768-Node: Colour support78844-Ref: #colour-support79011-Node: Flat mode79107-Ref: #flat-mode79255-Node: Depth limited balance reports79668-Ref: #depth-limited-balance-reports79853-Node: Percentages80309-Ref: #percentages80475-Node: Multicolumn balance report81612-Ref: #multicolumn-balance-report81792-Node: Budget report87389-Ref: #budget-report87532-Node: Nested budgets92798-Ref: #nested-budgets92910-Ref: #output-format-296391-Node: balancesheet96588-Ref: #balancesheet96724-Node: balancesheetequity98236-Ref: #balancesheetequity98385-Node: cashflow99461-Ref: #cashflow99589-Node: check-dates100805-Ref: #check-dates100932-Node: check-dupes101211-Ref: #check-dupes101337-Node: close101630-Ref: #close101738-Node: close usage103260-Ref: #close-usage103353-Node: codes106166-Ref: #codes106274-Node: commodities106986-Ref: #commodities107113-Node: descriptions107195-Ref: #descriptions107323-Node: diff107627-Ref: #diff107733-Node: files108780-Ref: #files108880-Node: help109027-Ref: #help109127-Node: import110208-Ref: #import110322-Node: Importing balance assignments111215-Ref: #importing-balance-assignments111363-Node: incomestatement112012-Ref: #incomestatement112145-Node: notes113490-Ref: #notes113603-Node: payees113971-Ref: #payees114077-Node: prices114497-Ref: #prices114603-Node: print114944-Ref: #print115054-Node: print-unique119850-Ref: #print-unique119976-Node: register120261-Ref: #register120388-Node: Custom register output124837-Ref: #custom-register-output124966-Node: register-match126303-Ref: #register-match126437-Node: rewrite126788-Ref: #rewrite126903-Node: Re-write rules in a file128758-Ref: #re-write-rules-in-a-file128892-Node: Diff output format130102-Ref: #diff-output-format130271-Node: rewrite vs print --auto131363-Ref: #rewrite-vs.-print---auto131542-Node: roi132098-Ref: #roi132196-Node: stats133208-Ref: #stats133307-Node: tags134095-Ref: #tags134193-Node: test134712-Ref: #test134820-Node: Add-on commands135567-Ref: #add-on-commands135684-Node: ui137027-Ref: #ui137115-Node: web137169-Ref: #web137272-Node: iadd137388-Ref: #iadd137499-Node: interest137581-Ref: #interest137688-Node: ENVIRONMENT137928-Ref: #environment138040-Node: FILES139025-Ref: #files-1139128-Node: LIMITATIONS139341-Ref: #limitations139460-Node: TROUBLESHOOTING140202-Ref: #troubleshooting140315+hledger(1) hledger 1.20+***********************++hledger - a command-line accounting tool++ 'hledger [-f FILE] COMMAND [OPTIONS] [ARGS]'+'hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]'+'hledger'++ hledger is a reliable, 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).++ This is hledger's command-line interface (there are also terminal and+web interfaces). Its basic function is to read a plain text file+describing financial transactions (in accounting terms, a general+journal) and print useful reports on standard output, or export them as+CSV. hledger can also read some other file formats such as CSV files,+translating them to journal format. Additionally, hledger lists other+hledger-* executables found in the user's $PATH and can invoke them as+subcommands.++ hledger reads data from one or more files in hledger journal,+timeclock, timedot, or CSV format specified with '-f', or+'$LEDGER_FILE', or '$HOME/.hledger.journal' (on windows, perhaps+'C:/Users/USER/.hledger.journal'). If using '$LEDGER_FILE', note this+must be a real environment variable, not a shell variable. You can+specify standard input with '-f-'.++ Transactions are dated movements of money between two (or more) named+accounts, and are recorded with journal entries like this:++2015/10/16 bought food+ expenses:food $10+ assets:cash++ For more about this format, see hledger_journal(5).++ Most users use a text editor to edit the journal, usually with an+editor mode such as ledger-mode for added convenience. hledger's+interactive add command is another way to record new transactions.+hledger never changes existing transactions.++ To get started, you can either save some entries like the above in+'~/.hledger.journal', or run 'hledger add' and follow the prompts. Then+try some commands like 'hledger print' or 'hledger balance'. Run+'hledger' with no arguments for a list of commands.++* Menu:++* COMMON TASKS::+* OPTIONS::+* COMMANDS::+* ENVIRONMENT::+* FILES::+* LIMITATIONS::+* TROUBLESHOOTING::+++File: hledger.info, Node: COMMON TASKS, Next: OPTIONS, Prev: Top, Up: Top++1 COMMON TASKS+**************++Here are some quick examples of how to do some basic tasks with hledger.+For more details, see the reference section below, the+hledger_journal(5) manual, or the more extensive docs at+https://hledger.org.++* Menu:++* Getting help::+* Constructing command lines::+* Starting a journal file::+* Setting opening balances::+* Recording transactions::+* Reconciling::+* Reporting::+* Migrating to a new file::+++File: hledger.info, Node: Getting help, Next: Constructing command lines, Up: COMMON TASKS++1.1 Getting help+================++$ hledger # show available commands+$ hledger --help # show common options+$ hledger CMD --help # show common and command options, and command help+$ hledger help # show available manuals/topics+$ hledger help hledger # show hledger manual as info/man/text (auto-chosen)+$ hledger help journal --man # show the journal manual as a man page+$ hledger help --help # show more detailed help for the help command++ Find more docs, chat, mail list, reddit, issue tracker:+https://hledger.org#help-feedback+++File: hledger.info, Node: Constructing command lines, Next: Starting a journal file, Prev: Getting help, Up: COMMON TASKS++1.2 Constructing command lines+==============================++hledger has an extensive and powerful command line interface. We strive+to keep it simple and ergonomic, but you may run into one of the+confusing real world details described in OPTIONS, below. If that+happens, here are some tips that may help:++ * command-specific options must go after the command (it's fine to+ put all options there) ('hledger CMD OPTS ARGS')+ * running add-on executables directly simplifies command line parsing+ ('hledger-ui OPTS ARGS')+ * enclose "problematic" args in single quotes+ * if needed, also add a backslash to hide regular expression+ metacharacters from the shell+ * to see how a misbehaving command is being parsed, add '--debug=2'.+++File: hledger.info, Node: Starting a journal file, Next: Setting opening balances, Prev: Constructing command lines, Up: COMMON TASKS++1.3 Starting a journal file+===========================++hledger looks for your accounting data in a journal file,+'$HOME/.hledger.journal' by default:++$ hledger stats+The hledger journal file "/Users/simon/.hledger.journal" was not found.+Please create it first, eg with "hledger add" or a text editor.+Or, specify an existing journal file with -f or LEDGER_FILE.++ You can override this by setting the 'LEDGER_FILE' environment+variable. It's a good practice to keep this important file under+version control, and to start a new file each year. So you could do+something like this:++$ mkdir ~/finance+$ cd ~/finance+$ git init+Initialized empty Git repository in /Users/simon/finance/.git/+$ touch 2020.journal+$ echo "export LEDGER_FILE=$HOME/finance/2020.journal" >> ~/.bashrc+$ source ~/.bashrc+$ hledger stats+Main file : /Users/simon/finance/2020.journal+Included files : +Transactions span : to (0 days)+Last transaction : none+Transactions : 0 (0.0 per day)+Transactions last 30 days: 0 (0.0 per day)+Transactions last 7 days : 0 (0.0 per day)+Payees/descriptions : 0+Accounts : 0 (depth 0)+Commodities : 0 ()+Market prices : 0 ()+++File: hledger.info, Node: Setting opening balances, Next: Recording transactions, Prev: Starting a journal file, Up: COMMON TASKS++1.4 Setting opening balances+============================++Pick a starting date for which you can look up the balances of some+real-world assets (bank accounts, wallet..) and liabilities (credit+cards..).++ To avoid a lot of data entry, you may want to start with just one or+two accounts, like your checking account or cash wallet; and pick a+recent starting date, like today or the start of the week. You can+always come back later and add more accounts and older transactions, eg+going back to january 1st.++ Add an opening balances transaction to the journal, declaring the+balances on this date. Here are two ways to do it:++ * The first way: open the journal in any text editor and save an+ entry like this:++ 2020-01-01 * opening balances+ assets:bank:checking $1000 = $1000+ assets:bank:savings $2000 = $2000+ assets:cash $100 = $100+ liabilities:creditcard $-50 = $-50+ equity:opening/closing balances++ These are start-of-day balances, ie whatever was in the account at+ the end of the previous day.++ The * after the date is an optional status flag. Here it means+ "cleared & confirmed".++ The currency symbols are optional, but usually a good idea as+ you'll be dealing with multiple currencies sooner or later.++ The = amounts are optional balance assertions, providing extra+ error checking.++ * The second way: run 'hledger add' and follow the prompts to record+ a similar transaction:++ $ hledger add+ Adding transactions to journal file /Users/simon/finance/2020.journal+ Any command line arguments will be used as defaults.+ Use tab key to complete, readline keys to edit, enter to accept defaults.+ An optional (CODE) may follow transaction dates.+ An optional ; COMMENT may follow descriptions or amounts.+ If you make a mistake, enter < at any prompt to go one step backward.+ To end a transaction, enter . when prompted.+ To quit, enter . at a date prompt or press control-d or control-c.+ Date [2020-02-07]: 2020-01-01+ Description: * opening balances+ Account 1: assets:bank:checking+ Amount 1: $1000+ Account 2: assets:bank:savings+ Amount 2 [$-1000]: $2000+ Account 3: assets:cash+ Amount 3 [$-3000]: $100+ Account 4: liabilities:creditcard+ Amount 4 [$-3100]: $-50+ Account 5: equity:opening/closing balances+ Amount 5 [$-3050]: + Account 6 (or . or enter to finish this transaction): .+ 2020-01-01 * opening balances+ assets:bank:checking $1000+ assets:bank:savings $2000+ assets:cash $100+ liabilities:creditcard $-50+ equity:opening/closing balances $-3050+ + Save this transaction to the journal ? [y]: + Saved.+ Starting the next transaction (. or ctrl-D/ctrl-C to quit)+ Date [2020-01-01]: .++ If you're using version control, this could be a good time to commit+the journal. Eg:++$ git commit -m 'initial balances' 2020.journal+++File: hledger.info, Node: Recording transactions, Next: Reconciling, Prev: Setting opening balances, Up: COMMON TASKS++1.5 Recording transactions+==========================++As you spend or receive money, you can record these transactions using+one of the methods above (text editor, hledger add) or by using the+hledger-iadd or hledger-web add-ons, or by using the import command to+convert CSV data downloaded from your bank.++ Here are some simple transactions, see the hledger_journal(5) manual+and hledger.org for more ideas:++2020/1/10 * gift received+ assets:cash $20+ income:gifts++2020.1.12 * farmers market+ expenses:food $13+ assets:cash++2020-01-15 paycheck+ income:salary+ assets:bank:checking $1000+++File: hledger.info, Node: Reconciling, Next: Reporting, Prev: Recording transactions, Up: COMMON TASKS++1.6 Reconciling+===============++Periodically you should reconcile - compare your hledger-reported+balances against external sources of truth, like bank statements or your+bank's 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.++ A typical workflow:++ 1. Reconcile cash. Count what's in your wallet. Compare with what+ hledger reports ('hledger bal cash'). 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+ ('hledger reg cash'). If you can't find the error, add an+ adjustment transaction. Eg if you have $105 after the above, and+ can't explain the missing $2, it could be:++ 2020-01-16 * adjust cash+ assets:cash $-2 = $105+ expenses:misc++ 2. Reconcile checking. Log in to your bank's website. Compare+ today's (cleared) balance with hledger's cleared balance ('hledger+ bal checking -C'). 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 'hledger reg checking -C'. This will be+ easier if you generally record transaction dates quite similar to+ your bank's clearing dates.++ 3. Repeat for other asset/liability accounts.++ Tip: instead of the register command, use hledger-ui to see a+live-updating register while you edit the journal: 'hledger-ui --watch+--register checking -C'++ After reconciling, it could be a good time to mark the reconciled+transactions' status as "cleared and confirmed", if you want to track+that, by adding the '*' marker. Eg in the paycheck transaction above,+insert '*' between '2020-01-15' and 'paycheck'++ If you're using version control, this can be another good time to+commit:++$ git commit -m 'txns' 2020.journal+++File: hledger.info, Node: Reporting, Next: Migrating to a new file, Prev: Reconciling, Up: COMMON TASKS++1.7 Reporting+=============++Here are some basic reports.++ Show all transactions:++$ hledger print+2020-01-01 * opening balances+ assets:bank:checking $1000+ assets:bank:savings $2000+ assets:cash $100+ liabilities:creditcard $-50+ equity:opening/closing balances $-3050++2020-01-10 * gift received+ assets:cash $20+ income:gifts++2020-01-12 * farmers market+ expenses:food $13+ assets:cash++2020-01-15 * paycheck+ income:salary+ assets:bank:checking $1000++2020-01-16 * adjust cash+ assets:cash $-2 = $105+ expenses:misc++ Show account names, and their hierarchy:++$ hledger accounts --tree+assets+ bank+ checking+ savings+ cash+equity+ opening/closing balances+expenses+ food+ misc+income+ gifts+ salary+liabilities+ creditcard++ Show all account totals:++$ hledger balance+ $4105 assets+ $4000 bank+ $2000 checking+ $2000 savings+ $105 cash+ $-3050 equity:opening/closing balances+ $15 expenses+ $13 food+ $2 misc+ $-1020 income+ $-20 gifts+ $-1000 salary+ $-50 liabilities:creditcard+--------------------+ 0++ Show only asset and liability balances, as a flat list, limited to+depth 2:++$ hledger bal assets liabilities --flat -2+ $4000 assets:bank+ $105 assets:cash+ $-50 liabilities:creditcard+--------------------+ $4055++ Show the same thing without negative numbers, formatted as a simple+balance sheet:++$ hledger bs --flat -2+Balance Sheet 2020-01-16++ || 2020-01-16 +========================++============+ Assets || +------------------------++------------+ assets:bank || $4000 + assets:cash || $105 +------------------------++------------+ || $4105 +========================++============+ Liabilities || +------------------------++------------+ liabilities:creditcard || $50 +------------------------++------------+ || $50 +========================++============+ Net: || $4055 ++ The final total is your "net worth" on the end date. (Or use 'bse'+for a full balance sheet with equity.)++ Show income and expense totals, formatted as an income statement:++hledger is +Income Statement 2020-01-01-2020-01-16++ || 2020-01-01-2020-01-16 +===============++=======================+ Revenues || +---------------++-----------------------+ income:gifts || $20 + income:salary || $1000 +---------------++-----------------------+ || $1020 +===============++=======================+ Expenses || +---------------++-----------------------+ expenses:food || $13 + expenses:misc || $2 +---------------++-----------------------+ || $15 +===============++=======================+ Net: || $1005 ++ The final total is your net income during this period.++ Show transactions affecting your wallet, with running total:++$ hledger register cash+2020-01-01 opening balances assets:cash $100 $100+2020-01-10 gift received assets:cash $20 $120+2020-01-12 farmers market assets:cash $-13 $107+2020-01-16 adjust cash assets:cash $-2 $105++ Show weekly posting counts as a bar chart:++$ hledger activity -W+2019-12-30 *****+2020-01-06 ****+2020-01-13 ****+++File: hledger.info, Node: Migrating to a new file, Prev: Reporting, Up: COMMON TASKS++1.8 Migrating to a new file+===========================++At the end of the year, you may want to continue your journal in a new+file, so that old transactions don't slow down or clutter your reports,+and to help ensure the integrity of your accounting history. See the+close command.++ If using version control, don't forget to 'git add' the new file.+++File: hledger.info, Node: OPTIONS, Next: COMMANDS, Prev: COMMON TASKS, Up: Top++2 OPTIONS+*********++* Menu:++* General options::+* Command options::+* Command arguments::+* Queries::+* Special characters in arguments and queries::+* Unicode characters::+* Input files::+* Strict mode::+* Output destination::+* Output format::+* Regular expressions::+* Smart dates::+* Report start & end date::+* Report intervals::+* Period expressions::+* Depth limiting::+* Pivoting::+* Valuation::+++File: hledger.info, Node: General options, Next: Command options, Up: OPTIONS++2.1 General options+===================++To see general usage help, including general options which are supported+by most hledger commands, run 'hledger -h'.++ General help options:++'-h --help'++ show general usage (or after COMMAND, command usage)+'--version'++ show version+'--debug[=N]'++ show debug output (levels 1-9, default: 1)++ General input options:++'-f FILE --file=FILE'++ use a different input file. For stdin, use - (default:+ '$LEDGER_FILE' or '$HOME/.hledger.journal')+'--rules-file=RULESFILE'++ Conversion rules file to use when reading CSV (default: FILE.rules)+'--separator=CHAR'++ Field separator to expect when reading CSV (default: ',')+'--alias=OLD=NEW'++ rename accounts named OLD to NEW+'--anon'++ anonymize accounts and payees+'--pivot FIELDNAME'++ use some other field or tag for the account name+'-I --ignore-assertions'++ disable balance assertion checks (note: does not disable balance+ assignments)+'-s --strict'++ do extra error checking (check that all posted accounts are+ declared)++ General reporting options:++'-b --begin=DATE'++ include postings/txns on or after this date+'-e --end=DATE'++ include postings/txns before this date+'-D --daily'++ multiperiod/multicolumn report by day+'-W --weekly'++ multiperiod/multicolumn report by week+'-M --monthly'++ multiperiod/multicolumn report by month+'-Q --quarterly'++ multiperiod/multicolumn report by quarter+'-Y --yearly'++ multiperiod/multicolumn report by year+'-p --period=PERIODEXP'++ set start date, end date, and/or reporting interval all at once+ using period expressions syntax+'--date2'++ match the secondary date instead (see command help for other+ effects)+'-U --unmarked'++ include only unmarked postings/txns (can combine with -P or -C)+'-P --pending'++ include only pending postings/txns+'-C --cleared'++ include only cleared postings/txns+'-R --real'++ include only non-virtual postings+'-NUM --depth=NUM'++ hide/aggregate accounts or postings more than NUM levels deep+'-E --empty'++ show items with zero amount, normally hidden (and vice-versa in+ hledger-ui/hledger-web)+'-B --cost'++ convert amounts to their cost/selling amount at transaction time+'-V --market'++ convert amounts to their market value in default valuation+ commodities+'-X --exchange=COMM'++ convert amounts to their market value in commodity COMM+'--value'++ convert amounts to cost or market value, more flexibly than+ -B/-V/-X+'--infer-value'++ with -V/-X/-value, also infer market prices from transactions+'--auto'++ apply automated posting rules to modify transactions.+'--forecast'++ generate future transactions from periodic transaction rules, for+ the next 6 months or till report end date. In hledger-ui, also+ make ordinary future transactions visible.+'--color=WHEN (or --colour=WHEN)'++ Should color-supporting commands use ANSI color codes in text+ output. 'auto' (default): whenever stdout seems to be a+ color-supporting terminal. 'always' or 'yes': always, useful eg+ when piping output into 'less -R'. 'never' or 'no': never. A+ NO_COLOR environment variable overrides this.++ When a reporting option appears more than once in the command line,+the last one takes precedence.++ Some reporting options can also be written as query arguments.+++File: hledger.info, Node: Command options, Next: Command arguments, Prev: General options, Up: OPTIONS++2.2 Command options+===================++To see options for a particular command, including command-specific+options, run: 'hledger COMMAND -h'.++ Command-specific options must be written after the command name, eg:+'hledger print -x'.++ Additionally, if the command is an addon, you may need to put its+options after a double-hyphen, eg: 'hledger ui -- --watch'. Or, you can+run the addon executable directly: 'hledger-ui --watch'.+++File: hledger.info, Node: Command arguments, Next: Queries, Prev: Command options, Up: OPTIONS++2.3 Command arguments+=====================++Most hledger commands accept arguments after the command name, which are+often a query, filtering the data in some way.++ You can save a set of command line options/arguments in a file, and+then reuse them by writing '@FILENAME' as a command line argument. Eg:+'hledger bal @foo.args'. (To prevent this, eg if you have an argument+that begins with a literal '@', precede it with '--', eg: 'hledger bal+-- @ARG').++ Inside the argument file, each line should contain just one option or+argument. Avoid the use of spaces, except inside quotes (or you'll see+a confusing error). Between a flag and its argument, use = (or+nothing). Bad:++assets depth:2+-X USD++ Good:++assets+depth:2+-X=USD++ For special characters (see below), use one less level of quoting+than you would at the command prompt. Bad:++-X"$"++ Good:++-X$++ See also: Save frequently used options.+++File: hledger.info, Node: Queries, Next: Special characters in arguments and queries, Prev: Command arguments, Up: OPTIONS++2.4 Queries+===========++One of hledger's strengths is being able to quickly report on precise+subsets of your data. Most commands accept an optional query+expression, written as arguments after the command name, to filter the+data by date, account name or other criteria. The syntax is similar to+a web search: one or more space-separated search terms, quotes to+enclose whitespace, prefixes to match specific fields, a not: prefix to+negate the match.++ We do not yet support arbitrary boolean combinations of search terms;+instead most commands show transactions/postings/accounts which match+(or negatively match):++ * any of the description terms AND+ * any of the account terms AND+ * any of the status terms AND+ * all the other terms.++ The print command instead shows transactions which:++ * match any of the description terms AND+ * have any postings matching any of the positive account terms AND+ * have no postings matching any of the negative account terms AND+ * match all the other terms.++ The following kinds of search terms can be used. Remember these can+also be prefixed with *'not:'*, eg to exclude a particular subaccount.++*'REGEX', 'acct:REGEX'*++ match account names by this regular expression. (With no prefix,+ 'acct:' is assumed.) same as above++*'amt:N, amt:<N, amt:<=N, amt:>N, amt:>=N'*++ match postings with a single-commodity amount that is equal to,+ less than, or greater than N. (Multi-commodity amounts are not+ tested, and will always match.) 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.+*'code:REGEX'*++ match by transaction code (eg check number)+*'cur:REGEX'*++ match postings or transactions including any amounts whose+ currency/commodity symbol is fully matched by REGEX. (For a partial+ match, use '.*REGEX.*'). Note, to match characters which are+ regex-significant, like the dollar sign ('$'), you need to prepend+ '\'. And when using the command line you need to add one more+ level of quoting to hide it from the shell, so eg do: 'hledger+ print cur:'\$'' or 'hledger print cur:\\$'.+*'desc:REGEX'*++ match transaction descriptions.+*'date:PERIODEXPR'*++ match dates within the specified period. PERIODEXPR is a period+ expression (with no report interval). Examples: 'date:2016',+ 'date:thismonth', 'date:2000/2/1-2/15', 'date:lastweek-'. If the+ '--date2' command line flag is present, this matches secondary+ dates instead.+*'date2:PERIODEXPR'*++ match secondary dates within the specified period.+*'depth:N'*++ match (or display, depending on command) accounts at or above this+ depth+*'note:REGEX'*++ match transaction notes (part of description right of '|', or whole+ description when there's no '|')+*'payee:REGEX'*++ match transaction payee/payer names (part of description left of+ '|', or whole description when there's no '|')+*'real:, real:0'*++ match real or virtual postings respectively+*'status:, status:!, status:*'*++ match unmarked, pending, or cleared transactions respectively+*'tag:REGEX[=REGEX]'*++ match by tag name, and optionally also by tag value. Note a tag:+ query is considered to match a transaction if it matches any of the+ postings. Also remember that postings inherit the tags of their+ parent transaction.++ The following special search term is used automatically in+hledger-web, only:++*'inacct:ACCTNAME'*++ tells hledger-web to show the transaction register for this+ account. Can be filtered further with 'acct' etc.++ Some of these can also be expressed as command-line options (eg+'depth:2' is equivalent to '--depth 2'). Generally you can mix options+and query arguments, and the resulting query will be their intersection+(perhaps excluding the '-p/--period' option).+++File: hledger.info, Node: Special characters in arguments and queries, Next: Unicode characters, Prev: Queries, Up: OPTIONS++2.5 Special characters in arguments and queries+===============================================++In shell command lines, option and argument values which contain+"problematic" characters, ie spaces, and also characters significant to+your shell such as '<', '>', '(', ')', '|' and '$', should be escaped by+enclosing them in quotes or by writing backslashes before the+characters. Eg:++ 'hledger register -p 'last year' "accounts receivable+(receivable|payable)" amt:\>100'.++* Menu:++* More escaping::+* Even more escaping::+* Less escaping::+++File: hledger.info, Node: More escaping, Next: Even more escaping, Up: Special characters in arguments and queries++2.5.1 More escaping+-------------------++Characters significant both to the shell and in regular expressions may+need one extra level of escaping. These include parentheses, the pipe+symbol and the dollar sign. Eg, to match the dollar symbol, bash users+should do:++ 'hledger balance cur:'\$''++ or:++ 'hledger balance cur:\\$'+++File: hledger.info, Node: Even more escaping, Next: Less escaping, Prev: More escaping, Up: Special characters in arguments and queries++2.5.2 Even more escaping+------------------------++When hledger runs an addon executable (eg you type 'hledger ui', hledger+runs 'hledger-ui'), it de-escapes command-line options and arguments+once, so you might need to _triple_-escape. Eg in bash, running the ui+command and matching the dollar sign, it's:++ 'hledger ui cur:'\\$''++ or:++ 'hledger ui cur:\\\\$'++ If you asked why _four_ slashes above, this may help:++unescaped: '$'+escaped: '\$'+double-escaped: '\\$'+triple-escaped: '\\\\$'++ (The number of backslashes in fish shell is left as an exercise for+the reader.)++ You can always avoid the extra escaping for addons by running the+addon directly:++ 'hledger-ui cur:\\$'+++File: hledger.info, Node: Less escaping, Prev: Even more escaping, Up: Special characters in arguments and queries++2.5.3 Less escaping+-------------------++Inside an argument file, or in the search field of hledger-ui or+hledger-web, or at a GHCI prompt, you need one less level of escaping+than at the command line. And backslashes may work better than quotes.+Eg:++ 'ghci> :main balance cur:\$'+++File: hledger.info, Node: Unicode characters, Next: Input files, Prev: Special characters in arguments and queries, Up: OPTIONS++2.6 Unicode characters+======================++hledger is expected to handle non-ascii characters correctly:++ * they should be parsed correctly in input files and on the command+ line, by all hledger tools (add, iadd, hledger-web's+ search/add/edit forms, etc.)++ * they should be displayed correctly by all hledger tools, and+ on-screen alignment should be preserved.++ This requires a well-configured environment. Here are some tips:++ * A system locale must be configured, and it must be one that can+ decode the characters being used. In bash, you can set a locale+ like this: 'export LANG=en_US.UTF-8'. There are some more details+ in Troubleshooting. This step is essential - without it, hledger+ will quit on encountering a non-ascii character (as with all+ GHC-compiled programs).++ * your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)+ must support unicode++ * the terminal must be using a font which includes the required+ unicode glyphs++ * the terminal should be configured to display wide characters as+ double width (for report alignment)++ * 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).+++File: hledger.info, Node: Input files, Next: Strict mode, Prev: Unicode characters, Up: OPTIONS++2.7 Input files+===============++hledger reads transactions from a data file (and the add command writes+to it). By default this file is '$HOME/.hledger.journal' (or on+Windows, something like 'C:/Users/USER/.hledger.journal'). You can+override this with the '$LEDGER_FILE' environment variable:++$ setenv LEDGER_FILE ~/finance/2016.journal+$ hledger stats++ or with the '-f/--file' option:++$ hledger -f /some/file stats++ The file name '-' (hyphen) means standard input:++$ cat some.journal | hledger -f-++ Usually the data file is in hledger's journal format, but it can be+in any of the supported file formats, which currently are:++Reader: Reads: Used for file+ extensions:+--------------------------------------------------------------------------+'journal'hledger journal files and some Ledger '.journal' '.j'+ journals, for transactions '.hledger' '.ledger'+'timeclock'timeclock files, for precise time '.timeclock'+ logging+'timedot'timedot files, for approximate time '.timedot'+ logging+'csv' comma/semicolon/tab/other-separated '.csv' '.ssv' '.tsv'+ values, for data import++ hledger detects the format automatically based on the file extensions+shown above. If it can't recognise the file extension, it assumes+'journal' format. So for non-journal files, it's important to use a+recognised file extension, so as to either read successfully or to show+relevant error messages.++ When you can't ensure the right file extension, not to worry: you can+force a specific reader/format by prefixing the file path with the+format and a colon. Eg to read a .dat file as csv:++$ hledger -f csv:/some/csv-file.dat stats+$ echo 'i 2009/13/1 08:00:00' | hledger print -ftimeclock:-++ You can specify multiple '-f' options, to read multiple files as one+big journal. There are some limitations with this:++ * directives in one file will not affect the other files+ * balance assertions will not see any account balances from previous+ files++ If you need either of those things, you can++ * use a single parent file which includes the others+ * or concatenate the files into one before reading, eg: 'cat+ a.journal b.journal | hledger -f- CMD'.+++File: hledger.info, Node: Strict mode, Next: Output destination, Prev: Input files, Up: OPTIONS++2.8 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:++ * Are the input files parseable, with valid syntax ?+ * Are all transactions balanced ?+ * Do all balance assertions pass ?++ With the '-s'/'--strict' flag, additional checks are performed:++ * Are all accounts posted to, declared with an 'account' directive ?+ (Account error checking)+ * Are all commodities declared with a 'commodity' directive ?+ (Commodity error checking)++ See also: https://hledger.org/checking-for-errors.html++ _experimental._+++File: hledger.info, Node: Output destination, Next: Output format, Prev: Strict mode, Up: OPTIONS++2.9 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:++$ hledger print > foo.txt++ Some commands (print, register, stats, the balance commands) also+provide the '-o/--output-file' option, which does the same thing without+needing the shell. Eg:++$ hledger print -o foo.txt+$ hledger print -o - # write to stdout (the default)+++File: hledger.info, Node: Output format, Next: Regular expressions, Prev: Output destination, Up: OPTIONS++2.10 Output format+==================++Some commands (print, register, the balance commands) offer a choice of+output format. In addition to the usual plain text format ('txt'),+there are CSV ('csv'), HTML ('html'), JSON ('json') and SQL ('sql').+This is controlled by the '-O/--output-format' option:++$ hledger print -O csv++ or, by a file extension specified with '-o/--output-file':++$ hledger balancesheet -o foo.html # write HTML to foo.html++ The '-O' option can be used to override the file extension if needed:++$ hledger balancesheet -o foo.txt -O html # write HTML to foo.txt++ Some notes about JSON output:++ * This feature is marked experimental, and not yet much used; you+ should expect our JSON to evolve. Real-world feedback is welcome.++ * Our JSON is rather large and verbose, as it is quite a faithful+ representation of hledger's internal data types. To understand the+ JSON, read the Haskell type definitions, which are mostly in+ https://github.com/simonmichael/hledger/blob/master/hledger-lib/Hledger/Data/Types.hs.++ * hledger represents quantities as Decimal values storing up to 255+ significant digits, eg for repeating decimals. Such numbers can+ arise in practice (from automatically-calculated transaction+ prices), and would break most JSON consumers. So in JSON, we show+ quantities as simple Numbers with at most 10 decimal places. We+ don't limit the number of integer digits, but that part is under+ your control. We hope this approach will not cause problems in+ practice; if you find otherwise, please let us know. (Cf #1195)++ Notes about SQL output:++ * SQL output is also marked experimental, and much like JSON could+ use real-world feedback.++ * SQL output is expected to work with sqlite, MySQL and PostgreSQL++ * SQL output is structured with the expectations that statements will+ be executed in the empty database. If you already have tables+ created via SQL output of hledger, you would probably want to+ either clear tables of existing data (via 'delete' or 'truncate'+ SQL statements) or drop tables completely as otherwise your+ postings will be duped.+++File: hledger.info, Node: Regular expressions, Next: Smart dates, Prev: Output format, Up: OPTIONS++2.11 Regular expressions+========================++hledger uses regular expressions in a number of places:++ * query terms, on the command line and in the hledger-web search+ form: 'REGEX', 'desc:REGEX', 'cur:REGEX', 'tag:...=REGEX'+ * CSV rules conditional blocks: 'if REGEX ...'+ * account alias directives and options: 'alias /REGEX/ =+ REPLACEMENT', '--alias /REGEX/=REPLACEMENT'++ hledger's regular expressions come from the regex-tdfa library. If+they're not doing what you expect, it's important to know exactly what+they support:++ 1. they are case insensitive+ 2. they are infix matching (they do not need to match the entire thing+ being matched)+ 3. they are POSIX ERE (extended regular expressions)+ 4. they also support GNU word boundaries ('\b', '\B', '\<', '\>')+ 5. they do not support backreferences; if you write '\1', it will+ match the digit '1'. Except when doing text replacement, eg in+ account aliases, where backreferences can be used in the+ replacement string to reference capturing groups in the search+ regexp.+ 6. they do not support mode modifiers ('(?s)'), character classes+ ('\w', '\d'), or anything else not mentioned above.++ Some things to note:++ * In the 'alias' directive and '--alias' option, regular expressions+ must be enclosed in forward slashes ('/REGEX/'). Elsewhere in+ hledger, these are not required.++ * In queries, to match a regular expression metacharacter like '$' as+ a literal character, prepend a backslash. Eg to search for amounts+ with the dollar sign in hledger-web, write 'cur:\$'.++ * On the command line, some metacharacters like '$' have a special+ meaning to the shell and so must be escaped at least once more.+ See Special characters.+++File: hledger.info, Node: Smart dates, Next: Report start & end date, Prev: Regular expressions, Up: OPTIONS++2.12 Smart dates+================++hledger's user interfaces accept a flexible "smart date" syntax (unlike+dates in the journal file). Smart dates allow some english words, can+be relative to today's date, and can have less-significant date parts+omitted (defaulting to 1).++ Examples:++'2004/10/1', exact date, several separators allowed. Year+'2004-01-01', is 4+ digits, month is 1-12, day is 1-31+'2004.9.1'+'2004' start of year+'2004/10' start of month+'10/1' month and day in current year+'21' day in current month+'october, oct' start of month in current year+'yesterday, today, -1, 0, 1 days from today+tomorrow'+'last/this/next -1, 0, 1 periods from the current period+day/week/month/quarter/year'+'20181201' 8 digit YYYYMMDD with valid year month and+ day+'201812' 6 digit YYYYMM with valid year and month++ Counterexamples - malformed digit sequences might give surprising+results:++'201813' 6 digits with an invalid month is parsed as start of+ 6-digit year+'20181301' 8 digits with an invalid month is parsed as start of+ 8-digit year+'20181232' 8 digits with an invalid day gives an error+'201801012' 9+ digits beginning with a valid YYYYMMDD gives an error+++File: hledger.info, Node: Report start & end date, Next: Report intervals, Prev: Smart dates, Up: OPTIONS++2.13 Report start & end date+============================++Most hledger reports show the full span of time represented by the+journal data, by default. So, the effective report start and end dates+will be the earliest and latest transaction or posting dates found in+the journal.++ Often you will want to see a shorter time span, such as the current+month. You can specify a start and/or end date using '-b/--begin',+'-e/--end', '-p/--period' or a 'date:' query (described below). All of+these accept the smart date syntax.++ Some notes:++ * As in Ledger, end dates are exclusive, so you need to write the+ date _after_ the last day you want to include.+ * As noted in reporting options: among start/end dates specified with+ _options_, the last (i.e. right-most) option takes precedence.+ * The effective report start and end dates are the intersection of+ the start/end dates from options and that from 'date:' queries.+ That is, 'date:2019-01 date:2019 -p'2000 to 2030'' yields January+ 2019, the smallest common time span.++ Examples:++'-b begin on St. Patrick's day 2016+2016/3/17'+'-e 12/1' end at the start of december 1st of the current year+ (11/30 will be the last date included)+'-b all transactions on or after the 1st of the current month+thismonth'+'-p all transactions in the current month+thismonth'+'date:2016/3/17..'the above written as queries instead ('..' can also be+ replaced with '-')+'date:..12/1'+'date:thismonth..'+'date:thismonth'+++File: hledger.info, Node: Report intervals, Next: Period expressions, Prev: Report start & end date, Up: OPTIONS++2.14 Report intervals+=====================++A report interval can be specified so that commands like register,+balance and activity will divide their reports into multiple subperiods.+The basic intervals can be selected with one of '-D/--daily',+'-W/--weekly', '-M/--monthly', '-Q/--quarterly', or '-Y/--yearly'. More+complex intervals may be specified with a period expression. Report+intervals can not be specified with a query.+++File: hledger.info, Node: Period expressions, Next: Depth limiting, Prev: Report intervals, Up: OPTIONS++2.15 Period expressions+=======================++The '-p/--period' option accepts period expressions, a shorthand way of+expressing a start date, end date, and/or report interval all at once.++ Here's a basic period expression specifying the first quarter of+2009. Note, hledger always treats start dates as inclusive and end+dates as exclusive:++ '-p "from 2009/1/1 to 2009/4/1"'++ Keywords like "from" and "to" are optional, and so are the spaces, as+long as you don't run two dates together. "to" can also be written as+".." or "-". These are equivalent to the above:++'-p "2009/1/1 2009/4/1"'+'-p2009/1/1to2009/4/1'+'-p2009/1/1..2009/4/1'++ Dates are smart dates, so if the current year is 2009, the above can+also be written as:++'-p "1/1 4/1"'+'-p "january-apr"'+'-p "this year to 4/1"'++ If you specify only one date, the missing start or end date will be+the earliest or latest transaction in your journal:++'-p "from 2009/1/1"' everything after january 1, 2009+'-p "from 2009/1"' the same+'-p "from 2009"' the same+'-p "to 2009"' everything before january 1, 2009++ A single date with no "from" or "to" defines both the start and end+date like so:++'-p "2009"' the year 2009; equivalent to “2009/1/1 to 2010/1/1”+'-p "2009/1"' the month of jan; equivalent to “2009/1/1 to 2009/2/1”+'-p "2009/1/1"' just that day; equivalent to “2009/1/1 to 2009/1/2”++ Or you can specify a single quarter like so:++'-p "2009Q1"' first quarter of 2009, equivalent to “2009/1/1 to 2009/4/1”+'-p "q4"' fourth quarter of the current year++ The argument of '-p' can also begin with, or be, a report interval+expression. The basic report intervals are 'daily', 'weekly',+'monthly', 'quarterly', or 'yearly', which have the same effect as the+'-D','-W','-M','-Q', or '-Y' flags. Between report interval and+start/end dates (if any), the word 'in' is optional. Examples:++'-p "weekly from 2009/1/1 to 2009/4/1"'+'-p "monthly in 2008"'+'-p "quarterly"'++ Note that 'weekly', 'monthly', 'quarterly' and 'yearly' intervals+will always start on the first day on week, month, quarter or year+accordingly, and will end on the last day of same period, even if+associated period expression specifies different explicit start and end+date.++ For example:++'-p "weekly from starts on 2008/12/29, closest preceding+2009/1/1 to 2009/4/1"' Monday+'-p "monthly in starts on 2018/11/01+2008/11/25"'+'-p "quarterly from starts on 2009/04/01, ends on 2009/06/30,+2009-05-05 to which are first and last days of Q2 2009+2009-06-01"'+'-p "yearly from starts on 2009/01/01, first day of 2009+2009-12-29"'++ The following more complex report intervals are also supported:+'biweekly', 'fortnightly', 'bimonthly', 'every+day|week|month|quarter|year', 'every N+days|weeks|months|quarters|years'.++ All of these will start on the first day of the requested period and+end on the last one, as described above.++ Examples:++'-p "bimonthly from periods will have boundaries on 2008/01/01,+2008"' 2008/03/01, ...+'-p "every 2 weeks"' starts on closest preceding Monday+'-p "every 5 month from periods will have boundaries on 2009/03/01,+2009/03"' 2009/08/01, ...++ If you want intervals that start on arbitrary day of your choosing+and span a week, month or year, you need to use any of the following:++ 'every Nth day of week', 'every WEEKDAYNAME' (eg+'mon|tue|wed|thu|fri|sat|sun'), 'every Nth day [of month]', 'every Nth+WEEKDAYNAME [of month]', 'every MM/DD [of year]', 'every Nth MMM [of+year]', 'every MMM Nth [of year]'.++ Examples:++'-p "every 2nd day of periods will go from Tue to Tue+week"'+'-p "every Tue"' same+'-p "every 15th day"' period boundaries will be on 15th of each+ month+'-p "every 2nd period boundaries will be on second Monday of+Monday"' each month+'-p "every 11/05"' yearly periods with boundaries on 5th of Nov+'-p "every 5th Nov"' same+'-p "every Nov 5th"' same++ Show historical balances at end of 15th each month (N is exclusive+end date):++ 'hledger balance -H -p "every 16th day"'++ Group postings from start of wednesday to end of next tuesday (N is+start date and exclusive end date):++ 'hledger register checking -p "every 3rd day of week"'+++File: hledger.info, Node: Depth limiting, Next: Pivoting, Prev: Period expressions, Up: OPTIONS++2.16 Depth limiting+===================++With the '--depth N' option (short form: '-N'), commands like account,+balance and register will show only the uppermost accounts in the+account tree, down to level N. Use this when you want a summary with+less detail. This flag has the same effect as a 'depth:' query argument+(so '-2', '--depth=2' or 'depth:2' are equivalent).+++File: hledger.info, Node: Pivoting, Next: Valuation, Prev: Depth limiting, Up: OPTIONS++2.17 Pivoting+=============++Normally hledger sums amounts, and organizes them in a hierarchy, based+on account name. The '--pivot FIELD' option causes it to sum and+organize hierarchy based on the value of some other field instead.+FIELD can be: 'code', 'description', 'payee', 'note', or the full name+(case insensitive) of any tag. As with account names, values containing+'colon:separated:parts' will be displayed hierarchically in reports.++ '--pivot' is a general option affecting all reports; you can think of+hledger transforming the journal before any other processing, replacing+every posting's account name with the value of the specified field on+that posting, inheriting it from the transaction or using a blank value+if it's not present.++ An example:++2016/02/16 Member Fee Payment+ assets:bank account 2 EUR+ income:member fees -2 EUR ; member: John Doe++ Normal balance report showing account names:++$ hledger balance+ 2 EUR assets:bank account+ -2 EUR income:member fees+--------------------+ 0++ Pivoted balance report, using member: tag values instead:++$ hledger balance --pivot member+ 2 EUR+ -2 EUR John Doe+--------------------+ 0++ One way to show only amounts with a member: value (using a query,+described below):++$ hledger balance --pivot member tag:member=.+ -2 EUR John Doe+--------------------+ -2 EUR++ Another way (the acct: query matches against the pivoted "account+name"):++$ hledger balance --pivot member acct:.+ -2 EUR John Doe+--------------------+ -2 EUR+++File: hledger.info, Node: Valuation, Prev: Pivoting, Up: OPTIONS++2.18 Valuation+==============++Instead of reporting amounts in their original commodity, hledger can+convert them to cost/sale amount (using the conversion rate recorded in+the transaction), or to market value (using some market price on a+certain date). This is controlled by the '--value=TYPE[,COMMODITY]'+option, but we also provide the simpler '-B'/'-V'/'-X' flags, and+usually one of those is all you need.++* Menu:++* -B Cost::+* -V Value::+* -X Value in specified commodity::+* Valuation date::+* Market prices::+* --infer-value market prices from transactions::+* Valuation commodity::+* Simple valuation examples::+* --value Flexible valuation::+* More valuation examples::+* Effect of valuation on reports::+++File: hledger.info, Node: -B Cost, Next: -V Value, Up: Valuation++2.18.1 -B: Cost+---------------++The '-B/--cost' flag converts amounts to their cost or sale amount at+transaction time, if they have a transaction price specified.+++File: hledger.info, Node: -V Value, Next: -X Value in specified commodity, Prev: -B Cost, Up: Valuation++2.18.2 -V: Value+----------------++The '-V/--market' flag converts amounts to market value in their default+_valuation commodity_, using the market prices in effect on the+_valuation date(s)_, if any. More on these in a minute.+++File: hledger.info, Node: -X Value in specified commodity, Next: Valuation date, Prev: -V Value, Up: Valuation++2.18.3 -X: Value in specified commodity+---------------------------------------++The '-X/--exchange=COMM' option is like '-V', except you tell it which+currency you want to convert to, and it tries to convert everything to+that.+++File: hledger.info, Node: Valuation date, Next: Market prices, Prev: -X Value in specified commodity, Up: Valuation++2.18.4 Valuation date+---------------------++Since market prices can change from day to day, market value reports+have a valuation date (or more than one), which determines which market+prices will be used.++ For single period reports, if an explicit report end date is+specified, that will be used as the valuation date; otherwise the+valuation date is "today".++ For multiperiod reports, each column/period is valued on the last day+of the period, by default.+++File: hledger.info, Node: Market prices, Next: --infer-value market prices from transactions, Prev: Valuation date, Up: Valuation++2.18.5 Market prices+--------------------++_(experimental)_++ 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 :++ 1. A _declared market price_ or _inferred market price_: A's latest+ market price in B on or before the valuation date as declared by a+ P directive, or (with the '--infer-value' flag) inferred from+ transaction prices.++ 2. A _reverse market price_: the inverse of a declared or inferred+ market price from B to A.++ 3. A _a forward chain of market prices_: a synthetic price formed by+ combining the shortest chain of "forward" (only 1 above) market+ prices, leading from A to B.++ 4. A _any chain of market prices_: a chain of any market prices,+ including both forward and reverse prices (1 and 2 above), leading+ from A to B.++ Amounts for which no applicable market price can be found, are not+converted.+++File: hledger.info, Node: --infer-value market prices from transactions, Next: Valuation commodity, Prev: Market prices, Up: Valuation++2.18.6 -infer-value: market prices from transactions+----------------------------------------------------++_(experimental)_++ 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 transaction prices as additional+market prices (as Ledger does) ? We could produce value reports without+needing P directives at all.++ Adding the '--infer-value' flag to '-V', '-X' or '--value' enables+this. So for example, 'hledger bs -V --infer-value' will get market+prices both from P directives and from transactions.++ 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 Valuation section carefully, and try adding+'--debug' or '--debug=2' to troubleshoot.++ '--infer-value' can infer market prices from:++ * multicommodity transactions with explicit prices ('@'/'@@')++ * multicommodity transactions with implicit prices (no '@', two+ commodities, unbalanced). (With these, the order of postings+ matters. 'hledger print -x' can be useful for troubleshooting.)++ * but not, currently, from "more correct" multicommodity transactions+ (no '@', multiple commodities, balanced).+++File: hledger.info, Node: Valuation commodity, Next: Simple valuation examples, Prev: --infer-value market prices from transactions, Up: Valuation++2.18.7 Valuation commodity+--------------------------++_(experimental)_++ *When you specify a valuation commodity ('-X COMM' or '--value+TYPE,COMM'):*+hledger will convert all amounts to COMM, wherever it can find a+suitable market price (including by reversing or chaining prices).++ *When you leave the valuation commodity unspecified ('-V' or '--value+TYPE'):*+For each commodity A, hledger picks a default valuation commodity as+follows, in this order of preference:++ 1. The price commodity from the latest P-declared market price for A+ on or before valuation date.++ 2. 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.)++ 3. If there are no P directives at all (any commodity or date) and the+ '--infer-value' flag is used: the price commodity from the latest+ transaction-inferred price for A on or before valuation date.++ This means:++ * If you have P directives, they determine which commodities '-V'+ will convert, and to what.++ * If you have no P directives, and use the '--infer-value' flag,+ transaction prices determine it.++ Amounts for which no valuation commodity can be found are not+converted.+++File: hledger.info, Node: Simple valuation examples, Next: --value Flexible valuation, Prev: Valuation commodity, Up: Valuation++2.18.8 Simple valuation examples+--------------------------------++Here are some quick examples of '-V':++; 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++ How many euros do I have ?++$ hledger -f t.j bal -N euros+ €100 assets:euros++ What are they worth at end of nov 3 ?++$ hledger -f t.j bal -N euros -V -e 2016/11/4+ $110.00 assets:euros++ What are they worth after 2016/12/21 ? (no report end date+specified, defaults to today)++$ hledger -f t.j bal -N euros -V+ $103.00 assets:euros+++File: hledger.info, Node: --value Flexible valuation, Next: More valuation examples, Prev: Simple valuation examples, Up: Valuation++2.18.9 -value: Flexible valuation+---------------------------------++'-B', '-V' and '-X' are special cases of the more general '--value'+option:++ --value=TYPE[,COMM] TYPE is cost, then, end, now or YYYY-MM-DD.+ COMM is an optional commodity symbol.+ Shows amounts converted to:+ - cost commodity using transaction prices (then optionally to COMM using market prices at period end(s))+ - 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++ The TYPE part selects cost or value and valuation date:++'--value=cost'++ Convert amounts to cost, using the prices recorded in transactions.+'--value=then'++ Convert amounts to their value in the default valuation commodity,+ using market prices on each posting's date. This is currently+ supported only by the print and register commands.+'--value=end'++ 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's end date); or in multiperiod reports,+ market prices on the last day of each subperiod.+'--value=now'++ Convert amounts to their value in the default valuation commodity+ using current market prices (as of when report is generated).+'--value=YYYY-MM-DD'++ Convert amounts to their value in the default valuation commodity+ using market prices on this date.++ To select a different valuation commodity, add the optional ',COMM'+part: a comma, then the target commodity's symbol. Eg:+*'--value=now,EUR'*. hledger will do its best to convert amounts to+this commodity, deducing market prices as described above.+++File: hledger.info, Node: More valuation examples, Next: Effect of valuation on reports, Prev: --value Flexible valuation, Up: Valuation++2.18.10 More valuation examples+-------------------------------++Here are some examples showing the effect of '--value', as seen with+'print':++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 @ 5 B++2000-02-01+ (a) 1 A @ 6 B++2000-03-01+ (a) 1 A @ 7 B++ Show the cost of each posting:++$ hledger -f- print --value=cost+2000-01-01+ (a) 5 B++2000-02-01+ (a) 6 B++2000-03-01+ (a) 7 B++ Show the value as of the last day of the report period (2000-02-29):++$ hledger -f- print --value=end date:2000/01-2000/03+2000-01-01+ (a) 2 B++2000-02-01+ (a) 2 B++ With no report period specified, that shows the value as of the last+day of the journal (2000-03-01):++$ hledger -f- print --value=end+2000-01-01+ (a) 3 B++2000-02-01+ (a) 3 B++2000-03-01+ (a) 3 B++ Show the current value (the 2000-04-01 price is still in effect+today):++$ hledger -f- print --value=now+2000-01-01+ (a) 4 B++2000-02-01+ (a) 4 B++2000-03-01+ (a) 4 B++ Show the value on 2000/01/15:++$ 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++ You may need to explicitly set a commodity's display style, when+reverse prices are used. Eg this output might be surprising:++P 2000-01-01 A 2B++2000-01-01+ a 1B+ b++$ hledger print -x -X A+2000-01-01+ a 0+ b 0++ Explanation: because there's no amount or commodity directive+specifying a display style for A, 0.5A gets the default style, which+shows no decimal digits. Because the displayed amount looks like zero,+the commodity symbol and minus sign are not displayed either. Adding a+commodity directive sets a more useful display style for A:++P 2000-01-01 A 2B+commodity 0.00A++2000-01-01+ a 1B+ b++$ hledger print -X A+2000-01-01+ a 0.50A+ b -0.50A+++File: hledger.info, Node: Effect of valuation on reports, Prev: More valuation examples, Up: Valuation++2.18.11 Effect of valuation on reports+--------------------------------------++Here is a reference for how valuation is supposed to affect each part of+hledger's reports (and a glossary). (It's wide, you'll have to scroll+sideways.) It may be useful when troubleshooting. If you find+problems, please report them, ideally with a reproducible example.+Related: #329, #1083.++Report '-B', '-V', '-X' '--value=then''--value=end' '--value=DATE',+type '--value=cost' '--value=now'+--------------------------------------------------------------------------------+*print*+posting cost value at value at value at value+amounts report end posting report or at+ or today date journal end DATE/today+balance unchanged unchanged unchanged unchanged unchanged+assertions/assignments+*register*+starting cost value at day not value at day value+balance before supported before at+(-H) report or report or DATE/today+ journal journal+ start start+posting cost value at value at value at value+amounts report end posting report or at+ or today date journal end DATE/today+summary summarised value at sum of value at value+posting cost period ends postings period ends at+amounts in DATE/today+with interval,+report valued at+interval interval+ start+running sum/average sum/average sum/average sum/average sum/average+total/averageof displayed of displayed of of displayed of+ values values displayed values displayed+ values values+*balance+(bs, bse,+cf, is)*+balance sums of value at not value at value+changes costs report end supported report or at+ or today of journal end DATE/today+ sums of of sums of of sums+ postings postings of+ postings+budget like balance like balance not like like+amounts changes changes supported balances balance+(-budget) changes+grand sum of sum of not sum of sum of+total displayed displayed supported displayed displayed+ values values values values+*balance+(bs, bse,+cf, is)+with+report+interval*+starting sums of value at not value at sums of+balances costs of report start supported report start postings+(-H) postings of sums of of sums of before+ before all postings all postings report+ report start before before start+ report start report start+balance sums of same as not balance value+changes costs of -value=end supported change in at+(bal, is, postings in each period, DATE/today+bs period valued at of sums+-change, period ends of+cf postings+-change)+end sums of same as not period end value+balances costs of -value=end supported balances, at+(bal -H, postings valued at DATE/today+is -H, from before period ends of sums+bs, cf) report start of+ to period postings+ end+budget like balance like balance not like like+amounts changes/end changes/end supported balances balance+(-budget) balances balances changes/end+ balances+row sums, sums, not sums, sums,+totals, averages of averages of supported averages of averages+row displayed displayed displayed of+averages values values values displayed+(-T, -A) values+column sums of sums of not sums of sums of+totals displayed displayed supported displayed displayed+ values values values values+grand sum, average sum, average not sum, average sum,+total, of column of column supported of column average+grand totals totals totals of+average column+ totals++ '--cumulative' is omitted to save space, it works like '-H' but with+a zero starting balance.++ *Glossary:*++_cost_++ calculated using price(s) recorded in the transaction(s).+_value_++ market value using available market price declarations, or the+ unchanged amount if no conversion rate can be found.+_report start_++ the first day of the report period specified with -b or -p or+ date:, otherwise today.+_report or journal start_++ the first day of the report period specified with -b or -p or+ date:, otherwise the earliest transaction date in the journal,+ otherwise today.+_report end_++ the last day of the report period specified with -e or -p or date:,+ otherwise today.+_report or journal end_++ the last day of the report period specified with -e or -p or date:,+ otherwise the latest transaction date in the journal, otherwise+ today.+_report interval_++ a flag (-D/-W/-M/-Q/-Y) or period expression that activates the+ report's multi-period mode (whether showing one or many+ subperiods).+++File: hledger.info, Node: COMMANDS, Next: ENVIRONMENT, Prev: OPTIONS, Up: Top++3 COMMANDS+**********++hledger provides a number of subcommands; 'hledger' with no arguments+shows a list.++ If you install additional 'hledger-*' packages, or if you put+programs or scripts named 'hledger-NAME' in your PATH, these will also+be listed as subcommands.++ Run a subcommand by writing its name as first argument (eg 'hledger+incomestatement'). You can also write one of the standard short aliases+displayed in parentheses in the command list ('hledger b'), or any any+unambiguous prefix of a command name ('hledger inc').++ Here are all the builtin commands in alphabetical order. See also+'hledger' for a more organised command list, and 'hledger CMD -h' for+detailed command help.++* Menu:++* accounts::+* activity::+* add::+* aregister::+* balance::+* balancesheet::+* balancesheetequity::+* cashflow::+* check::+* close::+* codes::+* commodities::+* descriptions::+* diff::+* files::+* help::+* import::+* incomestatement::+* notes::+* payees::+* prices::+* print::+* print-unique::+* register::+* register-match::+* rewrite::+* roi::+* stats::+* tags::+* test::+* Add-on commands::+++File: hledger.info, Node: accounts, Next: activity, Up: COMMANDS++3.1 accounts+============++accounts, a+Show account names.++ This command lists account names, either declared with account+directives (-declared), posted to (-used), or both (the default). With+query arguments, only matched account names and account names referenced+by matched postings are shown. It shows a flat list by default. With+'--tree', it uses indentation to show the account hierarchy. In flat+mode you can add '--drop N' to omit the first few account name+components. Account names can be depth-clipped with 'depth:N' or+'--depth N' or '-N'.++ Examples:++$ hledger accounts+assets:bank:checking+assets:bank:saving+assets:cash+expenses:food+expenses:supplies+income:gifts+income:salary+liabilities:debts+++File: hledger.info, Node: activity, Next: add, Prev: accounts, Up: COMMANDS++3.2 activity+============++activity+Show an ascii barchart of posting counts per interval.++ The activity command displays an ascii histogram showing transaction+counts by day, week, month or other reporting interval (by day is the+default). With query arguments, it counts only matched transactions.++ Examples:++$ hledger activity --quarterly+2008-01-01 **+2008-04-01 *******+2008-07-01 +2008-10-01 **+++File: hledger.info, Node: add, Next: aregister, Prev: activity, Up: COMMANDS++3.3 add+=======++add+Prompt for transactions and add them to the journal. Any arguments will+be used as default inputs for the first N prompts.++ Many hledger users edit their journals directly with a text editor,+or generate them from CSV. For more interactive data entry, there is the+'add' command, which prompts interactively on the console for new+transactions, and appends them to the journal file (if there are+multiple '-f FILE' options, the first file is used.) Existing+transactions are not changed. This is the only hledger command that+writes to the journal file.++ To use it, just run 'hledger add' and follow the prompts. You can+add as many transactions as you like; when you are finished, enter '.'+or press control-d or control-c to exit.++ Features:++ * add tries to provide useful defaults, using the most similar (by+ description) recent transaction (filtered by the query, if any) as+ a template.+ * You can also set the initial defaults with command line arguments.+ * Readline-style edit keys can be used during data entry.+ * The tab key will auto-complete whenever possible - accounts,+ descriptions, dates ('yesterday', 'today', 'tomorrow'). If the+ input area is empty, it will insert the default value.+ * If the journal defines a default commodity, it will be added to any+ bare numbers entered.+ * A parenthesised transaction code may be entered following a date.+ * Comments and tags may be entered following a description or amount.+ * If you make a mistake, enter '<' at any prompt to go one step+ backward.+ * Input prompts are displayed in a different colour when the terminal+ supports it.++ Example (see the tutorial for a detailed explanation):++$ hledger add+Adding transactions to journal file /src/hledger/examples/sample.journal+Any command line arguments will be used as defaults.+Use tab key to complete, readline keys to edit, enter to accept defaults.+An optional (CODE) may follow transaction dates.+An optional ; COMMENT may follow descriptions or amounts.+If you make a mistake, enter < at any prompt to go one step backward.+To end a transaction, enter . when prompted.+To quit, enter . at a date prompt or press control-d or control-c.+Date [2015/05/22]: +Description: supermarket+Account 1: expenses:food+Amount 1: $10+Account 2: assets:checking+Amount 2 [$-10.0]: +Account 3 (or . or enter to finish this transaction): .+2015/05/22 supermarket+ expenses:food $10+ assets:checking $-10.0++Save this transaction to the journal ? [y]: +Saved.+Starting the next transaction (. or ctrl-D/ctrl-C to quit)+Date [2015/05/22]: <CTRL-D> $++ On Microsoft Windows, the add command makes sure that no part of the+file path ends with a period, as that would cause problems (#1056).+++File: hledger.info, Node: aregister, Next: balance, Prev: add, Up: COMMANDS++3.4 aregister+=============++aregister, areg+Show transactions affecting a particular account, and the account's+running balance.++ 'aregister' shows the transactions affecting a particular account+(and its subaccounts), from the point of view of that account. Each+line shows:++ * the transaction's (or posting's, see below) date+ * the names of the other account(s) involved+ * the net change to this account's balance+ * the account's historical running balance (including balance from+ transactions before the report start date).++ With 'aregister', each line represents a whole transaction - as in+hledger-ui, hledger-web, and your bank statement. By contrast, the+'register' command shows individual postings, across all accounts. You+might prefer 'aregister' for reconciling with real-world asset/liability+accounts, and 'register' for reviewing detailed revenues/expenses.++ An account must be specified as the first argument, which should be+the full account name or an account pattern (regular expression).+aregister will show transactions in this account (the first one matched)+and any of its subaccounts.++ Any additional arguments form a query which will filter the+transactions shown.++ Transactions making a net change of zero are not shown by default;+add the '-E/--empty' flag to show them.++* Menu:++* aregister and custom posting dates::+* Output format::+++File: hledger.info, Node: aregister and custom posting dates, Next: , Up: aregister++3.4.1 aregister and custom posting dates+----------------------------------------++Transactions whose date is outside the report period can still be shown,+if they have a posting to this account dated inside the report period.+(And in this case it's the posting date that is shown.) This ensures+that 'aregister' can show an accurate historical running balance,+matching the one shown by 'register -H' with the same arguments.++ To filter strictly by transaction date instead, add the '--txn-dates'+flag. If you use this flag and some of your postings have custom dates,+it's probably best to assume the running balance is wrong.++3.4.2 Output format+-------------------++This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', and 'json'.++ Examples:++ Show all transactions and historical running balance in the first+account whose name contains "checking":++$ hledger areg checking++ Show transactions and historical running balance in all asset+accounts during july:++$ hledger areg assets date:jul+++File: hledger.info, Node: balance, Next: balancesheet, Prev: aregister, Up: COMMANDS++3.5 balance+===========++balance, bal, b+Show accounts and their balances.++ The balance command is hledger's most versatile command. Note,+despite the name, it is not always used for showing real-world account+balances; the more accounting-aware balancesheet and incomestatement may+be more convenient for that.++ By default, it displays all accounts, and each account's change in+balance during the entire period of the journal. Balance changes are+calculated by adding up the postings in each account. You can limit the+postings matched, by a query, to see fewer accounts, changes over a+different time period, changes from only cleared transactions, etc.++ If you include an account's complete history of postings in the+report, the balance change is equivalent to the account's current ending+balance. For a real-world account, typically you won't have all+transactions in the journal; instead you'll have all transactions after+a certain date, and an "opening balances" transaction setting the+correct starting balance on that date. Then the balance command will+show real-world account balances. In some cases the -H/-historical flag+is used to ensure this (more below).++ The balance command can produce several styles of report:++* Menu:++* Classic balance report::+* Customising the classic balance report::+* Colour support::+* Flat mode::+* Depth limited balance reports::+* Percentages::+* Sorting by amount::+* Multicolumn balance report::+* Budget report::+* Output format::+++File: hledger.info, Node: Classic balance report, Next: Customising the classic balance report, Up: balance++3.5.1 Classic balance report+----------------------------++This is the original balance report, as found in Ledger. It usually+looks like this:++$ hledger balance+ $-1 assets+ $1 bank:saving+ $-2 cash+ $2 expenses+ $1 food+ $1 supplies+ $-2 income+ $-1 gifts+ $-1 salary+ $1 liabilities:debts+--------------------+ 0++ By default, accounts are displayed hierarchically, with subaccounts+indented below their parent, with accounts at each level of the tree+sorted by declaration order if declared, then by account name.++ "Boring" accounts, which contain a single interesting subaccount and+no balance of their own, are elided into the following line for more+compact output. (Eg above, the "liabilities" account.) Use+'--no-elide' to prevent this.++ Account balances are "inclusive" - they include the balances of any+subaccounts.++ Accounts which have zero balance (and no non-zero subaccounts) are+omitted. Use '-E/--empty' to show them.++ A final total is displayed by default; use '-N/--no-total' to+suppress it, eg:++$ hledger balance -p 2008/6 expenses --no-total+ $2 expenses+ $1 food+ $1 supplies+++File: hledger.info, Node: Customising the classic balance report, Next: Colour support, Prev: Classic balance report, Up: balance++3.5.2 Customising the classic balance report+--------------------------------------------++You can customise the layout of classic balance reports with '--format+FMT':++$ hledger balance --format "%20(account) %12(total)"+ assets $-1+ bank:saving $1+ cash $-2+ expenses $2+ food $1+ supplies $1+ income $-2+ gifts $-1+ salary $-1+ liabilities:debts $1+---------------------------------+ 0++ The FMT format string (plus a newline) specifies the formatting+applied to each account/balance pair. It may contain any suitable text,+with data fields interpolated like so:++ '%[MIN][.MAX](FIELDNAME)'++ * MIN pads with spaces to at least this width (optional)++ * MAX truncates at this width (optional)++ * FIELDNAME must be enclosed in parentheses, and can be one of:++ * 'depth_spacer' - a number of spaces equal to the account's+ depth, or if MIN is specified, MIN * depth spaces.+ * 'account' - the account's name+ * 'total' - the account's balance/posted total, right justified++ Also, FMT can begin with an optional prefix to control how+multi-commodity amounts are rendered:++ * '%_' - render on multiple lines, bottom-aligned (the default)+ * '%^' - render on multiple lines, top-aligned+ * '%,' - render on one line, comma-separated++ There are some quirks. Eg in one-line mode, '%(depth_spacer)' has no+effect, instead '%(account)' has indentation built in. Experimentation+may be needed to get pleasing results.++ Some example formats:++ * '%(total)' - the account's total+ * '%-20.20(account)' - the account's name, left justified, padded to+ 20 characters and clipped at 20 characters+ * '%,%-50(account) %25(total)' - account name padded to 50+ characters, total padded to 20 characters, with multiple+ commodities rendered on one line+ * '%20(total) %2(depth_spacer)%-(account)' - the default format for+ the single-column balance report+++File: hledger.info, Node: Colour support, Next: Flat mode, Prev: Customising the classic balance report, Up: balance++3.5.3 Colour support+--------------------++In terminal output, when colour is enabled, the balance command shows+negative amounts in red.+++File: hledger.info, Node: Flat mode, Next: Depth limited balance reports, Prev: Colour support, Up: balance++3.5.4 Flat mode+---------------++To see a flat list instead of the default hierarchical display, use+'--flat'. In this mode, accounts (unless depth-clipped) show their full+names and "exclusive" balance, excluding any subaccount balances. In+this mode, you can also use '--drop N' to omit the first few account+name components.++$ hledger balance -p 2008/6 expenses -N --flat --drop 1+ $1 food+ $1 supplies+++File: hledger.info, Node: Depth limited balance reports, Next: Percentages, Prev: Flat mode, Up: balance++3.5.5 Depth limited balance reports+-----------------------------------++With '--depth N' or 'depth:N' or just '-N', balance reports show+accounts only to the specified numeric depth. This is very useful to+summarise a complex set of accounts and get an overview.++$ hledger balance -N -1+ $-1 assets+ $2 expenses+ $-2 income+ $1 liabilities++ Flat-mode balance reports, which normally show exclusive balances,+show inclusive balances at the depth limit.+++File: hledger.info, Node: Percentages, Next: Sorting by amount, Prev: Depth limited balance reports, Up: balance++3.5.6 Percentages+-----------------++With '-%' or '--percent', balance reports show each account's value+expressed as a percentage of the column's total. This is useful to get+an overview of the relative sizes of account balances. For example to+obtain an overview of expenses:++$ hledger balance expenses -%+ 100.0 % expenses+ 50.0 % food+ 50.0 % supplies+--------------------+ 100.0 %++ Note that '--tree' does not have an effect on '-%'. The percentages+are always relative to the total sum of each column, they are never+relative to the parent account.++ Since the percentages are relative to the columns sum, it is usually+not useful to calculate percentages if the signs of the amounts are+mixed. Although the results are technically correct, they are most+likely useless. Especially in a balance report that sums up to zero (eg+'hledger balance -B') all percentage values will be zero.++ This flag does not work if the report contains any mixed commodity+accounts. If there are mixed commodity accounts in the report be sure+to use '-V' or '-B' to coerce the report into using a single commodity.+++File: hledger.info, Node: Sorting by amount, Next: Multicolumn balance report, Prev: Percentages, Up: balance++3.5.7 Sorting by amount+-----------------------++With '-S'/'--sort-amount', accounts with the largest (most positive)+balances are shown first. For example, 'hledger bal expenses -MAS'+shows your biggest averaged monthly expenses first.++ Revenues and liability balances are typically negative, however, so+'-S' shows these in reverse order. To work around this, you can add+'--invert' to flip the signs. Or, use one of the sign-flipping reports+like 'balancesheet' or 'incomestatement', which also support '-S'. Eg:+'hledger is -MAS'.+++File: hledger.info, Node: Multicolumn balance report, Next: Budget report, Prev: Sorting by amount, Up: balance++3.5.8 Multicolumn balance report+--------------------------------++Multicolumn or tabular balance reports are a very useful hledger+feature, and usually the preferred style. They share many of the above+features, but they show the report as a table, with columns representing+time periods. This mode is activated by providing a reporting interval.++ There are three types of multicolumn balance report, showing+different information:++ 1. By default: each column shows the sum of postings in that period,+ ie the account's change of balance in that period. This is useful+ eg for a monthly income statement:++ $ hledger balance --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 ++ 2. With '--cumulative': each column shows the ending balance for that+ period, accumulating the changes across periods, starting from 0 at+ the report start date:++ $ hledger balance --quarterly income expenses -E --cumulative+ Ending balances (cumulative) in 2008:+ + || 2008/03/31 2008/06/30 2008/09/30 2008/12/31 + ===================++=================================================+ expenses:food || 0 $1 $1 $1 + expenses:supplies || 0 $1 $1 $1 + income:gifts || 0 $-1 $-1 $-1 + income:salary || $-1 $-1 $-1 $-1 + -------------------++-------------------------------------------------+ || $-1 0 0 0 ++ 3. With '--historical/-H': each column shows the actual historical+ ending balance for that period, accumulating the changes across+ periods, starting from the actual balance at the report start date.+ This is useful eg for a multi-period balance sheet, and when you+ are showing only the data after a certain start date:++ $ hledger balance ^assets ^liabilities --quarterly --historical --begin 2008/4/1+ Ending balances (historical) in 2008/04/01-2008/12/31:+ + || 2008/06/30 2008/09/30 2008/12/31 + ======================++=====================================+ assets:bank:checking || $1 $1 0 + assets:bank:saving || $1 $1 $1 + assets:cash || $-2 $-2 $-2 + liabilities:debts || 0 0 $1 + ----------------------++-------------------------------------+ || 0 0 0 ++ Note that '--cumulative' or '--historical/-H' disable+'--row-total/-T', since summing end balances generally does not make+sense.++ Multicolumn balance reports display accounts in flat mode by default;+to see the hierarchy, use '--tree'.++ With a reporting interval (like '--quarterly' above), the report+start/end dates will be adjusted if necessary so that they encompass the+displayed report periods. This is so that the first and last periods+will be "full" and comparable to the others.++ The '-E/--empty' flag does two things in multicolumn balance reports:+first, the report will show all columns within the specified report+period (without -E, leading and trailing columns with all zeroes are not+shown). Second, all accounts which existed at the report start date+will be considered, not just the ones with activity during the report+period (use -E to include low-activity accounts which would otherwise+would be omitted).++ The '-T/--row-total' flag adds an additional column showing the total+for each row.++ The '-A/--average' flag adds a column showing the average value in+each row.++ Here's an example of all three:++$ hledger balance -Q income expenses --tree -ETA+Balance changes in 2008:++ || 2008q1 2008q2 2008q3 2008q4 Total Average +============++===================================================+ expenses || 0 $2 0 0 $2 $1 + food || 0 $1 0 0 $1 0 + supplies || 0 $1 0 0 $1 0 + income || $-1 $-1 0 0 $-2 $-1 + gifts || 0 $-1 0 0 $-1 0 + salary || $-1 0 0 0 $-1 0 +------------++---------------------------------------------------+ || $-1 $1 0 0 0 0 ++(Average is rounded to the dollar here since all journal amounts are)++ The '--transpose' flag can be used to exchange the rows and columns+of a multicolumn report.++ When showing multicommodity amounts, multicolumn balance reports will+elide any amounts which have more than two commodities, since otherwise+columns could get very wide. The '--no-elide' flag disables this.+Hiding totals with the '-N/--no-total' flag can also help reduce the+width of multicommodity reports.++ When the report is still too wide, a good workaround is to pipe it+into 'less -RS' (-R for colour, -S to chop long lines). Eg: 'hledger+bal -D --color=yes | less -RS'.+++File: hledger.info, Node: Budget report, Next: , Prev: Multicolumn balance report, Up: balance++3.5.9 Budget report+-------------------++With '--budget', extra columns are displayed showing budget goals for+each account and period, if any. Budget goals are defined by periodic+transactions. This is very useful for comparing planned and actual+income, expenses, time usage, etc. -budget is most often combined with+a report interval.++ For example, you can take average monthly expenses in the common+expense categories to construct a minimal monthly budget:++;; Budget+~ monthly+ income $2000+ expenses:food $400+ expenses:bus $50+ expenses:movies $30+ assets:bank:checking++;; Two months worth of expenses+2017-11-01+ income $1950+ expenses:food $396+ expenses:bus $49+ expenses:movies $30+ expenses:supplies $20+ assets:bank:checking++2017-12-01+ income $2100+ expenses:food $412+ expenses:bus $53+ expenses:gifts $100+ assets:bank:checking++ You can now see a monthly budget report:++$ hledger balance -M --budget+Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec +======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + expenses || $495 [ 103% of $480] $565 [ 118% of $480] + expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50] + expenses:food || $396 [ 99% of $400] $412 [ 103% of $400] + expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30] + income || $1950 [ 98% of $2000] $2100 [ 105% of $2000] +----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0] ++ This is different from a normal balance report in several ways:++ * Only accounts with budget goals during the report period are shown,+ by default.++ * In each column, in square brackets after the actual amount, budget+ goal amounts are shown, and the actual/goal percentage. (Note:+ budget goals should be in the same commodity as the actual amount.)++ * All parent accounts are always shown, even in flat mode. Eg+ assets, assets:bank, and expenses above.++ * Amounts always include all subaccounts, budgeted or unbudgeted,+ even in flat mode.++ This means that the numbers displayed will not always add up! Eg+above, the 'expenses' actual amount includes the gifts and supplies+transactions, but the 'expenses:gifts' and 'expenses:supplies' accounts+are not shown, as they have no budget amounts declared.++ This can be confusing. When you need to make things clearer, use the+'-E/--empty' flag, which will reveal all accounts including unbudgeted+ones, giving the full picture. Eg:++$ hledger balance -M --budget --empty+Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec +======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + expenses || $495 [ 103% of $480] $565 [ 118% of $480] + expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50] + expenses:food || $396 [ 99% of $400] $412 [ 103% of $400] + expenses:gifts || 0 $100 + expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30] + expenses:supplies || $20 0 + income || $1950 [ 98% of $2000] $2100 [ 105% of $2000] +----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0] ++ You can roll over unspent budgets to next period with '--cumulative':++$ hledger balance -M --budget --cumulative+Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec +======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] + assets:bank || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] + assets:bank:checking || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] + expenses || $495 [ 103% of $480] $1060 [ 110% of $960] + expenses:bus || $49 [ 98% of $50] $102 [ 102% of $100] + expenses:food || $396 [ 99% of $400] $808 [ 101% of $800] + expenses:movies || $30 [ 100% of $30] $30 [ 50% of $60] + income || $1950 [ 98% of $2000] $4050 [ 101% of $4000] +----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0] ++ For more examples and notes, see Budgeting.++* Menu:++* Budget report start date::+* Nested budgets::+++File: hledger.info, Node: Budget report start date, Next: Nested budgets, Up: Budget report++3.5.9.1 Budget report start date+................................++This might be a bug, but for now: when making budget reports, it's a+good idea to explicitly set the report's start date to the first day of+a reporting period, because a periodic rule like '~ monthly' generates+its transactions on the 1st of each month, and if your journal has no+regular transactions on the 1st, the default report start date could+exclude that budget goal, which can be a little surprising. Eg here the+default report period is just the day of 2020-01-15:++~ monthly in 2020+ (expenses:food) $500++2020-01-15+ expenses:food $400+ assets:checking++$ hledger bal expenses --budget+Budget performance in 2020-01-15:++ || 2020-01-15 +==============++============+ <unbudgeted> || $400 +--------------++------------+ || $400 ++ To avoid this, specify the budget report's period, or at least the+start date, with '-b'/'-e'/'-p'/'date:', to ensure it includes the+budget goal transactions (periodic transactions) that you want. Eg,+adding '-b 2020/1/1' to the above:++$ hledger bal expenses --budget -b 2020/1/1+Budget performance in 2020-01-01..2020-01-15:++ || 2020-01-01..2020-01-15 +===============++========================+ expenses:food || $400 [80% of $500] +---------------++------------------------+ || $400 [80% of $500] +++File: hledger.info, Node: Nested budgets, Prev: Budget report start date, Up: Budget report++3.5.9.2 Nested budgets+......................++You can add budgets to any account in your account hierarchy. If you+have budgets on both parent account and some of its children, then+budget(s) of the child account(s) would be added to the budget of their+parent, much like account balances behave.++ In the most simple case this means that once you add a budget to any+account, all its parents would have budget as well.++ To illustrate this, consider the following budget:++~ monthly from 2019/01+ expenses:personal $1,000.00+ expenses:personal:electronics $100.00+ liabilities++ With this, monthly budget for electronics is defined to be $100 and+budget for personal expenses is an additional $1000, which implicitly+means that budget for both 'expenses:personal' and 'expenses' is $1100.++ Transactions in 'expenses:personal:electronics' will be counted both+towards its $100 budget and $1100 of 'expenses:personal' , and+transactions in any other subaccount of 'expenses:personal' would be+counted towards only towards the budget of 'expenses:personal'.++ For example, let's consider these transactions:++~ monthly from 2019/01+ expenses:personal $1,000.00+ expenses:personal:electronics $100.00+ liabilities++2019/01/01 Google home hub+ expenses:personal:electronics $90.00+ liabilities $-90.00++2019/01/02 Phone screen protector+ expenses:personal:electronics:upgrades $10.00+ liabilities++2019/01/02 Weekly train ticket+ expenses:personal:train tickets $153.00+ liabilities++2019/01/03 Flowers+ expenses:personal $30.00+ liabilities++ As you can see, we have transactions in+'expenses:personal:electronics:upgrades' and 'expenses:personal:train+tickets', and since both of these accounts are without explicitly+defined budget, these transactions would be counted towards budgets of+'expenses:personal:electronics' and 'expenses:personal' accordingly:++$ hledger balance --budget -M+Budget performance in 2019/01:++ || Jan +===============================++===============================+ expenses || $283.00 [ 26% of $1100.00] + expenses:personal || $283.00 [ 26% of $1100.00] + expenses:personal:electronics || $100.00 [ 100% of $100.00] + liabilities || $-283.00 [ 26% of $-1100.00] +-------------------------------++-------------------------------+ || 0 [ 0] ++ And with '--empty', we can get a better picture of budget allocation+and consumption:++$ hledger balance --budget -M --empty+Budget performance in 2019/01:++ || Jan +========================================++===============================+ expenses || $283.00 [ 26% of $1100.00] + expenses:personal || $283.00 [ 26% of $1100.00] + expenses:personal:electronics || $100.00 [ 100% of $100.00] + expenses:personal:electronics:upgrades || $10.00 + expenses:personal:train tickets || $153.00 + liabilities || $-283.00 [ 26% of $-1100.00] +----------------------------------------++-------------------------------+ || 0 [ 0] ++3.5.10 Output format+--------------------++This command also supports the output destination and output format+options The output formats supported are (in most modes): 'txt', 'csv',+'html', and 'json'.+++File: hledger.info, Node: balancesheet, Next: balancesheetequity, Prev: balance, Up: COMMANDS++3.6 balancesheet+================++balancesheet, bs+This command displays a balance sheet, showing historical ending+balances of asset and liability accounts. (To see equity as well, use+the balancesheetequity command.) Amounts are shown with normal positive+sign, as in conventional financial statements.++ The asset and liability accounts shown are those accounts declared+with the 'Asset' or 'Cash' or 'Liability' type, or otherwise all+accounts under a top-level 'asset' or 'liability' account (case+insensitive, plurals allowed).++ Example:++$ hledger balancesheet+Balance Sheet++Assets:+ $-1 assets+ $1 bank:saving+ $-2 cash+--------------------+ $-1++Liabilities:+ $1 liabilities:debts+--------------------+ $1++Total:+--------------------+ 0++ With a reporting interval, multiple columns will be shown, one for+each report period. As with multicolumn balance reports, you can alter+the report mode with '--change'/'--cumulative'/'--historical'. Normally+balancesheet shows historical ending balances, which is what you need+for a balance sheet; note this means it ignores report begin dates (and+'-T/--row-total', since summing end balances generally does not make+sense). Instead of absolute values percentages can be displayed with+'-%'.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'html', and+(experimental) 'json'.+++File: hledger.info, Node: balancesheetequity, Next: cashflow, Prev: balancesheet, Up: COMMANDS++3.7 balancesheetequity+======================++balancesheetequity, bse+This command displays a balance sheet, showing historical ending+balances of asset, liability and equity accounts. Amounts are shown+with normal positive sign, as in conventional financial statements.++ The asset, liability and equity accounts shown are those accounts+declared with the 'Asset', 'Cash', 'Liability' or 'Equity' type, or+otherwise all accounts under a top-level 'asset', 'liability' or+'equity' account (case insensitive, plurals allowed).++ Example:++$ hledger balancesheetequity+Balance Sheet With Equity++Assets:+ $-2 assets+ $1 bank:saving+ $-3 cash+--------------------+ $-2++Liabilities:+ $1 liabilities:debts+--------------------+ $1++Equity:+ $1 equity:owner+--------------------+ $1++Total:+--------------------+ 0++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'html', and+(experimental) 'json'.+++File: hledger.info, Node: cashflow, Next: check, Prev: balancesheetequity, Up: COMMANDS++3.8 cashflow+============++cashflow, cf+This command displays a cashflow statement, showing the inflows and+outflows affecting "cash" (ie, liquid) assets. Amounts are shown with+normal positive sign, as in conventional financial statements.++ The "cash" accounts shown are those accounts declared with the 'Cash'+type, or otherwise all accounts under a top-level 'asset' account (case+insensitive, plural allowed) which do not have 'fixed', 'investment',+'receivable' or 'A/R' in their name.++ Example:++$ hledger cashflow+Cashflow Statement++Cash flows:+ $-1 assets+ $1 bank:saving+ $-2 cash+--------------------+ $-1++Total:+--------------------+ $-1++ With a reporting interval, multiple columns will be shown, one for+each report period. Normally cashflow shows changes in assets per+period, though as with multicolumn balance reports you can alter the+report mode with '--change'/'--cumulative'/'--historical'. Instead of+absolute values percentages can be displayed with '-%'.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'html', and+(experimental) 'json'.+++File: hledger.info, Node: check, Next: close, Prev: cashflow, Up: COMMANDS++3.9 check+=========++check+Check for various kinds of errors in your data. _experimental_++ hledger provides a number of built-in error checks to help prevent+problems in your data. Some of these are run automatically; or, you can+use this 'check' command to run them on demand, with no output and a+zero exit code if all is well. Some examples:++hledger check # basic checks+hledger check -s # basic + strict checks+hledger check ordereddates uniqueleafnames # basic + specified checks++ Here are the checks currently available:++* Menu:++* Basic checks::+* Strict checks::+* Other checks::+* Addon checks::+++File: hledger.info, Node: Basic checks, Next: Strict checks, Up: check++3.9.1 Basic checks+------------------++These are always run by this command and other commands:++ * *parseable* - data files are well-formed and can be successfully+ parsed++ * *autobalanced* - all transactions are balanced, inferring missing+ amounts where necessary, and possibly converting commodities using+ transaction prices or automatically-inferred transaction prices++ * *assertions* - all balance assertions in the journal are passing.+ (This check can be disabled with '-I'/'--ignore-assertions'.)+++File: hledger.info, Node: Strict checks, Next: Other checks, Prev: Basic checks, Up: check++3.9.2 Strict checks+-------------------++These are always run by this and other commands when '-s'/'--strict' is+used (strict mode):++ * *accounts* - all account names used by transactions have been+ declared++ * *commodities* - all commodity symbols used have been declared+++File: hledger.info, Node: Other checks, Next: Addon checks, Prev: Strict checks, Up: check++3.9.3 Other checks+------------------++These checks can be run by specifying their names as arguments to the+check command:++ * *ordereddates* - transactions are ordered by date (similar to the+ old 'check-dates' command)++ * *uniqueleafnames* - all account leaf names are unique (similar to+ the old 'check-dupes' command)+++File: hledger.info, Node: Addon checks, Prev: Other checks, Up: check++3.9.4 Addon checks+------------------++Some checks are not yet integrated with this command, but are available+as add-on commands in+https://github.com/simonmichael/hledger/tree/master/bin:++ * *hledger-check-tagfiles* - all tag values containing / (a forward+ slash) exist as file paths++ * *hledger-check-fancyassertions* - more complex balance assertions+ are passing++ You could make your own similar scripts to perform custom checks;+Cookbook -> Scripting may be helpful.+++File: hledger.info, Node: close, Next: codes, Prev: check, Up: COMMANDS++3.10 close+==========++close, equity+Prints a "closing balances" transaction and an "opening balances"+transaction that bring account balances to and from zero, respectively.+These can be added to your journal file(s), eg to bring asset/liability+balances forward into a new journal file, or to close out+revenues/expenses to retained earnings at the end of a period.++ You can print just one of these transactions by using the '--close'+or '--open' flag. You can customise their descriptions with the+'--close-desc' and '--open-desc' options.++ One amountless posting to "equity:opening/closing balances" is added+to balance the transactions, by default. You can customise this account+name with '--close-acct' and '--open-acct'; if you specify only one of+these, it will be used for both.++ With '--x/--explicit', the equity posting's amount will be shown.+And if it involves multiple commodities, a posting for each commodity+will be shown, as with the print command.++ With '--interleaved', the equity postings are shown next to the+postings they balance, which makes troubleshooting easier.++ By default, transaction prices in the journal are ignored when+generating the closing/opening transactions. With '--show-costs', this+cost information is preserved ('balance -B' reports will be unchanged+after the transition). Separate postings are generated for each cost in+each commodity. Note this can generate very large journal entries, if+you have many foreign currency or investment transactions.++* Menu:++* close usage::+++File: hledger.info, Node: close usage, Up: close++3.10.1 close usage+------------------++If you split your journal files by time (eg yearly), you will typically+run this command at the end of the year, and save the closing+transaction as last entry of the old file, and the opening transaction+as the first entry of the new file. This makes the files self+contained, so that correct balances are reported no matter which of them+are loaded. Ie, if you load just one file, the balances are initialised+correctly; or if you load several files, the redundant closing/opening+transactions cancel each other out. (They will show up in print or+register reports; you can exclude them with a query like+'not:desc:'(opening|closing) balances''.)++ If you're running a business, you might also use this command to+"close the books" at the end of an accounting period, transferring+income statement account balances to retained earnings. (You may want+to change the equity account name to something like "equity:retained+earnings".)++ By default, the closing transaction is dated yesterday, the balances+are calculated as of end of yesterday, and the opening transaction is+dated today. To close on some other date, use: 'hledger close -e+OPENINGDATE'. Eg, to close/open on the 2018/2019 boundary, use '-e+2019'. You can also use -p or 'date:PERIOD' (any starting date is+ignored).++ Both transactions will include balance assertions for the+closed/reopened accounts. You probably shouldn't use status or realness+filters (like -C or -R or 'status:') with this command, or the generated+balance assertions will depend on these flags. Likewise, if you run+this command with -auto, the balance assertions will probably always+require -auto.++ Examples:++ Carrying asset/liability balances into a new file for 2019:++$ hledger close -f 2018.journal -e 2019 assets liabilities --open+ # (copy/paste the output to the start of your 2019 journal file)+$ hledger close -f 2018.journal -e 2019 assets liabilities --close+ # (copy/paste the output to the end of your 2018 journal file)++ Now:++$ hledger bs -f 2019.journal # one file - balances are correct+$ hledger bs -f 2018.journal -f 2019.journal # two files - balances still correct+$ hledger bs -f 2018.journal not:desc:closing # to see year-end balances, must exclude closing txn++ Transactions spanning the closing date can complicate matters,+breaking balance assertions:++2018/12/30 a purchase made in 2018, clearing the following year+ expenses:food 5+ assets:bank:checking -5 ; [2019/1/2]++ Here's one way to resolve that:++; in 2018.journal:+2018/12/30 a purchase made in 2018, clearing the following year+ expenses:food 5+ liabilities:pending++; in 2019.journal:+2019/1/2 clearance of last year's pending transactions+ liabilities:pending 5 = 0+ assets:checking+++File: hledger.info, Node: codes, Next: commodities, Prev: close, Up: COMMANDS++3.11 codes+==========++codes+List the codes seen in transactions, in the order parsed.++ This command prints the value of each transaction's 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.++ Transactions aren't required to have a code, and missing or empty+codes will not be shown by default. With the '-E'/'--empty' flag, they+will be printed as blank lines.++ You can add a query to select a subset of transactions.++ Examples:++1/1 (123)+ (a) 1++1/1 ()+ (a) 1++1/1+ (a) 1++1/1 (126)+ (a) 1++$ hledger codes+123+124+126++$ hledger codes -E+123+124+++126+++File: hledger.info, Node: commodities, Next: descriptions, Prev: codes, Up: COMMANDS++3.12 commodities+================++commodities+List all commodity/currency symbols used or declared in the journal.+++File: hledger.info, Node: descriptions, Next: diff, Prev: commodities, Up: COMMANDS++3.13 descriptions+=================++descriptions+List the unique descriptions that appear in transactions.++ This command lists the unique descriptions that appear in+transactions, in alphabetic order. You can add a query to select a+subset of transactions.++ Example:++$ hledger descriptions+Store Name+Gas Station | Petrol+Person A+++File: hledger.info, Node: diff, Next: files, Prev: descriptions, Up: COMMANDS++3.14 diff+=========++diff+Compares a particular account's transactions in two input files. It+shows any transactions to this account which are in one file but not in+the other.++ More precisely, for each posting affecting this account in either+file, it looks for a corresponding posting in the other file which posts+the same amount to the same account (ignoring date, description, etc.)+Since postings not transactions are compared, this also works when+multiple bank transactions have been combined into a single journal+entry.++ This is useful eg if you have downloaded an account's 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.++ Examples:++$ 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:+++File: hledger.info, Node: files, Next: help, Prev: diff, Up: COMMANDS++3.15 files+==========++files+List all files included in the journal. With a REGEX argument, only+file names matching the regular expression (case sensitive) are shown.+++File: hledger.info, Node: help, Next: import, Prev: files, Up: COMMANDS++3.16 help+=========++help+Show any of the hledger manuals.++ The 'help' command displays any of the main hledger manuals, in one+of several ways. Run it with no argument to list the manuals, or+provide a full or partial manual name to select one.++ hledger manuals are available in several formats. hledger help will+use the first of these display methods that it finds: info, man, $PAGER,+less, stdout (or when non-interactive, just stdout). You can force a+particular viewer with the '--info', '--man', '--pager', '--cat' flags.++ Examples:++$ hledger help+Please choose a manual by typing "hledger help MANUAL" (a substring is ok).+Manuals: hledger hledger-ui hledger-web journal csv timeclock timedot++$ hledger help h --man++hledger(1) hledger User Manuals hledger(1)++NAME+ hledger - a command-line accounting tool++SYNOPSIS+ hledger [-f FILE] COMMAND [OPTIONS] [ARGS]+ hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]+ hledger++DESCRIPTION+ hledger is a cross-platform program for tracking money, time, or any+...+++File: hledger.info, Node: import, Next: incomestatement, Prev: help, Up: COMMANDS++3.17 import+===========++import+Read new transactions added to each FILE since last run, and add them to+the main journal file. Or with -dry-run, just print the transactions+that would be added. Or with -catchup, just mark all of the FILEs'+transactions as imported, without actually importing any.++ The input files are specified as arguments - no need to write -f+before each one. So eg to add new transactions from all CSV files to+the main journal, it's just: 'hledger import *.csv'++ New transactions are detected in the same way as print -new: by+assuming transactions are always added to the input files in increasing+date order, and by saving '.latest.FILE' state files.++ The -dry-run output is in journal format, so you can filter it, eg to+see only uncategorised transactions:++$ hledger import --dry ... | hledger -f- print unknown --ignore-assertions++* Menu:++* Importing balance assignments::+* Commodity display styles::+++File: hledger.info, Node: Importing balance assignments, Next: Commodity display styles, Up: import++3.17.1 Importing balance assignments+------------------------------------++Entries added by import will have their posting amounts made explicit+(like 'hledger print -x'). This means that any balance assignments in+imported files must be evaluated; but, imported files don't get to see+the main file's account balances. As a result, importing entries with+balance assignments (eg from an institution that provides only balances+and not posting amounts) will probably generate incorrect posting+amounts. To avoid this problem, use print instead of import:++$ hledger print IMPORTFILE [--new] >> $LEDGER_FILE++ (If you think import should leave amounts implicit like print does,+please test it and send a pull request.)+++File: hledger.info, Node: Commodity display styles, Prev: Importing balance assignments, Up: import++3.17.2 Commodity display styles+-------------------------------++Imported amounts will be formatted according to the canonical commodity+styles (declared or inferred) in the main journal file.+++File: hledger.info, Node: incomestatement, Next: notes, Prev: import, Up: COMMANDS++3.18 incomestatement+====================++incomestatement, is++ This command displays an income statement, showing revenues and+expenses during one or more periods. Amounts are shown with normal+positive sign, as in conventional financial statements.++ The revenue and expense accounts shown are those accounts declared+with the 'Revenue' or 'Expense' type, or otherwise all accounts under a+top-level 'revenue' or 'income' or 'expense' account (case insensitive,+plurals allowed).++ Example:++$ hledger incomestatement+Income Statement++Revenues:+ $-2 income+ $-1 gifts+ $-1 salary+--------------------+ $-2++Expenses:+ $2 expenses+ $1 food+ $1 supplies+--------------------+ $2++Total:+--------------------+ 0++ With a reporting interval, multiple columns will be shown, one for+each report period. Normally incomestatement shows revenues/expenses+per period, though as with multicolumn balance reports you can alter the+report mode with '--change'/'--cumulative'/'--historical'. Instead of+absolute values percentages can be displayed with '-%'.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'html', and+(experimental) 'json'.+++File: hledger.info, Node: notes, Next: payees, Prev: incomestatement, Up: COMMANDS++3.19 notes+==========++notes+List the unique notes that appear in transactions.++ 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).++ Example:++$ hledger notes+Petrol+Snacks+++File: hledger.info, Node: payees, Next: prices, Prev: notes, Up: COMMANDS++3.20 payees+===========++payees+List the unique payee/payer names that appear in transactions.++ This command lists the unique payee/payer names that appear in+transactions, in alphabetic order. You can add a query to select a+subset of transactions. The payee/payer is the part of the transaction+description before a | character (or if there is no |, the whole+description).++ Example:++$ hledger payees+Store Name+Gas Station+Person A+++File: hledger.info, Node: prices, Next: print, Prev: payees, Up: COMMANDS++3.21 prices+===========++prices+Print market price directives from the journal. With -costs, also print+synthetic market prices based on transaction prices. With+-inverted-costs, also print inverse prices based on transaction prices.+Prices (and postings providing prices) can be filtered by a query.+Price amounts are always displayed with their full precision.+++File: hledger.info, Node: print, Next: print-unique, Prev: prices, Up: COMMANDS++3.22 print+==========++print, txns, p+Show transaction journal entries, sorted by date.++ The print command displays full journal entries (transactions) from+the journal file in date order, tidily formatted. With -date2,+transactions are sorted by secondary date instead.++ print's output is always a valid hledger journal.+It preserves all transaction information, but it does not preserve+directives or inter-transaction comments++$ hledger print+2008/01/01 income+ assets:bank:checking $1+ income:salary $-1++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++2008/12/31 * pay off+ liabilities:debts $1+ assets:bank:checking $-1++ Normally, the journal entry's explicit or implicit amount style is+preserved. For example, when an amount is omitted in the journal, it+will not appear in the output. Similarly, when a transaction price is+implied but not written, it will not appear in the output. You can use+the '-x'/'--explicit' flag to make all amounts and transaction prices+explicit, which can be useful for troubleshooting or for making your+journal more readable and robust against data entry errors. '-x' is+also implied by using any of '-B','-V','-X','--value'.++ Note, '-x'/'--explicit' will cause postings with a multi-commodity+amount (these can arise when a multi-commodity transaction has an+implicit amount) to be split into multiple single-commodity postings,+keeping the output parseable.++ With '-B'/'--cost', amounts with transaction prices are converted to+cost using that price. This can be used for troubleshooting.++ With '-m'/'--match' and a STR argument, print will show at most one+transaction: the one one whose description is most similar to STR, and+is most recent. STR should contain at least two characters. If there+is no similar-enough match, no transaction will be shown.++ With '--new', for each FILE being read, hledger reads (and writes) a+special state file ('.latest.FILE' in the same directory), containing+the latest transaction date(s) that were seen last time FILE was read.+When this file is found, only transactions with newer dates (and new+transactions on the latest date) are printed. This is useful for+ignoring already-seen entries in import data, such as downloaded CSV+files. Eg:++$ hledger -f bank1.csv print --new+(shows transactions added since last print --new on this file)++ This assumes that transactions added to FILE always have same or+increasing dates, and that transactions on the same day do not get+reordered. See also the import command.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', and+(experimental) 'json' and 'sql'.++ Here's an example of print's CSV output:++$ hledger print -Ocsv+"txnidx","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","posting-status","posting-comment"+"1","2008/01/01","","","","income","","assets:bank:checking","1","$","","1","",""+"1","2008/01/01","","","","income","","income:salary","-1","$","1","","",""+"2","2008/06/01","","","","gift","","assets:bank:checking","1","$","","1","",""+"2","2008/06/01","","","","gift","","income:gifts","-1","$","1","","",""+"3","2008/06/02","","","","save","","assets:bank:saving","1","$","","1","",""+"3","2008/06/02","","","","save","","assets:bank:checking","-1","$","1","","",""+"4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","","1","",""+"4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","","1","",""+"4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","2","","",""+"5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","","1","",""+"5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","1","","",""++ * There is one CSV record per posting, with the parent transaction's+ fields repeated.+ * The "txnidx" (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.)+ * The amount is separated into "commodity" (the symbol) and "amount"+ (numeric quantity) fields.+ * The numeric amount is repeated in either the "credit" or "debit"+ column, for convenience. (Those names are not accurate in the+ accounting sense; it just puts negative amounts under credit and+ zero or greater amounts under debit.)+++File: hledger.info, Node: print-unique, Next: register, Prev: print, Up: COMMANDS++3.23 print-unique+=================++print-unique+Print transactions which do not reuse an already-seen description.++ Example:++$ cat unique.journal+1/1 test+ (acct:one) 1+2/2 test+ (acct:two) 2+$ LEDGER_FILE=unique.journal hledger print-unique+(-f option not supported)+2015/01/01 test+ (acct:one) 1+++File: hledger.info, Node: register, Next: register-match, Prev: print-unique, Up: COMMANDS++3.24 register+=============++register, reg, r+Show postings and their running total.++ The register command displays matched postings, across all accounts,+in date order, with their running total or running historical balance.+(See also the 'aregister' command, which shows matched transactions in a+specific account.)++ register normally shows line per posting, but note that+multi-commodity amounts will occupy multiple lines (one line per+commodity).++ It is typically used with a query selecting a particular account, to+see that account's activity:++$ 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++ With -date2, it shows and sorts by secondary date instead.++ The '--historical'/'-H' 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:++$ 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++ The '--depth' option limits the amount of sub-account detail+displayed.++ The '--average'/'-A' 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 '--empty' (see+below). It is affected by '--historical'. It works best when showing+just one account and one commodity.++ The '--related'/'-r' flag shows the _other_ postings in the+transactions of the postings which would normally be shown.++ The '--invert' flag negates all amounts. For example, it can be used+on an income account where amounts are normally displayed as negative+numbers. It's also useful to show postings on the checking account+together with the related account:++$ hledger register --related --invert assets:checking++ With a reporting interval, register shows summary postings, one per+interval, aggregating the postings to each account:++$ hledger register --monthly income+2008/01 income:salary $-1 $-1+2008/06 income:gifts $-1 $-2++ Periods with no activity, and summary postings with a zero amount,+are not shown by default; use the '--empty'/'-E' flag to see them:++$ 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++ Often, you'll want to see just one line per interval. The '--depth'+option helps with this, causing subaccounts to be aggregated:++$ hledger register --monthly assets --depth 1h+2008/01 assets $1 $1+2008/06 assets $-1 0+2008/12 assets $-1 $-1++ 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.++* Menu:++* Custom register output::+++File: hledger.info, Node: Custom register output, Up: register++3.24.1 Custom register output+-----------------------------++register uses the full terminal width by default, except on windows.+You can override this by setting the 'COLUMNS' environment variable (not+a bash shell variable) or by using the '--width'/'-w' option.++ 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's argument, comma-separated:+'--width W,D' . Here's a diagram (won't display correctly in -help):++<--------------------------------- width (W) ---------------------------------->+date (10) description (D) account (W-41-D) amount (12) balance (12)+DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA++ and some examples:++$ hledger reg # use terminal width (or 80 on windows)+$ hledger reg -w 100 # use width 100+$ COLUMNS=100 hledger reg # set with one-time environment variable+$ export COLUMNS=100; hledger reg # set till session end (or window resize)+$ hledger reg -w 100,40 # set overall width 100, description width 40+$ hledger reg -w $COLUMNS,40 # use terminal width, & description width 40++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', and+(experimental) 'json'.+++File: hledger.info, Node: register-match, Next: rewrite, Prev: register, Up: COMMANDS++3.25 register-match+===================++register-match+Print the one posting whose transaction description is closest to DESC,+in the style of the register command. If there are multiple equally+good matches, it shows the most recent. Query options (options, not+arguments) can be used to restrict the search space. Helps+ledger-autosync detect already-seen transactions when importing.+++File: hledger.info, Node: rewrite, Next: roi, Prev: register-match, Up: COMMANDS++3.26 rewrite+============++rewrite+Print all transactions, rewriting the postings of matched transactions.+For now the only rewrite available is adding new postings, like print+-auto.++ 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's first posting amount.++ Examples:++$ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'+$ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'+$ hledger-rewrite.hs -f rewrites.hledger++ rewrites.hledger may consist of entries like:++= ^income 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++ Note the single quotes to protect the dollar sign from bash, and the+two spaces between account and amount.++ More:++$ hledger rewrite -- [QUERY] --add-posting "ACCT AMTEXPR" ...+$ hledger rewrite -- ^income --add-posting '(liabilities:tax) *.33'+$ hledger rewrite -- expenses:gifts --add-posting '(budget:gifts) *-1"'+$ hledger rewrite -- ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'++ Argument for '--add-posting' option is a usual posting of transaction+with an exception for amount specification. More precisely, you can use+''*'' (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's+commodity.++* Menu:++* Re-write rules in a file::+++File: hledger.info, Node: Re-write rules in a file, Up: rewrite++3.26.1 Re-write rules in a file+-------------------------------++During the run this tool will execute so called "Automated Transactions"+found in any journal it process. I.e instead of specifying this+operations in command line you can put them in a journal file.++$ rewrite-rules.journal++ Make contents look like this:++= ^income+ (liabilities:tax) *.33++= expenses:gifts+ budget:gifts *-1+ assets:budget *1++ Note that ''='' (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.++$ hledger rewrite -- -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal++ This is something similar to the commands pipeline:++$ hledger rewrite -- -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \+ | hledger rewrite -- -f - expenses:gifts --add-posting 'budget:gifts *-1' \+ --add-posting 'assets:budget *1' \+ > rewritten-tidy-output.journal++ It is important to understand that relative order of such entries in+journal is important. You can re-use result of previously added+postings.++* Menu:++* Diff output format::+* rewrite vs print --auto::+++File: hledger.info, Node: Diff output format, Next: rewrite vs print --auto, Up: Re-write rules in a file++3.26.1.1 Diff output format+...........................++To use this tool for batch modification of your journal files you may+find useful output in form of unified diff.++$ hledger rewrite -- --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'++ Output might look like:++--- /tmp/examples/sample.journal++++ /tmp/examples/sample.journal+@@ -18,3 +18,4 @@+ 2008/01/01 income+- assets:bank:checking $1++ assets:bank:checking $1+ income:salary++ (liabilities:tax) 0+@@ -22,3 +23,4 @@+ 2008/06/01 gift+- assets:bank:checking $1++ assets:bank:checking $1+ income:gifts++ (liabilities:tax) 0++ If you'll pass this through 'patch' tool you'll 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 '--file' options and 'include' directives inside of these+files.++ Be careful. Whole transaction being re-formatted in a style of+output from 'hledger print'.++ See also:++ https://github.com/simonmichael/hledger/issues/99+++File: hledger.info, Node: rewrite vs print --auto, Prev: Diff output format, Up: Re-write rules in a file++3.26.1.2 rewrite vs. print -auto+................................++This command predates print -auto, and currently does much the same+thing, but with these differences:++ * with multiple files, rewrite lets rules in any file affect all+ other files. print -auto uses standard directive scoping; rules+ affect only child files.++ * rewrite's query limits which transactions can be rewritten; all are+ printed. print -auto's query limits which transactions are+ printed.++ * rewrite applies rules specified on command line or in the journal.+ print -auto applies rules specified in the journal.+++File: hledger.info, Node: roi, Next: stats, Prev: rewrite, Up: COMMANDS++3.27 roi+========++roi+Shows the time-weighted (TWR) and money-weighted (IRR) rate of return on+your investments.++ This command assumes that you have account(s) that hold nothing but+your investments and whenever you record current appraisal/valuation of+these investments you offset unrealized profit and loss into account(s)+that, again, hold nothing but unrealized profit and loss.++ Any transactions affecting balance of investment account(s) and not+originating from unrealized profit and loss account(s) are assumed to be+your investments or withdrawals.++ At a minimum, you need to supply a query (which could be just an+account name) to select your investments with '--inv', and another query+to identify your profit and loss transactions with '--pnl'.++ This command will compute and display the internalized rate of return+(IRR) and time-weighted rate of return (TWR) for your investments for+the time period requested. Both rates of return are annualized before+display, regardless of the length of reporting interval.++ Note, in some cases this report can fail, for these reasons:++ * Error (NotBracketed): No solution for Internal Rate of Return+ (IRR). Possible causes: IRR is huge (>1000000%), balance of+ investment becomes negative at some point in time.+ * Error (SearchFailed): Failed to find solution for Internal Rate of+ Return (IRR). Either search does not converge to a solution, or+ converges too slowly.++ Examples:++ * Using roi to report unrealised gains:+ https://github.com/simonmichael/hledger/blob/master/examples/roi-unrealised.ledger++ More background:++ "ROI" stands for "return on investment". Traditionally this was+computed as a difference between current value of investment and its+initial value, expressed in percentage of the initial value.++ However, this approach is only practical in simple cases, where+investments receives no in-flows or out-flows of money, and where 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.++ Internal rate of return, or "IRR" (also called "money-weighted rate+of return") takes into account effects of in-flows and out-flows.+Naively, if you are withdrawing from your investment, your future gains+would be smaller (in absolute numbers), and will be a smaller percentage+of your initial investment, and if you are adding to your investment,+you will receive bigger absolute gains (but probably at the same rate of+return). IRR is a way to compute rate of return for each period between+in-flow or out-flow of money, and then combine them in a way that gives+you an annual rate of return that investment is expected to generate.++ As mentioned before, in-flows and out-flows would be any cash that+you personally put in or withdraw, and for the "roi" command, these are+transactions that involve account(s) matching '--inv' argument and NOT+involve account(s) matching '--pnl' argument.++ Presumably, you will also record changes in the value of your+investment, and balance them against "profit and loss" (or "unrealized+gains") account. Note that in order for IRR to compute the precise+effect of your in-flows and out-flows on the rate of return, you will+need to record the value of your investement on or close to the days+when in- or out-flows occur.++ Implementation of IRR in hledger should match the 'XIRR' formula in+Excel.++ Second way to compute rate of return that 'roi' command implements is+called "time-weighted rate of return" or "TWR". Like IRR, it will also+break the history of your investment into periods between in-flows and+out-flows to compute rate of return per each period and then a compound+rate of return. However, internal workings of TWR are quite different.++ In technical terms, IRR uses the same approach as computation of net+present value, and tries to find a discount rate that makes net present+value of all the cash flows of your investment to add up to zero. This+could be hard to wrap your head around, especially if you haven't done+discounted cash flow analysis before.++ TWR represents your investment as an imaginary "unit fund" where+in-flows/ out-flows lead to buying or selling "units" of your investment+and changes in its value change the value of "investment unit". Change+in "unit price" over the reporting period gives you rate of return of+your investment.++ References: * Explanation of rate of return * Explanation of IRR *+Explanation of TWR * Examples of computing IRR and TWR and discussion of+the limitations of both metrics++ More examples:++ Lets say that we found an investment in Snake Oil that is proising to+give us 10% annually:++2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-12-24 Recording the growth of Snake Oil+ investment:snake oil = $110+ equity:unrealized gains++ For now, basic computation of the rate of return, as well as IRR and+TWR, gives us the expected 10%:++$ hledger roi -Y --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+-----++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 110 | 10 || 10.00% | 10.00% |++---++------------+------------++---------------+----------+-------------+-----++--------+--------+++ However, lets say that shorty after investing in the Snake Oil we+started to have second thoughs, so we prompty withdrew $90, leaving only+$10 in. Before Christmas, though, we started to get the "fear of+mission out", so we put the $90 back in. So for most of the year, our+investment was just $10 dollars, and it gave us just $1 in growth:++2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil+ +2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil = $101+ equity:unrealized gains++ Now IRR and TWR are drastically different:++$ hledger roi -Y --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+-----++-------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++=======+=======++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101 | 1 || 9.32% | 1.00% |++---++------------+------------++---------------+----------+-------------+-----++-------+-------+++ Here, IRR tells us that we made close to 10% on the $10 dollars that+we had in the account most of the time. And TWR is ... just 1%? Why?++ Based on the transactions in our journal, TWR "think" that we are+buying back $90 worst of Snake Oil at the same price that it had at the+beginning of they year, and then after that our $100 investment gets $1+increase in value, or 1% of $100. Let's take a closer look at what is+happening here by asking for quarterly reports instead of annual:++$ hledger roi -Q --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+-----++--------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+=======++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10 | 0 || 0.00% | 0.00% |+| 2 || 2019-04-01 | 2019-06-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 3 || 2019-07-01 | 2019-09-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 4 || 2019-10-01 | 2019-12-31 || 10 | 90 | 101 | 1 || 37.80% | 4.03% |++---++------------+------------++---------------+----------+-------------+-----++--------+-------+++ Now both IRR and TWR are thrown off by the fact that all of the+growth for our investment happens in Q4 2019. This happes because IRR+computation is still yielding 9.32% and TWR is still 1%, but this time+these are rates for three month period instead of twelve, so in order to+get an annual rate they should be multiplied by four!++ Let's try to keep a better record of how Snake Oil grew in value:++2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil++2019-02-28 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-06-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-09-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ Would our quartery report look better now? Almost:++$ hledger roi -Q --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 1.00% |++---++------------+------------++---------------+----------+-------------+------++--------+--------+++ Something is still wrong with TWR computation for Q4, and if you have+been paying attention you know what it is already: big $90 buy-back is+recorded prior to the only transaction that captures the change of value+of Snake Oil that happened in this time period. Lets combine+transactions from 30th and 31st of Dec into one:++2019-12-30 Fear of missing out and growth of Snake Oil+ assets:cash -$90+ investment:snake oil+ equity:unrealized gains -$0.25++ Now growth of investment properly affects its price at the time of+buy-back:++$ hledger roi -Q --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 9.57% |++---++------------+------------++---------------+----------+-------------+------++--------+--------+++ And for annual report, TWR now reports the exact profitability of our+investment:++$ hledger roi -Y --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+------++-------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++=======+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101.00 | 1.00 || 9.32% | 10.00% |++---++------------+------------++---------------+----------+-------------+------++-------+--------++++File: hledger.info, Node: stats, Next: tags, Prev: roi, Up: COMMANDS++3.28 stats+==========++stats+Show some journal statistics.++ The stats command displays summary information for the whole journal,+or a matched part of it. With a reporting interval, it shows a report+for each report period.++ Example:++$ hledger stats+Main journal file : /src/hledger/examples/sample.journal+Included journal files : +Transactions span : 2008-01-01 to 2009-01-01 (366 days)+Last transaction : 2008-12-31 (2333 days ago)+Transactions : 5 (0.0 per day)+Transactions last 30 days: 0 (0.0 per day)+Transactions last 7 days : 0 (0.0 per day)+Payees/descriptions : 5+Accounts : 8 (depth 3)+Commodities : 1 ($)+Market prices : 12 ($)++ This command also supports output destination and output format+selection.+++File: hledger.info, Node: tags, Next: test, Prev: stats, Up: COMMANDS++3.29 tags+=========++tags+List the unique tag names used in the journal. With a TAGREGEX+argument, only tag names matching the regular expression (case+insensitive) are shown. With QUERY arguments, only transactions+matching the query are considered.++ With the -values flag, the tags' unique values are listed instead.++ With -parsed flag, all tags or values are shown in the order they are+parsed from the input data, including duplicates.++ With -E/-empty, any blank/empty values will also be shown, otherwise+they are omitted.+++File: hledger.info, Node: test, Next: Add-on commands, Prev: tags, Up: COMMANDS++3.30 test+=========++test+Run built-in unit tests.++ This command runs the unit tests built in to hledger and hledger-lib,+printing the results on stdout. If any test fails, the exit code will+be non-zero.++ This is mainly used by hledger developers, but you can also use it to+sanity-check the installed hledger executable on your platform. All+tests are expected to pass - if you ever see a failure, please report as+a bug!++ This command also accepts tasty test runner options, written after a+- (double hyphen). Eg to run only the tests in Hledger.Data.Amount,+with ANSI colour codes disabled:++$ hledger test -- -pData.Amount --color=never++ For help on these, see https://github.com/feuerbach/tasty#options+('-- --help' currently doesn't show them).+++File: hledger.info, Node: Add-on commands, Prev: test, Up: COMMANDS++3.31 Add-on commands+====================++hledger also searches for external add-on commands, and will include+these in the commands list. These are programs or scripts in your PATH+whose name starts with 'hledger-' and ends with a recognised file+extension (currently: no extension, 'bat','com','exe',+'hs','lhs','pl','py','rb','rkt','sh').++ Add-ons can be invoked like any hledger command, but there are a few+things to be aware of. Eg if the 'hledger-web' add-on is installed,++ * 'hledger -h web' shows hledger's help, while 'hledger web -h' shows+ hledger-web's help.++ * Flags specific to the add-on must have a preceding '--' to hide+ them from hledger. So 'hledger web --serve --port 9000' will be+ rejected; you must use 'hledger web -- --serve --port 9000'.++ * You can always run add-ons directly if preferred: 'hledger-web+ --serve --port 9000'.++ Add-ons are a relatively easy way to add local features or experiment+with new ideas. They can be written in any language, but haskell+scripts have a big advantage: they can use the same hledger (and+haskell) library functions that built-in commands do, for command-line+options, journal parsing, reporting, etc.++ Two important add-ons are the hledger-ui and hledger-web user+interfaces. These are maintained and released along with hledger:++* Menu:++* ui::+* web::+* iadd::+* interest::+++File: hledger.info, Node: ui, Next: web, Up: Add-on commands++3.31.1 ui+---------++hledger-ui provides an efficient terminal interface.+++File: hledger.info, Node: web, Next: iadd, Prev: ui, Up: Add-on commands++3.31.2 web+----------++hledger-web provides a simple web interface.++ Third party add-ons, maintained separately from hledger, include:+++File: hledger.info, Node: iadd, Next: interest, Prev: web, Up: Add-on commands++3.31.3 iadd+-----------++hledger-iadd is a more interactive, terminal UI replacement for the add+command.+++File: hledger.info, Node: interest, Prev: iadd, Up: Add-on commands++3.31.4 interest+---------------++hledger-interest generates interest transactions for an account+according to various schemes.++ A few more experimental or old add-ons can be found in hledger's bin/+directory. These are typically prototypes and not guaranteed to work.+++File: hledger.info, Node: ENVIRONMENT, Next: FILES, Prev: COMMANDS, Up: Top++4 ENVIRONMENT+*************++*LEDGER_FILE* The journal file path when not specified with '-f'.+Default: '~/.hledger.journal' (on windows, perhaps+'C:/Users/USER/.hledger.journal').++ A typical value is '~/DIR/YYYY.journal', where DIR is a+version-controlled finance directory and YYYY is the current year. Or+'~/DIR/current.journal', where current.journal is a symbolic link to+YYYY.journal.++ On Mac computers, you can set this and other environment variables in+a more thorough way that also affects applications started from the GUI+(say, an Emacs dock icon). Eg on MacOS Catalina I have a+'~/.MacOSX/environment.plist' file containing++{+ "LEDGER_FILE" : "~/finance/current.journal"+}++ To see the effect you may need to 'killall Dock', or reboot.++ *COLUMNS* The screen width used by the register command. Default:+the full terminal width.++ *NO_COLOR* If this variable exists with any value, hledger will not+use ANSI color codes in terminal output. This overrides the+-color/-colour option.+++File: hledger.info, Node: FILES, Next: LIMITATIONS, Prev: ENVIRONMENT, Up: Top++5 FILES+*******++Reads data from one or more files in hledger journal, timeclock,+timedot, or CSV format specified with '-f', or '$LEDGER_FILE', or+'$HOME/.hledger.journal' (on windows, perhaps+'C:/Users/USER/.hledger.journal').+++File: hledger.info, Node: LIMITATIONS, Next: TROUBLESHOOTING, Prev: FILES, Up: Top++6 LIMITATIONS+*************++The need to precede addon command options with '--' when invoked from+hledger is awkward.++ When input data contains non-ascii characters, a suitable system+locale must be configured (or there will be an unhelpful error). Eg on+POSIX, set LANG to something other than C.++ In a Microsoft Windows CMD window, non-ascii characters and colours+are not supported.++ On Windows, non-ascii characters may not display correctly when+running a hledger built in CMD in MSYS/CYGWIN, or vice-versa.++ In a Cygwin/MSYS/Mintty window, the tab key is not supported in+hledger add.++ Not all of Ledger's journal file syntax is supported. See file+format differences.++ On large data files, hledger is slower and uses more memory than+Ledger.+++File: hledger.info, Node: TROUBLESHOOTING, Prev: LIMITATIONS, Up: Top++7 TROUBLESHOOTING+*****************++Here are some issues you might encounter when you run hledger (and+remember you can also seek help from the IRC channel, mail list or bug+tracker):++ *Successfully installed, but "No command 'hledger' found"*+stack and cabal install binaries into a special directory, which should+be added to your PATH environment variable. Eg on unix-like systems,+that is ~/.local/bin and ~/.cabal/bin respectively.++ *I set a custom LEDGER_FILE, but hledger is still using the default+file*+'LEDGER_FILE' should be a real environment variable, not just a shell+variable. The command 'env | grep LEDGER_FILE' should show it. You may+need to use 'export'. Here's an explanation.++ *Getting errors like "Illegal byte sequence" or "Invalid or+incomplete multibyte or wide character" or "commitAndReleaseBuffer:+invalid argument (invalid character)"*+Programs compiled with GHC (hledger, haskell build tools, etc.) need to+have a UTF-8-aware locale configured in the environment, otherwise they+will fail with these kinds of errors when they encounter non-ascii+characters.++ To fix it, set the LANG environment variable to some locale which+supports UTF-8. The locale you choose must be installed on your system.++ Here's an example of setting LANG temporarily, on Ubuntu GNU/Linux:++$ file my.journal+my.journal: UTF-8 Unicode text # the file is UTF8-encoded+$ echo $LANG+C # LANG is set to the default locale, which does not support UTF8+$ locale -a # which locales are installed ?+C+en_US.utf8 # here's a UTF8-aware one we can use+POSIX+$ LANG=en_US.utf8 hledger -f my.journal print # ensure it is used for this command++ If available, 'C.UTF-8' will also work. If your preferred locale+isn't listed by 'locale -a', you might need to install it. Eg on+Ubuntu/Debian:++$ apt-get install language-pack-fr+$ locale -a+C+en_US.utf8+fr_BE.utf8+fr_CA.utf8+fr_CH.utf8+fr_FR.utf8+fr_LU.utf8+POSIX+$ LANG=fr_FR.utf8 hledger -f my.journal print++ Here's how you could set it permanently, if you use a bash shell:++$ echo "export LANG=en_US.utf8" >>~/.bash_profile+$ bash --login++ Exact spelling and capitalisation may be important. Note the+difference on MacOS ('UTF-8', not 'utf8'). Some platforms (eg ubuntu)+allow variant spellings, but others (eg macos) require it to be exact:++$ locale -a | grep -iE en_us.*utf+en_US.UTF-8+$ LANG=en_US.UTF-8 hledger -f my.journal print+++Tag Table:+Node: Top68+Node: COMMON TASKS2315+Ref: #common-tasks2427+Node: Getting help2834+Ref: #getting-help2966+Node: Constructing command lines3519+Ref: #constructing-command-lines3711+Node: Starting a journal file4408+Ref: #starting-a-journal-file4606+Node: Setting opening balances5794+Ref: #setting-opening-balances5990+Node: Recording transactions9131+Ref: #recording-transactions9311+Node: Reconciling9867+Ref: #reconciling10010+Node: Reporting12267+Ref: #reporting12407+Node: Migrating to a new file16406+Ref: #migrating-to-a-new-file16554+Node: OPTIONS16853+Ref: #options16960+Node: General options17346+Ref: #general-options17471+Node: Command options20872+Ref: #command-options21023+Node: Command arguments21421+Ref: #command-arguments21568+Node: Queries22448+Ref: #queries22603+Node: Special characters in arguments and queries26565+Ref: #special-characters-in-arguments-and-queries26793+Node: More escaping27244+Ref: #more-escaping27406+Node: Even more escaping27702+Ref: #even-more-escaping27896+Node: Less escaping28567+Ref: #less-escaping28729+Node: Unicode characters28974+Ref: #unicode-characters29156+Node: Input files30568+Ref: #input-files30704+Node: Strict mode33003+Ref: #strict-mode33139+Node: Output destination33787+Ref: #output-destination33939+Node: Output format34364+Ref: #output-format34516+Node: Regular expressions36683+Ref: #regular-expressions36840+Node: Smart dates38576+Ref: #smart-dates38727+Node: Report start & end date40088+Ref: #report-start-end-date40260+Node: Report intervals41757+Ref: #report-intervals41922+Node: Period expressions42312+Ref: #period-expressions42472+Node: Depth limiting46845+Ref: #depth-limiting46989+Node: Pivoting47321+Ref: #pivoting47444+Node: Valuation49120+Ref: #valuation49222+Node: -B Cost49911+Ref: #b-cost50015+Node: -V Value50148+Ref: #v-value50294+Node: -X Value in specified commodity50489+Ref: #x-value-in-specified-commodity50688+Node: Valuation date50837+Ref: #valuation-date51005+Node: Market prices51427+Ref: #market-prices51607+Node: --infer-value market prices from transactions52549+Ref: #infer-value-market-prices-from-transactions52798+Node: Valuation commodity54080+Ref: #valuation-commodity54289+Node: Simple valuation examples55515+Ref: #simple-valuation-examples55717+Node: --value Flexible valuation56376+Ref: #value-flexible-valuation56584+Node: More valuation examples58531+Ref: #more-valuation-examples58740+Node: Effect of valuation on reports60745+Ref: #effect-of-valuation-on-reports60933+Node: COMMANDS67952+Ref: #commands68060+Node: accounts69146+Ref: #accounts69244+Node: activity69943+Ref: #activity70053+Node: add70436+Ref: #add70537+Node: aregister73330+Ref: #aregister73442+Node: aregister and custom posting dates74815+Ref: #aregister-and-custom-posting-dates74988+Ref: #output-format-175581+Node: balance75986+Ref: #balance76103+Node: Classic balance report77583+Ref: #classic-balance-report77756+Node: Customising the classic balance report79080+Ref: #customising-the-classic-balance-report79308+Node: Colour support81384+Ref: #colour-support81551+Node: Flat mode81647+Ref: #flat-mode81795+Node: Depth limited balance reports82208+Ref: #depth-limited-balance-reports82393+Node: Percentages82849+Ref: #percentages83006+Node: Sorting by amount84143+Ref: #sorting-by-amount84309+Node: Multicolumn balance report84803+Ref: #multicolumn-balance-report84989+Node: Budget report90586+Ref: #budget-report90729+Node: Budget report start date96018+Ref: #budget-report-start-date96183+Node: Nested budgets97515+Ref: #nested-budgets97660+Ref: #output-format-2101143+Node: balancesheet101304+Ref: #balancesheet101440+Node: balancesheetequity102952+Ref: #balancesheetequity103101+Node: cashflow104177+Ref: #cashflow104299+Node: check105515+Ref: #check105618+Node: Basic checks106222+Ref: #basic-checks106338+Node: Strict checks106831+Ref: #strict-checks106970+Node: Other checks107213+Ref: #other-checks107350+Node: Addon checks107648+Ref: #addon-checks107763+Node: close108216+Ref: #close108318+Node: close usage109840+Ref: #close-usage109933+Node: codes112746+Ref: #codes112854+Node: commodities113566+Ref: #commodities113693+Node: descriptions113775+Ref: #descriptions113903+Node: diff114207+Ref: #diff114313+Node: files115360+Ref: #files115460+Node: help115607+Ref: #help115707+Node: import116788+Ref: #import116902+Node: Importing balance assignments117824+Ref: #importing-balance-assignments118005+Node: Commodity display styles118654+Ref: #commodity-display-styles118825+Node: incomestatement118954+Ref: #incomestatement119087+Node: notes120432+Ref: #notes120545+Node: payees120913+Ref: #payees121019+Node: prices121439+Ref: #prices121545+Node: print121886+Ref: #print121996+Node: print-unique126792+Ref: #print-unique126918+Node: register127203+Ref: #register127330+Node: Custom register output131779+Ref: #custom-register-output131908+Node: register-match133245+Ref: #register-match133379+Node: rewrite133730+Ref: #rewrite133845+Node: Re-write rules in a file135700+Ref: #re-write-rules-in-a-file135834+Node: Diff output format137044+Ref: #diff-output-format137213+Node: rewrite vs print --auto138305+Ref: #rewrite-vs.-print---auto138484+Node: roi139040+Ref: #roi139138+Node: stats151348+Ref: #stats151447+Node: tags152235+Ref: #tags152333+Node: test152852+Ref: #test152960+Node: Add-on commands153707+Ref: #add-on-commands153824+Node: ui155167+Ref: #ui155255+Node: web155309+Ref: #web155412+Node: iadd155528+Ref: #iadd155639+Node: interest155721+Ref: #interest155828+Node: ENVIRONMENT156068+Ref: #environment156180+Node: FILES157165+Ref: #files-1157268+Node: LIMITATIONS157481+Ref: #limitations157600+Node: TROUBLESHOOTING158342+Ref: #troubleshooting158455 End Tag Table
embeddedfiles/hledger.txt view
@@ -464,3000 +464,3381 @@ disable balance assertion checks (note: does not disable balance assignments) - General reporting options:-- -b --begin=DATE- include postings/txns on or after this date-- -e --end=DATE- include postings/txns before this date-- -D --daily- multiperiod/multicolumn report by day-- -W --weekly- multiperiod/multicolumn report by week-- -M --monthly- multiperiod/multicolumn report by month-- -Q --quarterly- multiperiod/multicolumn report by quarter-- -Y --yearly- multiperiod/multicolumn report by year-- -p --period=PERIODEXP- set start date, end date, and/or reporting interval all at once- using period expressions syntax-- --date2- match the secondary date instead (see command help for other ef-- fects)-- -U --unmarked- include only unmarked postings/txns (can combine with -P or -C)-- -P --pending- include only pending postings/txns-- -C --cleared- include only cleared postings/txns-- -R --real- include only non-virtual postings-- -NUM --depth=NUM- hide/aggregate accounts or postings more than NUM levels deep-- -E --empty- show items with zero amount, normally hidden (and vice-versa in- hledger-ui/hledger-web)-- -B --cost- convert amounts to their cost/selling amount at transaction time-- -V --market- convert amounts to their market value in default valuation com-- modities-- -X --exchange=COMM- convert amounts to their market value in commodity COMM-- --value- convert amounts to cost or market value, more flexibly than- -B/-V/-X-- --infer-value- with -V/-X/--value, also infer market prices from transactions-- --auto apply automated posting rules to modify transactions.-- --forecast- generate future transactions from periodic transaction rules,- for the next 6 months or till report end date. In hledger-ui,- also make ordinary future transactions visible.-- --color=WHEN (or --colour=WHEN)- Should color-supporting commands use ANSI color codes in text- output. 'auto' (default): whenever stdout seems to be a color-- supporting terminal. 'always' or 'yes': always, useful eg when- piping output into 'less -R'. 'never' or 'no': never. A- NO_COLOR environment variable overrides this.-- When a reporting option appears more than once in the command line, the- last one takes precedence.-- Some reporting options can also be written as query arguments.-- Command options- To see options for a particular command, including command-specific op-- tions, run: hledger COMMAND -h.-- Command-specific options must be written after the command name, eg:- hledger print -x.-- Additionally, if the command is an addon, you may need to put its op-- tions after a double-hyphen, eg: hledger ui -- --watch. Or, you can- run the addon executable directly: hledger-ui --watch.-- Command arguments- Most hledger commands accept arguments after the command name, which- are often a query, filtering the data in some way.-- You can save a set of command line options/arguments in a file, and- then reuse them by writing @FILENAME as a command line argument. Eg:- hledger bal @foo.args. (To prevent this, eg if you have an argument- that begins with a literal @, precede it with --, eg: hledger bal --- @ARG).-- Inside the argument file, each line should contain just one option or- argument. Avoid the use of spaces, except inside quotes (or you'll see- a confusing error). Between a flag and its argument, use = (or noth-- ing). Bad:-- assets depth:2- -X USD-- Good:-- assets- depth:2- -X=USD-- For special characters (see below), use one less level of quoting than- you would at the command prompt. Bad:-- -X"$"-- Good:-- -X$-- See also: Save frequently used options.-- Queries- One of hledger's strengths is being able to quickly report on precise- subsets of your data. Most commands accept an optional query expres-- sion, written as arguments after the command name, to filter the data- by date, account name or other criteria. The syntax is similar to a- web search: one or more space-separated search terms, quotes to enclose- whitespace, prefixes to match specific fields, a not: prefix to negate- the match.-- We do not yet support arbitrary boolean combinations of search terms;- instead most commands show transactions/postings/accounts which match- (or negatively match):-- o any of the description terms AND-- o any of the account terms AND-- o any of the status terms AND-- o all the other terms.-- The print command instead shows transactions which:-- o match any of the description terms AND-- o have any postings matching any of the positive account terms AND-- o have no postings matching any of the negative account terms AND-- o match all the other terms.-- The following kinds of search terms can be used. Remember these can- also be prefixed with not:, eg to exclude a particular subaccount.-- REGEX, acct:REGEX- match account names by this regular expression. (With no pre-- fix, acct: is assumed.) same as above-- amt:N, amt:<N, amt:<=N, amt:>N, amt:>=N- match postings with a single-commodity amount that is equal to,- less than, or greater than N. (Multi-commodity amounts are not- tested, and will always match.) 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.-- code:REGEX- match by transaction code (eg check number)-- cur:REGEX- match postings or transactions including any amounts whose cur-- rency/commodity symbol is fully matched by REGEX. (For a par-- tial match, use .*REGEX.*). Note, to match characters which are- regex-significant, like the dollar sign ($), you need to prepend- \. And when using the command line you need to add one more- level of quoting to hide it from the shell, so eg do: hledger- print cur:'\$' or hledger print cur:\\$.-- desc:REGEX- match transaction descriptions.-- date:PERIODEXPR- match dates within the specified period. PERIODEXPR is a period- expression (with no report interval). Examples: date:2016,- date:thismonth, date:2000/2/1-2/15, date:lastweek-. If the- --date2 command line flag is present, this matches secondary- dates instead.-- date2:PERIODEXPR- match secondary dates within the specified period.-- depth:N- match (or display, depending on command) accounts at or above- this depth-- note:REGEX- match transaction notes (part of description right of |, or- whole description when there's no |)-- payee:REGEX- match transaction payee/payer names (part of description left of- |, or whole description when there's no |)-- real:, real:0- match real or virtual postings respectively-- status:, status:!, status:*- match unmarked, pending, or cleared transactions respectively-- tag:REGEX[=REGEX]- match by tag name, and optionally also by tag value. Note a- tag: query is considered to match a transaction if it matches- any of the postings. Also remember that postings inherit the- tags of their parent transaction.-- The following special search term is used automatically in hledger-web,- only:-- inacct:ACCTNAME- tells hledger-web to show the transaction register for this ac-- count. Can be filtered further with acct etc.-- Some of these can also be expressed as command-line options (eg depth:2- is equivalent to --depth 2). Generally you can mix options and query- arguments, and the resulting query will be their intersection (perhaps- excluding the -p/--period option).-- Special characters in arguments and queries- In shell command lines, option and argument values which contain "prob-- lematic" characters, ie spaces, and also characters significant to your- shell such as <, >, (, ), | and $, should be escaped by enclosing them- in quotes or by writing backslashes before the characters. Eg:-- hledger register -p 'last year' "accounts receivable (receiv-- able|payable)" amt:\>100.-- More escaping- Characters significant both to the shell and in regular expressions may- need one extra level of escaping. These include parentheses, the pipe- symbol and the dollar sign. Eg, to match the dollar symbol, bash users- should do:-- hledger balance cur:'\$'-- or:-- hledger balance cur:\\$-- Even more escaping- When hledger runs an addon executable (eg you type hledger ui, hledger- runs hledger-ui), it de-escapes command-line options and arguments- once, so you might need to triple-escape. Eg in bash, running the ui- command and matching the dollar sign, it's:-- hledger ui cur:'\\$'-- or:-- hledger ui cur:\\\\$-- If you asked why four slashes above, this may help:-- unescaped: $- escaped: \$- double-escaped: \\$- triple-escaped: \\\\$-- (The number of backslashes in fish shell is left as an exercise for the- reader.)-- You can always avoid the extra escaping for addons by running the addon- directly:-- hledger-ui cur:\\$-- Less escaping- Inside an argument file, or in the search field of hledger-ui or- hledger-web, or at a GHCI prompt, you need one less level of escaping- than at the command line. And backslashes may work better than quotes.- Eg:-- ghci> :main balance cur:\$-- Unicode characters- hledger is expected to handle non-ascii characters correctly:-- o they should be parsed correctly in input files and on the command- line, by all hledger tools (add, iadd, hledger-web's search/add/edit- forms, etc.)-- o they should be displayed correctly by all hledger tools, and on-- screen alignment should be preserved.-- This requires a well-configured environment. Here are some tips:-- o A system locale must be configured, and it must be one that can de-- code the characters being used. In bash, you can set a locale like- this: export LANG=en_US.UTF-8. There are some more details in Trou-- bleshooting. This step is essential - without it, hledger will quit- on encountering a non-ascii character (as with all GHC-compiled pro-- grams).-- o your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)- must support unicode-- o the terminal must be using a font which includes the required unicode- glyphs-- o the terminal should be configured to display wide characters as dou-- ble width (for report alignment)-- o 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 stan-- dard 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).-- Input files- hledger reads transactions from a data file (and the add command writes- to it). By default this file is $HOME/.hledger.journal (or on Windows,- something like C:/Users/USER/.hledger.journal). You can override this- with the $LEDGER_FILE environment variable:-- $ setenv LEDGER_FILE ~/finance/2016.journal- $ hledger stats-- or with the -f/--file option:-- $ hledger -f /some/file stats-- The file name - (hyphen) means standard input:-- $ cat some.journal | hledger -f--- Usually the data file is in hledger's journal format, but it can be in- any of the supported file formats, which currently are:-- Reader: Reads: Used for file exten-- sions:- ------------------------------------------------------------------------------ journal hledger journal files and some Ledger .journal .j .hledger- journals, for transactions .ledger- time- timeclock files, for precise time log- .timeclock- clock ging- timedot timedot files, for approximate time .timedot- logging- csv comma/semicolon/tab/other-separated .csv .ssv .tsv- values, for data import-- hledger detects the format automatically based on the file extensions- shown above. If it can't recognise the file extension, it assumes- journal format. So for non-journal files, it's important to use a- recognised file extension, so as to either read successfully or to show- relevant error messages.-- When you can't ensure the right file extension, not to worry: you can- force a specific reader/format by prefixing the file path with the for-- mat and a colon. Eg to read a .dat file as csv:-- $ hledger -f csv:/some/csv-file.dat stats- $ echo 'i 2009/13/1 08:00:00' | hledger print -ftimeclock:--- You can specify multiple -f options, to read multiple files as one big- journal. There are some limitations with this:-- o directives in one file will not affect the other files-- o balance assertions will not see any account balances from previous- files-- If you need either of those things, you can-- o use a single parent file which includes the others-- o or concatenate the files into one before reading, eg: cat a.journal- b.journal | hledger -f- CMD.-- 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:-- $ hledger print > foo.txt-- Some commands (print, register, stats, the balance commands) also pro-- vide the -o/--output-file option, which does the same thing without- needing the shell. Eg:-- $ hledger print -o foo.txt- $ hledger print -o - # write to stdout (the default)-- Output format- Some commands (print, register, the balance commands) offer a choice of- output format. In addition to the usual plain text format (txt), there- are CSV (csv), HTML (html), JSON (json) and SQL (sql). This is con-- trolled by the -O/--output-format option:-- $ hledger print -O csv-- or, by a file extension specified with -o/--output-file:-- $ hledger balancesheet -o foo.html # write HTML to foo.html-- The -O option can be used to override the file extension if needed:-- $ hledger balancesheet -o foo.txt -O html # write HTML to foo.txt-- Some notes about JSON output:-- o This feature is marked experimental, and not yet much used; you- should expect our JSON to evolve. Real-world feedback is welcome.-- o Our JSON is rather large and verbose, as it is quite a faithful rep-- resentation of hledger's internal data types. To understand the- JSON, read the Haskell type definitions, which are mostly in- https://github.com/simonmichael/hledger/blob/master/hledger-- lib/Hledger/Data/Types.hs.-- o hledger represents quantities as Decimal values storing up to 255- significant digits, eg for repeating decimals. Such numbers can- arise in practice (from automatically-calculated transaction prices),- and would break most JSON consumers. So in JSON, we show quantities- as simple Numbers with at most 10 decimal places. We don't limit the- number of integer digits, but that part is under your control. We- hope this approach will not cause problems in practice; if you find- otherwise, please let us know. (Cf #1195)-- Notes about SQL output:-- o SQL output is also marked experimental, and much like JSON could use- real-world feedback.-- o SQL output is expected to work with sqlite, MySQL and PostgreSQL-- o SQL output is structured with the expectations that statements will- be executed in the empty database. If you already have tables cre-- ated via SQL output of hledger, you would probably want to either- clear tables of existing data (via delete or truncate SQL statements)- or drop tables completely as otherwise your postings will be duped.-- Regular expressions- hledger uses regular expressions in a number of places:-- o query terms, on the command line and in the hledger-web search form:- REGEX, desc:REGEX, cur:REGEX, tag:...=REGEX-- o CSV rules conditional blocks: if REGEX ...-- o account alias directives and options: alias /REGEX/ = REPLACEMENT,- --alias /REGEX/=REPLACEMENT-- hledger's regular expressions come from the regex-tdfa library. If- they're not doing what you expect, it's important to know exactly what- they support:-- 1. they are case insensitive-- 2. they are infix matching (they do not need to match the entire thing- being matched)-- 3. they are POSIX ERE (extended regular expressions)-- 4. they also support GNU word boundaries (\b, \B, \<, \>)-- 5. they do not support backreferences; if you write \1, it will match- the digit 1. Except when doing text replacement, eg in account- aliases, where backreferences can be used in the replacement string- to reference capturing groups in the search regexp.-- 6. they do not support mode modifiers ((?s)), character classes (\w,- \d), or anything else not mentioned above.-- Some things to note:-- o In the alias directive and --alias option, regular expressions must- be enclosed in forward slashes (/REGEX/). Elsewhere in hledger,- these are not required.-- o In queries, to match a regular expression metacharacter like $ as a- literal character, prepend a backslash. Eg to search for amounts- with the dollar sign in hledger-web, write cur:\$.-- o On the command line, some metacharacters like $ have a special mean-- ing to the shell and so must be escaped at least once more. See Spe-- cial characters.-- Smart dates- hledger's user interfaces accept a flexible "smart date" syntax (unlike- dates in the journal file). Smart dates allow some english words, can- be relative to today's date, and can have less-significant date parts- omitted (defaulting to 1).-- Examples:-- 2004/10/1, 2004-01-01, exact date, several separators allowed. Year- 2004.9.1 is 4+ digits, month is 1-12, day is 1-31- 2004 start of year- 2004/10 start of month- 10/1 month and day in current year- 21 day in current month- october, oct start of month in current year- yesterday, today, tomor- -1, 0, 1 days from today- row- last/this/next -1, 0, 1 periods from the current period- day/week/month/quar-- ter/year- 20181201 8 digit YYYYMMDD with valid year month and day- 201812 6 digit YYYYMM with valid year and month-- Counterexamples - malformed digit sequences might give surprising re-- sults:-- 201813 6 digits with an invalid month is parsed as start of- 6-digit year- 20181301 8 digits with an invalid month is parsed as start of- 8-digit year- 20181232 8 digits with an invalid day gives an error- 201801012 9+ digits beginning with a valid YYYYMMDD gives an error-- Report start & end date- Most hledger reports show the full span of time represented by the- journal data, by default. So, the effective report start and end dates- will be the earliest and latest transaction or posting dates found in- the journal.-- Often you will want to see a shorter time span, such as the current- month. You can specify a start and/or end date using -b/--begin,- -e/--end, -p/--period or a date: query (described below). All of these- accept the smart date syntax.-- Some notes:-- o As in Ledger, end dates are exclusive, so you need to write the date- after the last day you want to include.-- o As noted in reporting options: among start/end dates specified with- options, the last (i.e. right-most) option takes precedence.-- o The effective report start and end dates are the intersection of the- start/end dates from options and that from date: queries. That is,- date:2019-01 date:2019 -p'2000 to 2030' yields January 2019, the- smallest common time span.-- Examples:-- -b 2016/3/17 begin on St. Patrick's day 2016- -e 12/1 end at the start of december 1st of the current year- (11/30 will be the last date included)- -b thismonth all transactions on or after the 1st of the current month- -p thismonth all transactions in the current month- date:2016/3/17.. the above written as queries instead (.. can also be re-- placed with -)- date:..12/1- date:thismonth..- date:thismonth-- Report intervals- A report interval can be specified so that commands like register, bal-- ance and activity will divide their reports into multiple subperiods.- The basic intervals can be selected with one of -D/--daily,- -W/--weekly, -M/--monthly, -Q/--quarterly, or -Y/--yearly. More com-- plex intervals may be specified with a period expression. Report in-- tervals can not be specified with a query.-- Period expressions- The -p/--period option accepts period expressions, a shorthand way of- expressing a start date, end date, and/or report interval all at once.-- Here's a basic period expression specifying the first quarter of 2009.- Note, hledger always treats start dates as inclusive and end dates as- exclusive:-- -p "from 2009/1/1 to 2009/4/1"-- Keywords like "from" and "to" are optional, and so are the spaces, as- long as you don't run two dates together. "to" can also be written as- ".." or "-". These are equivalent to the above:-- -p "2009/1/1 2009/4/1"- -p2009/1/1to2009/4/1- -p2009/1/1..2009/4/1-- Dates are smart dates, so if the current year is 2009, the above can- also be written as:-- -p "1/1 4/1"- -p "january-apr"- -p "this year to 4/1"-- If you specify only one date, the missing start or end date will be the- earliest or latest transaction in your journal:-- -p "from 2009/1/1" everything after january- 1, 2009- -p "from 2009/1" the same- -p "from 2009" the same-- -p "to 2009" everything before january- 1, 2009-- A single date with no "from" or "to" defines both the start and end- date like so:-- -p "2009" the year 2009; equivalent- to "2009/1/1 to 2010/1/1"- -p "2009/1" the month of jan; equiva-- lent to "2009/1/1 to- 2009/2/1"- -p "2009/1/1" just that day; equivalent- to "2009/1/1 to 2009/1/2"-- Or you can specify a single quarter like so:-- -p "2009Q1" first quarter of 2009,- equivalent to "2009/1/1 to- 2009/4/1"- -p "q4" fourth quarter of the cur-- rent year-- The argument of -p can also begin with, or be, a report interval ex-- pression. The basic report intervals are daily, weekly, monthly, quar-- terly, or yearly, which have the same effect as the -D,-W,-M,-Q, or -Y- flags. Between report interval and start/end dates (if any), the word- in is optional. Examples:-- -p "weekly from 2009/1/1 to 2009/4/1"- -p "monthly in 2008"- -p "quarterly"-- Note that weekly, monthly, quarterly and yearly intervals will always- start on the first day on week, month, quarter or year accordingly, and- will end on the last day of same period, even if associated period ex-- pression specifies different explicit start and end date.-- For example:-- -p "weekly from 2009/1/1 starts on 2008/12/29, closest preceding Mon-- to 2009/4/1" day- -p "monthly in starts on 2018/11/01- 2008/11/25"- -p "quarterly from starts on 2009/04/01, ends on 2009/06/30,- 2009-05-05 to 2009-06-01" which are first and last days of Q2 2009- -p "yearly from starts on 2009/01/01, first day of 2009- 2009-12-29"-- The following more complex report intervals are also supported: bi-- weekly, fortnightly, bimonthly, every day|week|month|quarter|year, ev-- ery N days|weeks|months|quarters|years.-- All of these will start on the first day of the requested period and- end on the last one, as described above.-- Examples:-- -p "bimonthly from 2008" periods will have boundaries on 2008/01/01,- 2008/03/01, ...- -p "every 2 weeks" starts on closest preceding Monday- -p "every 5 month from periods will have boundaries on 2009/03/01,- 2009/03" 2009/08/01, ...-- If you want intervals that start on arbitrary day of your choosing and- span a week, month or year, you need to use any of the following:-- every Nth day of week, every <weekday>, every Nth day [of month], every- Nth weekday [of month], every MM/DD [of year], every Nth MMM [of year],- every MMM Nth [of year].-- Examples:-- -p "every 2nd day of periods will go from Tue to Tue- week"- -p "every Tue" same- -p "every 15th day" period boundaries will be on 15th of each- month- -p "every 2nd Monday" period boundaries will be on second Monday of- each month- -p "every 11/05" yearly periods with boundaries on 5th of Nov- -p "every 5th Nov" same- -p "every Nov 5th" same-- Show historical balances at end of 15th each month (N is exclusive end- date):-- hledger balance -H -p "every 16th day"-- Group postings from start of wednesday to end of next tuesday (N is- start date and exclusive end date):-- hledger register checking -p "every 3rd day of week"-- Depth limiting- With the --depth N option (short form: -N), commands like account, bal-- ance and register will show only the uppermost accounts in the account- tree, down to level N. Use this when you want a summary with less de-- tail. This flag has the same effect as a depth: query argument (so -2,- --depth=2 or depth:2 are equivalent).-- Pivoting- Normally hledger sums amounts, and organizes them in a hierarchy, based- on account name. The --pivot FIELD option causes it to sum and orga-- nize hierarchy based on the value of some other field instead. FIELD- can be: code, description, payee, note, or the full name (case insensi-- tive) of any tag. As with account names, values containing colon:sepa-- rated:parts will be displayed hierarchically in reports.-- --pivot is a general option affecting all reports; you can think of- hledger transforming the journal before any other processing, replacing- every posting's account name with the value of the specified field on- that posting, inheriting it from the transaction or using a blank value- if it's not present.-- An example:-- 2016/02/16 Member Fee Payment- assets:bank account 2 EUR- income:member fees -2 EUR ; member: John Doe-- Normal balance report showing account names:-- $ hledger balance- 2 EUR assets:bank account- -2 EUR income:member fees- --------------------- 0-- Pivoted balance report, using member: tag values instead:-- $ hledger balance --pivot member- 2 EUR- -2 EUR John Doe- --------------------- 0-- One way to show only amounts with a member: value (using a query, de-- scribed below):-- $ hledger balance --pivot member tag:member=.- -2 EUR John Doe- --------------------- -2 EUR-- Another way (the acct: query matches against the pivoted "account- name"):-- $ hledger balance --pivot member acct:.- -2 EUR John Doe- --------------------- -2 EUR-- Valuation- Instead of reporting amounts in their original commodity, hledger can- convert them to cost/sale amount (using the conversion rate recorded in- the transaction), or to market value (using some market price on a cer-- tain date). This is controlled by the --value=TYPE[,COMMODITY] option,- but we also provide the simpler -B/-V/-X flags, and usually one of- those is all you need.-- -B: Cost- The -B/--cost flag converts amounts to their cost or sale amount at- transaction time, if they have a transaction price specified.-- -V: Value- The -V/--market flag converts amounts to market value in their default- valuation commodity, using the market prices in effect on the valuation- date(s), if any. More on these in a minute.-- -X: Value in specified commodity- The -X/--exchange=COMM option is like -V, except you tell it which cur-- rency you want to convert to, and it tries to convert everything to- that.-- Valuation date- Since market prices can change from day to day, market value reports- have a valuation date (or more than one), which determines which market- prices will be used.-- For single period reports, if an explicit report end date is specified,- that will be used as the valuation date; otherwise the valuation date- is "today".-- For multiperiod reports, each column/period is valued on the last day- of the period.-- Market prices- (experimental)-- 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 :-- 1. A declared market price or inferred market price: A's latest market- price in B on or before the valuation date as declared by a P direc-- tive, or (if the --infer-value flag is used) inferred from transac-- tion prices.-- 2. A reverse market price: the inverse of a declared or inferred market- price from B to A.-- 3. A chained market price: a synthetic price formed by combining the- shortest chain of market prices (any of the above types) leading- from A to B.-- Amounts for which no applicable market price can be found, are not con-- verted.-- --infer-value: market prices from transactions- (experimental)-- 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 transaction prices as additional market- prices (as Ledger does) ? We could produce value reports without need-- ing P directives at all.-- Adding the --infer-value flag to -V, -X or --value enables this. So- for example, hledger bs -V --infer-value will get market prices both- from P directives and from transactions.-- There is a downside: value reports can sometimes be affected in confus-- ing/undesired ways by your journal entries. If this happens to you,- read all of this Valuation section carefully, and try adding --debug or- --debug=2 to troubleshoot.-- --infer-value can infer market prices from:-- o multicommodity transactions with explicit prices (@/@@)-- o multicommodity transactions with implicit prices (no @, two commodi-- ties, unbalanced). (With these, the order of postings matters.- hledger print -x can be useful for troubleshooting.)-- o but not, currently, from "more correct" multicommodity transactions- (no @, multiple commodities, balanced).-- Valuation commodity- (experimental)-- When you specify a valuation commodity (-X COMM or --value TYPE,COMM):- hledger will convert all amounts to COMM, wherever it can find a suit-- able market price (including by reversing or chaining prices).-- When you leave the valuation commodity unspecified (-V or --value- TYPE):- For each commodity A, hledger picks a default valuation commodity as- follows, in this order of preference:-- 1. The price commodity from the latest P-declared market price for A on- or before valuation date.-- 2. 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.)-- 3. If there are no P directives at all (any commodity or date) and the- --infer-value flag is used: the price commodity from the latest- transaction-inferred price for A on or before valuation date.-- This means:-- o If you have P directives, they determine which commodities -V will- convert, and to what.-- o If you have no P directives, and use the --infer-value flag, transac-- tion prices determine it.-- Amounts for which no valuation commodity can be found are not con-- verted.-- Simple valuation examples- Here are some quick examples of -V:-- ; one euro is worth this many dollars from nov 1- P 2016/11/01 EUR $1.10-- ; purchase some euros on nov 3- 2016/11/3- assets:euros EUR100- assets:checking-- ; the euro is worth fewer dollars by dec 21- P 2016/12/21 EUR $1.03-- How many euros do I have ?-- $ hledger -f t.j bal -N euros- EUR100 assets:euros-- What are they worth at end of nov 3 ?-- $ hledger -f t.j bal -N euros -V -e 2016/11/4- $110.00 assets:euros-- What are they worth after 2016/12/21 ? (no report end date specified,- defaults to today)-- $ hledger -f t.j bal -N euros -V- $103.00 assets:euros-- --value: Flexible valuation- -B, -V and -X are special cases of the more general --value option:-- --value=TYPE[,COMM] TYPE is cost, then, end, now or YYYY-MM-DD.- COMM is an optional commodity symbol.- Shows amounts converted to:- - cost commodity using transaction prices (then optionally to COMM using market prices at period end(s))- - 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-- The TYPE part selects cost or value and valuation date:-- --value=cost- Convert amounts to cost, using the prices recorded in transac-- tions.-- --value=then- Convert amounts to their value in the default valuation commod-- ity, using market prices on each posting's date. This is cur-- rently supported only by the print and register commands.-- --value=end- Convert amounts to their value in the default valuation commod-- ity, using market prices on the last day of the report period- (or if unspecified, the journal's end date); or in multiperiod- reports, market prices on the last day of each subperiod.-- --value=now- Convert amounts to their value in the default valuation commod-- ity using current market prices (as of when report is gener-- ated).-- --value=YYYY-MM-DD- Convert amounts to their value in the default valuation commod-- ity using market prices on this date.-- To select a different valuation commodity, add the optional ,COMM part:- a comma, then the target commodity's symbol. Eg: --value=now,EUR.- hledger will do its best to convert amounts to this commodity, deducing- market prices as described above.-- More valuation examples- Here are some examples showing the effect of --value, as seen with- print:-- 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 @ 5 B-- 2000-02-01- (a) 1 A @ 6 B-- 2000-03-01- (a) 1 A @ 7 B-- Show the cost of each posting:-- $ hledger -f- print --value=cost- 2000-01-01- (a) 5 B-- 2000-02-01- (a) 6 B-- 2000-03-01- (a) 7 B-- Show the value as of the last day of the report period (2000-02-29):-- $ hledger -f- print --value=end date:2000/01-2000/03- 2000-01-01- (a) 2 B-- 2000-02-01- (a) 2 B-- With no report period specified, that shows the value as of the last- day of the journal (2000-03-01):-- $ hledger -f- print --value=end- 2000-01-01- (a) 3 B-- 2000-02-01- (a) 3 B-- 2000-03-01- (a) 3 B-- Show the current value (the 2000-04-01 price is still in effect today):-- $ hledger -f- print --value=now- 2000-01-01- (a) 4 B-- 2000-02-01- (a) 4 B-- 2000-03-01- (a) 4 B-- Show the value on 2000/01/15:-- $ 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-- You may need to explicitly set a commodity's display style, when re-- verse prices are used. Eg this output might be surprising:-- P 2000-01-01 A 2B-- 2000-01-01- a 1B- b-- $ hledger print -x -X A- 2000-01-01- a 0- b 0-- Explanation: because there's no amount or commodity directive specify-- ing a display style for A, 0.5A gets the default style, which shows no- decimal digits. Because the displayed amount looks like zero, the com-- modity symbol and minus sign are not displayed either. Adding a com-- modity directive sets a more useful display style for A:-- P 2000-01-01 A 2B- commodity 0.00A-- 2000-01-01- a 1B- b-- $ hledger print -X A- 2000-01-01- a 0.50A- b -0.50A-- Effect of valuation on reports- Here is a reference for how valuation is supposed to affect each part- of hledger's reports (and a glossary). (It's wide, you'll have to- scroll sideways.) It may be useful when troubleshooting. If you find- problems, please report them, ideally with a reproducible example. Re-- lated: #329, #1083.-- Report type -B, -V, -X --value=then --value=end --value=DATE,- --value=cost --value=now- ------------------------------------------------------------------------------------------- print- posting cost value at re- value at value at re- value at- amounts port end or posting date port or DATE/today- today journal end- balance as- unchanged unchanged unchanged unchanged unchanged- sertions /- assignments-- register- starting cost value at day not supported value at day value at- balance before re- before re- DATE/today- (with -H) port or port or- journal journal- start start- posting cost value at re- value at value at re- value at- amounts (no port end or posting date port or DATE/today- report in- today journal end- terval)- summary summarised value at pe- sum of post- value at pe- value at- posting cost riod ends ings in in- riod ends DATE/today- amounts terval, val-- (with report ued at inter-- interval) val start- running to- sum/average sum/average sum/average sum/average sum/average- tal/average of displayed of displayed of displayed of displayed of displayed- values values values values values--- balance (bs,- bse, cf,- is..)- balances (no sums of value at re- not supported value at re- value at- report in- costs port end or port or DATE/today of- terval) today of journal end sums of post-- sums of of sums of ings- postings postings- balances sums of value at pe- not supported value at pe- value at- (with report costs riod ends of riod ends of DATE/today of- interval) sums of sums of sums of post-- postings postings ings- starting sums of sums of not supported sums of sums of post-- balances costs of postings be- postings be- ings before- (with report postings be- fore report fore report report start- interval and fore report start start- -H) start- budget like bal- like bal- not supported like bal- like balances- amounts with ances ances ances- --budget- grand total sum of dis- sum of dis- not supported sum of dis- sum of dis-- (no report played val- played val- played val- played values- interval) ues ues ues- row to- sums/aver- sums/aver- not supported sums/aver- sums/averages- tals/aver- ages of dis- ages of dis- ages of dis- of displayed- ages (with played val- played val- played val- values- report in- ues ues ues- terval)- column to- sums of dis- sums of dis- not supported sums of dis- sums of dis-- tals played val- played val- played val- played values- ues ues ues- grand to- sum/average sum/average not supported sum/average sum/average- tal/average of column of column of column of column to-- totals totals totals tals--- Glossary:-- cost calculated using price(s) recorded in the transaction(s).-- value market value using available market price declarations, or the- unchanged amount if no conversion rate can be found.-- report start- the first day of the report period specified with -b or -p or- date:, otherwise today.-- report or journal start- the first day of the report period specified with -b or -p or- date:, otherwise the earliest transaction date in the journal,- otherwise today.-- report end- the last day of the report period specified with -e or -p or- date:, otherwise today.-- report or journal end- the last day of the report period specified with -e or -p or- date:, otherwise the latest transaction date in the journal,- otherwise today.-- report interval- a flag (-D/-W/-M/-Q/-Y) or period expression that activates the- report's multi-period mode (whether showing one or many subperi-- ods).--COMMANDS- hledger provides a number of subcommands; hledger with no arguments- shows a list.-- If you install additional hledger-* packages, or if you put programs or- scripts named hledger-NAME in your PATH, these will also be listed as- subcommands.-- Run a subcommand by writing its name as first argument (eg hledger in-- comestatement). You can also write one of the standard short aliases- displayed in parentheses in the command list (hledger b), or any any- unambiguous prefix of a command name (hledger inc).-- Here are all the builtin commands in alphabetical order. See also- hledger for a more organised command list, and hledger CMD -h for de-- tailed command help.-- accounts- accounts, a- Show account names.-- This command lists account names, either declared with account direc-- tives (--declared), posted to (--used), or both (the default). With- query arguments, only matched account names and account names refer-- enced by matched postings are shown. It shows a flat list by default.- With --tree, it uses indentation to show the account hierarchy. In- flat mode you can add --drop N to omit the first few account name com-- ponents. Account names can be depth-clipped with depth:N or --depth N- or -N.-- Examples:-- $ hledger accounts- assets:bank:checking- assets:bank:saving- assets:cash- expenses:food- expenses:supplies- income:gifts- income:salary- liabilities:debts-- activity- activity- Show an ascii barchart of posting counts per interval.-- The activity command displays an ascii histogram showing transaction- counts by day, week, month or other reporting interval (by day is the- default). With query arguments, it counts only matched transactions.-- Examples:-- $ hledger activity --quarterly- 2008-01-01 **- 2008-04-01 *******- 2008-07-01- 2008-10-01 **-- add- add- Prompt for transactions and add them to the journal. Any arguments- will be used as default inputs for the first N prompts.-- Many hledger users edit their journals directly with a text editor, or- generate them from CSV. For more interactive data entry, there is the- add command, which prompts interactively on the console for new trans-- actions, and appends them to the journal file (if there are multiple -f- FILE options, the first file is used.) Existing transactions are not- changed. This is the only hledger command that writes to the journal- file.-- To use it, just run hledger add and follow the prompts. You can add as- many transactions as you like; when you are finished, enter . or press- control-d or control-c to exit.-- Features:-- o add tries to provide useful defaults, using the most similar (by de-- scription) recent transaction (filtered by the query, if any) as a- template.-- o You can also set the initial defaults with command line arguments.-- o Readline-style edit keys can be used during data entry.-- o The tab key will auto-complete whenever possible - accounts, descrip-- tions, dates (yesterday, today, tomorrow). If the input area is- empty, it will insert the default value.-- o If the journal defines a default commodity, it will be added to any- bare numbers entered.-- o A parenthesised transaction code may be entered following a date.-- o Comments and tags may be entered following a description or amount.-- o If you make a mistake, enter < at any prompt to go one step backward.-- o Input prompts are displayed in a different colour when the terminal- supports it.-- Example (see the tutorial for a detailed explanation):-- $ hledger add- Adding transactions to journal file /src/hledger/examples/sample.journal- Any command line arguments will be used as defaults.- Use tab key to complete, readline keys to edit, enter to accept defaults.- An optional (CODE) may follow transaction dates.- An optional ; COMMENT may follow descriptions or amounts.- If you make a mistake, enter < at any prompt to go one step backward.- To end a transaction, enter . when prompted.- To quit, enter . at a date prompt or press control-d or control-c.- Date [2015/05/22]:- Description: supermarket- Account 1: expenses:food- Amount 1: $10- Account 2: assets:checking- Amount 2 [$-10.0]:- Account 3 (or . or enter to finish this transaction): .- 2015/05/22 supermarket- expenses:food $10- assets:checking $-10.0-- Save this transaction to the journal ? [y]:- Saved.- Starting the next transaction (. or ctrl-D/ctrl-C to quit)- Date [2015/05/22]: <CTRL-D> $-- On Microsoft Windows, the add command makes sure that no part of the- file path ends with a period, as that would cause problems (#1056).-- aregister- aregister, areg- Show transactions affecting a particular account, and the account's- running balance.-- aregister shows the transactions affecting a particular account (and- its subaccounts), from the point of view of that account. Each line- shows:-- o the transaction's (or posting's, see below) date-- o the names of the other account(s) involved-- o the net change to this account's balance-- o the account's historical running balance (including balance from- transactions before the report start date).-- With aregister, each line represents a whole transaction - as in- hledger-ui, hledger-web, and your bank statement. By contrast, the- register command shows individual postings, across all accounts. You- might prefer aregister for reconciling with real-world asset/liability- accounts, and register for reviewing detailed revenues/expenses.-- An account must be specified as the first argument, which should be the- full account name or an account pattern (regular expression). aregis-- ter will show transactions in this account (the first one matched) and- any of its subaccounts.-- Any additional arguments form a query which will filter the transac-- tions shown.-- Transactions making a net change of zero are not shown by default; add- the -E/--empty flag to show them.-- aregister and custom posting dates- Transactions whose date is outside the report period can still be- shown, if they have a posting to this account dated inside the report- period. (And in this case it's the posting date that is shown.) This- ensures that aregister can show an accurate historical running balance,- matching the one shown by register -H with the same arguments.-- To filter strictly by transaction date instead, add the --txn-dates- flag. If you use this flag and some of your postings have custom- dates, it's probably best to assume the running balance is wrong.-- Output format- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, and json.-- Examples:-- Show all transactions and historical running balance in the first ac-- count whose name contains "checking":-- $ hledger areg checking-- Show transactions and historical running balance in all asset accounts- during july:-- $ hledger areg assets date:jul-- balance- balance, bal, b- Show accounts and their balances.-- The balance command is hledger's most versatile command. Note, despite- the name, it is not always used for showing real-world account bal-- ances; the more accounting-aware balancesheet and incomestatement may- be more convenient for that.-- By default, it displays all accounts, and each account's change in bal-- ance during the entire period of the journal. Balance changes are cal-- culated by adding up the postings in each account. You can limit the- postings matched, by a query, to see fewer accounts, changes over a- different time period, changes from only cleared transactions, etc.-- If you include an account's complete history of postings in the report,- the balance change is equivalent to the account's current ending bal-- ance. For a real-world account, typically you won't have all transac-- tions in the journal; instead you'll have all transactions after a cer-- tain date, and an "opening balances" transaction setting the correct- starting balance on that date. Then the balance command will show- real-world account balances. In some cases the -H/--historical flag is- used to ensure this (more below).-- The balance command can produce several styles of report:-- Classic balance report- This is the original balance report, as found in Ledger. It usually- looks like this:-- $ hledger balance- $-1 assets- $1 bank:saving- $-2 cash- $2 expenses- $1 food- $1 supplies- $-2 income- $-1 gifts- $-1 salary- $1 liabilities:debts- --------------------- 0-- By default, accounts are displayed hierarchically, with subaccounts in-- dented below their parent. At each level of the tree, accounts are- sorted by account code if any, then by account name. Or with- -S/--sort-amount, by their balance amount, largest first.-- "Boring" accounts, which contain a single interesting subaccount and no- balance of their own, are elided into the following line for more com-- pact output. (Eg above, the "liabilities" account.) Use --no-elide to- prevent this.-- Account balances are "inclusive" - they include the balances of any- subaccounts.-- Accounts which have zero balance (and no non-zero subaccounts) are- omitted. Use -E/--empty to show them.-- A final total is displayed by default; use -N/--no-total to suppress- it, eg:-- $ hledger balance -p 2008/6 expenses --no-total- $2 expenses- $1 food- $1 supplies-- Customising the classic balance report- You can customise the layout of classic balance reports with --format- FMT:-- $ hledger balance --format "%20(account) %12(total)"- assets $-1- bank:saving $1- cash $-2- expenses $2- food $1- supplies $1- income $-2- gifts $-1- salary $-1- liabilities:debts $1- ---------------------------------- 0-- The FMT format string (plus a newline) specifies the formatting applied- to each account/balance pair. It may contain any suitable text, with- data fields interpolated like so:-- %[MIN][.MAX](FIELDNAME)-- o MIN pads with spaces to at least this width (optional)-- o MAX truncates at this width (optional)-- o FIELDNAME must be enclosed in parentheses, and can be one of:-- o depth_spacer - a number of spaces equal to the account's depth, or- if MIN is specified, MIN * depth spaces.-- o account - the account's name-- o total - the account's balance/posted total, right justified-- Also, FMT can begin with an optional prefix to control how multi-com-- modity amounts are rendered:-- o %_ - render on multiple lines, bottom-aligned (the default)-- o %^ - render on multiple lines, top-aligned-- o %, - render on one line, comma-separated-- There are some quirks. Eg in one-line mode, %(depth_spacer) has no ef-- fect, instead %(account) has indentation built in. Experimentation may- be needed to get pleasing results.-- Some example formats:-- o %(total) - the account's total-- o %-20.20(account) - the account's name, left justified, padded to 20- characters and clipped at 20 characters-- o %,%-50(account) %25(total) - account name padded to 50 characters,- total padded to 20 characters, with multiple commodities rendered on- one line-- o %20(total) %2(depth_spacer)%-(account) - the default format for the- single-column balance report-- Colour support- In terminal output, when colour is enabled, the balance command shows- negative amounts in red.-- Flat mode- To see a flat list instead of the default hierarchical display, use- --flat. In this mode, accounts (unless depth-clipped) show their full- names and "exclusive" balance, excluding any subaccount balances. In- this mode, you can also use --drop N to omit the first few account name- components.-- $ hledger balance -p 2008/6 expenses -N --flat --drop 1- $1 food- $1 supplies-- Depth limited balance reports- With --depth N or depth:N or just -N, balance reports show accounts- only to the specified numeric depth. This is very useful to summarise- a complex set of accounts and get an overview.-- $ hledger balance -N -1- $-1 assets- $2 expenses- $-2 income- $1 liabilities-- Flat-mode balance reports, which normally show exclusive balances, show- inclusive balances at the depth limit.-- Percentages- With -% or --percent, balance reports show each account's value ex-- pressed as a percentage of the column's total. This is useful to get- an overview of the relative sizes of account balances. For example to- obtain an overview of expenses:-- $ hledger balance expenses -%- 100.0 % expenses- 50.0 % food- 50.0 % supplies- --------------------- 100.0 %-- Note that --tree does not have an effect on -%. The percentages are- always relative to the total sum of each column, they are never rela-- tive to the parent account.-- Since the percentages are relative to the columns sum, it is usually- not useful to calculate percentages if the signs of the amounts are- mixed. Although the results are technically correct, they are most- likely useless. Especially in a balance report that sums up to zero- (eg hledger balance -B) all percentage values will be zero.-- This flag does not work if the report contains any mixed commodity ac-- counts. If there are mixed commodity accounts in the report be sure to- use -V or -B to coerce the report into using a single commodity.-- Multicolumn balance report- Multicolumn or tabular balance reports are a very useful hledger fea-- ture, and usually the preferred style. They share many of the above- features, but they show the report as a table, with columns represent-- ing time periods. This mode is activated by providing a reporting in-- terval.-- There are three types of multicolumn balance report, showing different- information:-- 1. By default: each column shows the sum of postings in that period, ie- the account's change of balance in that period. This is useful eg- for a monthly income statement:-- $ hledger balance --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-- 2. With --cumulative: each column shows the ending balance for that pe-- riod, accumulating the changes across periods, starting from 0 at- the report start date:-- $ hledger balance --quarterly income expenses -E --cumulative- Ending balances (cumulative) in 2008:-- || 2008/03/31 2008/06/30 2008/09/30 2008/12/31- ===================++=================================================- expenses:food || 0 $1 $1 $1- expenses:supplies || 0 $1 $1 $1- income:gifts || 0 $-1 $-1 $-1- income:salary || $-1 $-1 $-1 $-1- -------------------++-------------------------------------------------- || $-1 0 0 0-- 3. With --historical/-H: each column shows the actual historical ending- balance for that period, accumulating the changes across periods,- starting from the actual balance at the report start date. This is- useful eg for a multi-period balance sheet, and when you are showing- only the data after a certain start date:-- $ hledger balance ^assets ^liabilities --quarterly --historical --begin 2008/4/1- Ending balances (historical) in 2008/04/01-2008/12/31:-- || 2008/06/30 2008/09/30 2008/12/31- ======================++=====================================- assets:bank:checking || $1 $1 0- assets:bank:saving || $1 $1 $1- assets:cash || $-2 $-2 $-2- liabilities:debts || 0 0 $1- ----------------------++-------------------------------------- || 0 0 0-- Note that --cumulative or --historical/-H disable --row-total/-T, since- summing end balances generally does not make sense.-- Multicolumn balance reports display accounts in flat mode by default;- to see the hierarchy, use --tree.-- With a reporting interval (like --quarterly above), the report- start/end dates will be adjusted if necessary so that they encompass- the displayed report periods. This is so that the first and last peri-- ods will be "full" and comparable to the others.-- The -E/--empty flag does two things in multicolumn balance reports:- first, the report will show all columns within the specified report pe-- riod (without -E, leading and trailing columns with all zeroes are not- shown). Second, all accounts which existed at the report start date- will be considered, not just the ones with activity during the report- period (use -E to include low-activity accounts which would otherwise- would be omitted).-- The -T/--row-total flag adds an additional column showing the total for- each row.-- The -A/--average flag adds a column showing the average value in each- row.-- Here's an example of all three:-- $ hledger balance -Q income expenses --tree -ETA- Balance changes in 2008:-- || 2008q1 2008q2 2008q3 2008q4 Total Average- ============++===================================================- expenses || 0 $2 0 0 $2 $1- food || 0 $1 0 0 $1 0- supplies || 0 $1 0 0 $1 0- income || $-1 $-1 0 0 $-2 $-1- gifts || 0 $-1 0 0 $-1 0- salary || $-1 0 0 0 $-1 0- ------------++---------------------------------------------------- || $-1 $1 0 0 0 0-- (Average is rounded to the dollar here since all journal amounts are)-- The --transpose flag can be used to exchange the rows and columns of a- multicolumn report.-- When showing multicommodity amounts, multicolumn balance reports will- elide any amounts which have more than two commodities, since otherwise- columns could get very wide. The --no-elide flag disables this. Hid-- ing totals with the -N/--no-total flag can also help reduce the width- of multicommodity reports.-- When the report is still too wide, a good workaround is to pipe it into- less -RS (-R for colour, -S to chop long lines). Eg: hledger bal -D- --color=yes | less -RS.-- Budget report- With --budget, extra columns are displayed showing budget goals for- each account and period, if any. Budget goals are defined by periodic- transactions. This is very useful for comparing planned and actual in-- come, expenses, time usage, etc. --budget is most often combined with- a report interval.-- For example, you can take average monthly expenses in the common ex-- pense categories to construct a minimal monthly budget:-- ;; Budget- ~ monthly- income $2000- expenses:food $400- expenses:bus $50- expenses:movies $30- assets:bank:checking-- ;; Two months worth of expenses- 2017-11-01- income $1950- expenses:food $396- expenses:bus $49- expenses:movies $30- expenses:supplies $20- assets:bank:checking-- 2017-12-01- income $2100- expenses:food $412- expenses:bus $53- expenses:gifts $100- assets:bank:checking-- You can now see a monthly budget report:-- $ hledger balance -M --budget- Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec- ======================++====================================================- assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- expenses || $495 [ 103% of $480] $565 [ 118% of $480]- expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50]- expenses:food || $396 [ 99% of $400] $412 [ 103% of $400]- expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30]- income || $1950 [ 98% of $2000] $2100 [ 105% of $2000]- ----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0]-- This is different from a normal balance report in several ways:-- o Only accounts with budget goals during the report period are shown,- by default.-- o In each column, in square brackets after the actual amount, budget- goal amounts are shown, and the actual/goal percentage. (Note: bud-- get goals should be in the same commodity as the actual amount.)-- o All parent accounts are always shown, even in flat mode. Eg assets,- assets:bank, and expenses above.-- o Amounts always include all subaccounts, budgeted or unbudgeted, even- in flat mode.-- This means that the numbers displayed will not always add up! Eg above,- the expenses actual amount includes the gifts and supplies transac-- tions, but the expenses:gifts and expenses:supplies accounts are not- shown, as they have no budget amounts declared.-- This can be confusing. When you need to make things clearer, use the- -E/--empty flag, which will reveal all accounts including unbudgeted- ones, giving the full picture. Eg:-- $ hledger balance -M --budget --empty- Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec- ======================++====================================================- assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- expenses || $495 [ 103% of $480] $565 [ 118% of $480]- expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50]- expenses:food || $396 [ 99% of $400] $412 [ 103% of $400]- expenses:gifts || 0 $100- expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30]- expenses:supplies || $20 0- income || $1950 [ 98% of $2000] $2100 [ 105% of $2000]- ----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0]-- You can roll over unspent budgets to next period with --cumulative:-- $ hledger balance -M --budget --cumulative- Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec- ======================++====================================================- assets || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]- assets:bank || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]- assets:bank:checking || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]- expenses || $495 [ 103% of $480] $1060 [ 110% of $960]- expenses:bus || $49 [ 98% of $50] $102 [ 102% of $100]- expenses:food || $396 [ 99% of $400] $808 [ 101% of $800]- expenses:movies || $30 [ 100% of $30] $30 [ 50% of $60]- income || $1950 [ 98% of $2000] $4050 [ 101% of $4000]- ----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0]-- For more examples, see Budgeting and Forecasting.-- Nested budgets- You can add budgets to any account in your account hierarchy. If you- have budgets on both parent account and some of its children, then bud-- get(s) of the child account(s) would be added to the budget of their- parent, much like account balances behave.-- In the most simple case this means that once you add a budget to any- account, all its parents would have budget as well.-- To illustrate this, consider the following budget:-- ~ monthly from 2019/01- expenses:personal $1,000.00- expenses:personal:electronics $100.00- liabilities-- With this, monthly budget for electronics is defined to be $100 and- budget for personal expenses is an additional $1000, which implicitly- means that budget for both expenses:personal and expenses is $1100.-- Transactions in expenses:personal:electronics will be counted both to-- wards its $100 budget and $1100 of expenses:personal , and transactions- in any other subaccount of expenses:personal would be counted towards- only towards the budget of expenses:personal.-- For example, let's consider these transactions:-- ~ monthly from 2019/01- expenses:personal $1,000.00- expenses:personal:electronics $100.00- liabilities-- 2019/01/01 Google home hub- expenses:personal:electronics $90.00- liabilities $-90.00-- 2019/01/02 Phone screen protector- expenses:personal:electronics:upgrades $10.00- liabilities-- 2019/01/02 Weekly train ticket- expenses:personal:train tickets $153.00- liabilities-- 2019/01/03 Flowers- expenses:personal $30.00- liabilities-- As you can see, we have transactions in expenses:personal:electron-- ics:upgrades and expenses:personal:train tickets, and since both of- these accounts are without explicitly defined budget, these transac-- tions would be counted towards budgets of expenses:personal:electronics- and expenses:personal accordingly:-- $ hledger balance --budget -M- Budget performance in 2019/01:-- || Jan- ===============================++===============================- expenses || $283.00 [ 26% of $1100.00]- expenses:personal || $283.00 [ 26% of $1100.00]- expenses:personal:electronics || $100.00 [ 100% of $100.00]- liabilities || $-283.00 [ 26% of $-1100.00]- -------------------------------++-------------------------------- || 0 [ 0]-- And with --empty, we can get a better picture of budget allocation and- consumption:-- $ hledger balance --budget -M --empty- Budget performance in 2019/01:-- || Jan- ========================================++===============================- expenses || $283.00 [ 26% of $1100.00]- expenses:personal || $283.00 [ 26% of $1100.00]- expenses:personal:electronics || $100.00 [ 100% of $100.00]- expenses:personal:electronics:upgrades || $10.00- expenses:personal:train tickets || $153.00- liabilities || $-283.00 [ 26% of $-1100.00]- ----------------------------------------++-------------------------------- || 0 [ 0]-- Output format- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, (multicolumn non-bud-- get reports only) html, and (experimental) json.-- balancesheet- balancesheet, bs- This command displays a balance sheet, showing historical ending bal-- ances of asset and liability accounts. (To see equity as well, use the- balancesheetequity command.) Amounts are shown with normal positive- sign, as in conventional financial statements.-- The asset and liability accounts shown are those accounts declared with- the Asset or Cash or Liability type, or otherwise all accounts under a- top-level asset or liability account (case insensitive, plurals al-- lowed).-- Example:-- $ hledger balancesheet- Balance Sheet-- Assets:- $-1 assets- $1 bank:saving- $-2 cash- --------------------- $-1-- Liabilities:- $1 liabilities:debts- --------------------- $1-- Total:- --------------------- 0-- With a reporting interval, multiple columns will be shown, one for each- report period. As with multicolumn balance reports, you can alter the- report mode with --change/--cumulative/--historical. Normally bal-- ancesheet shows historical ending balances, which is what you need for- a balance sheet; note this means it ignores report begin dates (and- -T/--row-total, since summing end balances generally does not make- sense). Instead of absolute values percentages can be displayed with- -%.-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, html, and (experimen-- tal) json.-- balancesheetequity- balancesheetequity, bse- This command displays a balance sheet, showing historical ending bal-- ances of asset, liability and equity accounts. Amounts are shown with- normal positive sign, as in conventional financial statements.-- The asset, liability and equity accounts shown are those accounts de-- clared with the Asset, Cash, Liability or Equity type, or otherwise all- accounts under a top-level asset, liability or equity account (case in-- sensitive, plurals allowed).-- Example:-- $ hledger balancesheetequity- Balance Sheet With Equity-- Assets:- $-2 assets- $1 bank:saving- $-3 cash- --------------------- $-2-- Liabilities:- $1 liabilities:debts- --------------------- $1-- Equity:- $1 equity:owner- --------------------- $1-- Total:- --------------------- 0-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, html, and (experimen-- tal) json.-- cashflow- cashflow, cf- This command displays a cashflow statement, showing the inflows and- outflows affecting "cash" (ie, liquid) assets. Amounts are shown with- normal positive sign, as in conventional financial statements.-- The "cash" accounts shown are those accounts declared with the Cash- type, or otherwise all accounts under a top-level asset account (case- insensitive, plural allowed) which do not have fixed, investment, re-- ceivable or A/R in their name.-- Example:-- $ hledger cashflow- Cashflow Statement-- Cash flows:- $-1 assets- $1 bank:saving- $-2 cash- --------------------- $-1-- Total:- --------------------- $-1-- With a reporting interval, multiple columns will be shown, one for each- report period. Normally cashflow shows changes in assets per period,- though as with multicolumn balance reports you can alter the report- mode with --change/--cumulative/--historical. Instead of absolute val-- ues percentages can be displayed with -%.-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, html, and (experimen-- tal) json.-- check-dates- check-dates- Check that transactions are sorted by increasing date. With --date2,- checks secondary dates instead. With --strict, dates must also be- unique. With a query, only matched transactions' dates are checked.- Reads the default journal file, or another specified with -f.-- check-dupes- check-dupes- Reports account names having the same leaf but different prefixes. In- other words, two or more leaves that are categorized differently.- Reads the default journal file, or another specified as an argument.-- An example: http://stefanorodighiero.net/software/hledger-dupes.html-- close- close, equity- Prints a "closing balances" transaction and an "opening balances"- transaction that bring account balances to and from zero, respectively.- These can be added to your journal file(s), eg to bring asset/liability- balances forward into a new journal file, or to close out revenues/ex-- penses to retained earnings at the end of a period.-- You can print just one of these transactions by using the --close or- --open flag. You can customise their descriptions with the --close-- desc and --open-desc options.-- One amountless posting to "equity:opening/closing balances" is added to- balance the transactions, by default. You can customise this account- name with --close-acct and --open-acct; if you specify only one of- these, it will be used for both.-- With --x/--explicit, the equity posting's amount will be shown. And if- it involves multiple commodities, a posting for each commodity will be- shown, as with the print command.-- With --interleaved, the equity postings are shown next to the postings- they balance, which makes troubleshooting easier.-- By default, transaction prices in the journal are ignored when generat-- ing the closing/opening transactions. With --show-costs, this cost in-- formation is preserved (balance -B reports will be unchanged after the- transition). Separate postings are generated for each cost in each- commodity. Note this can generate very large journal entries, if you- have many foreign currency or investment transactions.-- close usage- If you split your journal files by time (eg yearly), you will typically- run this command at the end of the year, and save the closing transac-- tion as last entry of the old file, and the opening transaction as the- first entry of the new file. This makes the files self contained, so- that correct balances are reported no matter which of them are loaded.- Ie, if you load just one file, the balances are initialised correctly;- or if you load several files, the redundant closing/opening transac-- tions cancel each other out. (They will show up in print or register- reports; you can exclude them with a query like not:desc:'(open-- ing|closing) balances'.)-- If you're running a business, you might also use this command to "close- the books" at the end of an accounting period, transferring income- statement account balances to retained earnings. (You may want to- change the equity account name to something like "equity:retained earn-- ings".)-- By default, the closing transaction is dated yesterday, the balances- are calculated as of end of yesterday, and the opening transaction is- dated today. To close on some other date, use: hledger close -e OPEN-- INGDATE. Eg, to close/open on the 2018/2019 boundary, use -e 2019.- You can also use -p or date:PERIOD (any starting date is ignored).-- Both transactions will include balance assertions for the closed/re-- opened accounts. You probably shouldn't use status or realness filters- (like -C or -R or status:) with this command, or the generated balance- assertions will depend on these flags. Likewise, if you run this com-- mand with --auto, the balance assertions will probably always require- --auto.-- Examples:-- Carrying asset/liability balances into a new file for 2019:-- $ hledger close -f 2018.journal -e 2019 assets liabilities --open- # (copy/paste the output to the start of your 2019 journal file)- $ hledger close -f 2018.journal -e 2019 assets liabilities --close- # (copy/paste the output to the end of your 2018 journal file)-- Now:-- $ hledger bs -f 2019.journal # one file - balances are correct- $ hledger bs -f 2018.journal -f 2019.journal # two files - balances still correct- $ hledger bs -f 2018.journal not:desc:closing # to see year-end balances, must exclude closing txn-- Transactions spanning the closing date can complicate matters, breaking- balance assertions:-- 2018/12/30 a purchase made in 2018, clearing the following year- expenses:food 5- assets:bank:checking -5 ; [2019/1/2]-- Here's one way to resolve that:-- ; in 2018.journal:- 2018/12/30 a purchase made in 2018, clearing the following year- expenses:food 5- liabilities:pending-- ; in 2019.journal:- 2019/1/2 clearance of last year's pending transactions- liabilities:pending 5 = 0- assets:checking-- codes- codes- List the codes seen in transactions, in the order parsed.-- This command prints the value of each transaction's 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.-- Transactions aren't required to have a code, and missing or empty codes- will not be shown by default. With the -E/--empty flag, they will be- printed as blank lines.-- You can add a query to select a subset of transactions.-- Examples:-- 1/1 (123)- (a) 1-- 1/1 ()- (a) 1-- 1/1- (a) 1-- 1/1 (126)- (a) 1-- $ hledger codes- 123- 124- 126-- $ hledger codes -E- 123- 124--- 126-- commodities- commodities- List all commodity/currency symbols used or declared in the journal.-- descriptions- descriptions- List the unique descriptions that appear in transactions.-- This command lists the unique descriptions that appear in transactions,- in alphabetic order. You can add a query to select a subset of trans-- actions.-- Example:-- $ hledger descriptions- Store Name- Gas Station | Petrol- Person A-- diff- diff- Compares a particular account's transactions in two input files. It- shows any transactions to this account which are in one file but not in- the other.-- More precisely, for each posting affecting this account in either file,- it looks for a corresponding posting in the other file which posts the- same amount to the same account (ignoring date, description, etc.)- Since postings not transactions are compared, this also works when mul-- tiple bank transactions have been combined into a single journal entry.-- This is useful eg if you have downloaded an account's 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.-- Examples:-- $ 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:-- files- files- List all files included in the journal. With a REGEX argument, only- file names matching the regular expression (case sensitive) are shown.-- help- help- Show any of the hledger manuals.-- The help command displays any of the main hledger manuals, in one of- several ways. Run it with no argument to list the manuals, or provide- a full or partial manual name to select one.-- hledger manuals are available in several formats. hledger help will- use the first of these display methods that it finds: info, man,- $PAGER, less, stdout (or when non-interactive, just stdout). You can- force a particular viewer with the --info, --man, --pager, --cat flags.-- Examples:-- $ hledger help- Please choose a manual by typing "hledger help MANUAL" (a substring is ok).- Manuals: hledger hledger-ui hledger-web journal csv timeclock timedot-- $ hledger help h --man-- hledger(1) hledger User Manuals hledger(1)-- NAME- hledger - a command-line accounting tool-- SYNOPSIS- hledger [-f FILE] COMMAND [OPTIONS] [ARGS]- hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]- hledger-- DESCRIPTION- hledger is a cross-platform program for tracking money, time, or any- ...-- import- import- Read new transactions added to each FILE since last run, and add them- to the main journal file. Or with --dry-run, just print the transac-- tions that would be added. Or with --catchup, just mark all of the- FILEs' transactions as imported, without actually importing any.-- The input files are specified as arguments - no need to write -f before- each one. So eg to add new transactions from all CSV files to the main- journal, it's just: hledger import *.csv-- New transactions are detected in the same way as print --new: by assum-- ing transactions are always added to the input files in increasing date- order, and by saving .latest.FILE state files.-- The --dry-run output is in journal format, so you can filter it, eg to- see only uncategorised transactions:-- $ hledger import --dry ... | hledger -f- print unknown --ignore-assertions-- Importing balance assignments- Entries added by import will have their posting amounts made explicit- (like hledger print -x). This means that any balance assignments in- imported files must be evaluated; but, imported files don't get to see- the main file's account balances. As a result, importing entries with- balance assignments (eg from an institution that provides only balances- and not posting amounts) will probably generate incorrect posting- amounts. To avoid this problem, use print instead of import:-- $ hledger print IMPORTFILE [--new] >> $LEDGER_FILE-- (If you think import should leave amounts implicit like print does,- please test it and send a pull request.)-- incomestatement- incomestatement, is- This command displays an income statement, showing revenues and ex-- penses during one or more periods. Amounts are shown with normal posi-- tive sign, as in conventional financial statements.-- The revenue and expense accounts shown are those accounts declared with- the Revenue or Expense type, or otherwise all accounts under a top-- level revenue or income or expense account (case insensitive, plurals- allowed).-- Example:-- $ hledger incomestatement- Income Statement-- Revenues:- $-2 income- $-1 gifts- $-1 salary- --------------------- $-2-- Expenses:- $2 expenses- $1 food- $1 supplies- --------------------- $2-- Total:- --------------------- 0-- With a reporting interval, multiple columns will be shown, one for each- report period. Normally incomestatement shows revenues/expenses per- period, though as with multicolumn balance reports you can alter the- report mode with --change/--cumulative/--historical. Instead of abso-- lute values percentages can be displayed with -%.-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, html, and (experimen-- tal) json.-- notes- notes- List the unique notes that appear in transactions.-- This command lists the unique notes that appear in transactions, in al-- phabetic order. You can add a query to select a subset of transac-- tions. The note is the part of the transaction description after a |- character (or if there is no |, the whole description).-- Example:-- $ hledger notes- Petrol- Snacks-- payees- payees- List the unique payee/payer names that appear in transactions.-- This command lists the unique payee/payer names that appear in transac-- tions, in alphabetic order. You can add a query to select a subset of- transactions. The payee/payer is the part of the transaction descrip-- tion before a | character (or if there is no |, the whole description).-- Example:-- $ hledger payees- Store Name- Gas Station- Person A-- prices- prices- Print market price directives from the journal. With --costs, also- print synthetic market prices based on transaction prices. With --in-- verted-costs, also print inverse prices based on transaction prices.- Prices (and postings providing prices) can be filtered by a query.- Price amounts are always displayed with their full precision.-- print- print, txns, p- Show transaction journal entries, sorted by date.-- The print command displays full journal entries (transactions) from the- journal file in date order, tidily formatted. With --date2, transac-- tions are sorted by secondary date instead.-- print's output is always a valid hledger journal.- It preserves all transaction information, but it does not preserve di-- rectives or inter-transaction comments-- $ hledger print- 2008/01/01 income- assets:bank:checking $1- income:salary $-1-- 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-- 2008/12/31 * pay off- liabilities:debts $1- assets:bank:checking $-1-- Normally, the journal entry's explicit or implicit amount style is pre-- served. For example, when an amount is omitted in the journal, it will- not appear in the output. Similarly, when a transaction price is im-- plied but not written, it will not appear in the output. You can use- the -x/--explicit flag to make all amounts and transaction prices ex-- plicit, which can be useful for troubleshooting or for making your- journal more readable and robust against data entry errors. -x is also- implied by using any of -B,-V,-X,--value.-- Note, -x/--explicit will cause postings with a multi-commodity amount- (these can arise when a multi-commodity transaction has an implicit- amount) to be split into multiple single-commodity postings, keeping- the output parseable.-- With -B/--cost, amounts with transaction prices are converted to cost- using that price. This can be used for troubleshooting.-- With -m/--match and a STR argument, print will show at most one trans-- action: the one one whose description is most similar to STR, and is- most recent. STR should contain at least two characters. If there is- no similar-enough match, no transaction will be shown.-- With --new, for each FILE being read, hledger reads (and writes) a spe-- cial state file (.latest.FILE in the same directory), containing the- latest transaction date(s) that were seen last time FILE was read.- When this file is found, only transactions with newer dates (and new- transactions on the latest date) are printed. This is useful for ig-- noring already-seen entries in import data, such as downloaded CSV- files. Eg:-- $ hledger -f bank1.csv print --new- (shows transactions added since last print --new on this file)-- This assumes that transactions added to FILE always have same or in-- creasing dates, and that transactions on the same day do not get re-- ordered. See also the import command.-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, and (experimental)- json and sql.-- Here's an example of print's CSV output:-- $ hledger print -Ocsv- "txnidx","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","posting-status","posting-comment"- "1","2008/01/01","","","","income","","assets:bank:checking","1","$","","1","",""- "1","2008/01/01","","","","income","","income:salary","-1","$","1","","",""- "2","2008/06/01","","","","gift","","assets:bank:checking","1","$","","1","",""- "2","2008/06/01","","","","gift","","income:gifts","-1","$","1","","",""- "3","2008/06/02","","","","save","","assets:bank:saving","1","$","","1","",""- "3","2008/06/02","","","","save","","assets:bank:checking","-1","$","1","","",""- "4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","","1","",""- "4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","","1","",""- "4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","2","","",""- "5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","","1","",""- "5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","1","","",""-- o There is one CSV record per posting, with the parent transaction's- fields repeated.-- o The "txnidx" (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.)-- o The amount is separated into "commodity" (the symbol) and "amount"- (numeric quantity) fields.-- o The numeric amount is repeated in either the "credit" or "debit" col-- umn, for convenience. (Those names are not accurate in the account-- ing sense; it just puts negative amounts under credit and zero or- greater amounts under debit.)-- print-unique- print-unique- Print transactions which do not reuse an already-seen description.-- Example:-- $ cat unique.journal- 1/1 test- (acct:one) 1- 2/2 test- (acct:two) 2- $ LEDGER_FILE=unique.journal hledger print-unique- (-f option not supported)- 2015/01/01 test- (acct:one) 1-- register- register, reg, r- Show postings and their running total.-- The register command displays matched postings, across all accounts, in- date order, with their running total or running historical balance.- (See also the aregister command, which shows matched transactions in a- specific account.)-- register normally shows line per posting, but note that multi-commodity- amounts will occupy multiple lines (one line per commodity).-- It is typically used with a query selecting a particular account, to- see that account's activity:-- $ 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-- With --date2, it shows and sorts by secondary date instead.-- The --historical/-H 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:-- $ 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-- The --depth option limits the amount of sub-account detail displayed.-- The --average/-A 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 --empty (see below). It- is affected by --historical. It works best when showing just one ac-- count and one commodity.-- The --related/-r flag shows the other postings in the transactions of- the postings which would normally be shown.-- The --invert flag negates all amounts. For example, it can be used on- an income account where amounts are normally displayed as negative num-- bers. It's also useful to show postings on the checking account to-- gether with the related account:-- $ hledger register --related --invert assets:checking-- With a reporting interval, register shows summary postings, one per in-- terval, aggregating the postings to each account:-- $ hledger register --monthly income- 2008/01 income:salary $-1 $-1- 2008/06 income:gifts $-1 $-2-- Periods with no activity, and summary postings with a zero amount, are- not shown by default; use the --empty/-E flag to see them:-- $ 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-- Often, you'll want to see just one line per interval. The --depth op-- tion helps with this, causing subaccounts to be aggregated:-- $ hledger register --monthly assets --depth 1h- 2008/01 assets $1 $1- 2008/06 assets $-1 0- 2008/12 assets $-1 $-1-- Note when using report intervals, if you specify start/end dates these- will be adjusted outward if necessary to contain a whole number of in-- tervals. This ensures that the first and last intervals are full- length and comparable to the others in the report.-- Custom register output- register uses the full terminal width by default, except on windows.- You can override this by setting the COLUMNS environment variable (not- a bash shell variable) or by using the --width/-w option.-- The description and account columns normally share the space equally- (about half of (width - 40) each). You can adjust this by adding a de-- scription width as part of --width's argument, comma-separated: --width- W,D . Here's a diagram (won't display correctly in --help):-- <--------------------------------- width (W) ---------------------------------->- date (10) description (D) account (W-41-D) amount (12) balance (12)- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA-- and some examples:-- $ hledger reg # use terminal width (or 80 on windows)- $ hledger reg -w 100 # use width 100- $ COLUMNS=100 hledger reg # set with one-time environment variable- $ export COLUMNS=100; hledger reg # set till session end (or window resize)- $ hledger reg -w 100,40 # set overall width 100, description width 40- $ hledger reg -w $COLUMNS,40 # use terminal width, & description width 40-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, and (experimental)- json.-- register-match- register-match- Print the one posting whose transaction description is closest to DESC,- in the style of the register command. If there are multiple equally- good matches, it shows the most recent. Query options (options, not- arguments) can be used to restrict the search space. Helps ledger-au-- tosync detect already-seen transactions when importing.-- rewrite- rewrite- Print all transactions, rewriting the postings of matched transactions.- For now the only rewrite available is adding new postings, like print- --auto.-- 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 transac-- tion's first posting amount.-- Examples:-- $ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'- $ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'- $ hledger-rewrite.hs -f rewrites.hledger-- rewrites.hledger may consist of entries like:-- = ^income 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-- Note the single quotes to protect the dollar sign from bash, and the- two spaces between account and amount.-- More:-- $ hledger rewrite -- [QUERY] --add-posting "ACCT AMTEXPR" ...- $ hledger rewrite -- ^income --add-posting '(liabilities:tax) *.33'- $ hledger rewrite -- expenses:gifts --add-posting '(budget:gifts) *-1"'- $ hledger rewrite -- ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'-- Argument for --add-posting option is a usual posting of transaction- with an exception for amount specification. More precisely, you can- use '*' (star symbol) before the amount to indicate that that this is a- factor for an amount of original matched posting. If the amount in-- cludes a commodity name, the new posting amount will be in the new com-- modity; otherwise, it will be in the matched posting amount's commod-- ity.-- Re-write rules in a file- During the run this tool will execute so called "Automated Transac-- tions" found in any journal it process. I.e instead of specifying this- operations in command line you can put them in a journal file.-- $ rewrite-rules.journal-- Make contents look like this:-- = ^income- (liabilities:tax) *.33-- = expenses:gifts- budget:gifts *-1- assets:budget *1-- Note that '=' (equality symbol) that is used instead of date in trans-- actions you usually write. It indicates the query by which you want to- match the posting to add new ones.-- $ hledger rewrite -- -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal-- This is something similar to the commands pipeline:-- $ hledger rewrite -- -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \- | hledger rewrite -- -f - expenses:gifts --add-posting 'budget:gifts *-1' \- --add-posting 'assets:budget *1' \- > rewritten-tidy-output.journal-- It is important to understand that relative order of such entries in- journal is important. You can re-use result of previously added post-- ings.-- Diff output format- To use this tool for batch modification of your journal files you may- find useful output in form of unified diff.-- $ hledger rewrite -- --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'-- Output might look like:-- --- /tmp/examples/sample.journal- +++ /tmp/examples/sample.journal- @@ -18,3 +18,4 @@- 2008/01/01 income- - assets:bank:checking $1- + assets:bank:checking $1- income:salary- + (liabilities:tax) 0- @@ -22,3 +23,4 @@- 2008/06/01 gift- - assets:bank:checking $1- + assets:bank:checking $1- income:gifts- + (liabilities:tax) 0-- If you'll pass this through patch tool you'll get transactions contain-- ing the posting that matches your query be updated. Note that multiple- files might be update according to list of input files specified via- --file options and include directives inside of these files.-- Be careful. Whole transaction being re-formatted in a style of output- from hledger print.-- See also:-- https://github.com/simonmichael/hledger/issues/99-- rewrite vs. print --auto- This command predates print --auto, and currently does much the same- thing, but with these differences:-- o with multiple files, rewrite lets rules in any file affect all other- files. print --auto uses standard directive scoping; rules affect- only child files.-- o rewrite's query limits which transactions can be rewritten; all are- printed. print --auto's query limits which transactions are printed.-- o rewrite applies rules specified on command line or in the journal.- print --auto applies rules specified in the journal.-- roi- roi- Shows the time-weighted (TWR) and money-weighted (IRR) rate of return- on your investments.-- This command assumes that you have account(s) that hold nothing but- your investments and whenever you record current appraisal/valuation of- these investments you offset unrealized profit and loss into account(s)- that, again, hold nothing but unrealized profit and loss.-- Any transactions affecting balance of investment account(s) and not- originating from unrealized profit and loss account(s) are assumed to- be your investments or withdrawals.-- At a minimum, you need to supply a query (which could be just an ac-- count name) to select your investments with --inv, and another query to- identify your profit and loss transactions with --pnl.-- It will compute and display the internalized rate of return (IRR) and- time-weighted rate of return (TWR) for your investments for the time- period requested. Both rates of return are annualized before display,- regardless of the length of reporting interval.-- stats- stats- Show some journal statistics.-- The stats command displays summary information for the whole journal,- or a matched part of it. With a reporting interval, it shows a report- for each report period.-- Example:-- $ hledger stats- Main journal file : /src/hledger/examples/sample.journal- Included journal files :- Transactions span : 2008-01-01 to 2009-01-01 (366 days)- Last transaction : 2008-12-31 (2333 days ago)- Transactions : 5 (0.0 per day)- Transactions last 30 days: 0 (0.0 per day)- Transactions last 7 days : 0 (0.0 per day)- Payees/descriptions : 5- Accounts : 8 (depth 3)- Commodities : 1 ($)- Market prices : 12 ($)-- This command also supports output destination and output format selec-- tion.-- tags- tags- List the unique tag names used in the journal. With a TAGREGEX argu-- ment, only tag names matching the regular expression (case insensitive)- are shown. With QUERY arguments, only transactions matching the query- are considered.-- With the --values flag, the tags' unique values are listed instead.-- With --parsed flag, all tags or values are shown in the order they are- parsed from the input data, including duplicates.-- With -E/--empty, any blank/empty values will also be shown, otherwise- they are omitted.-- test- test- Run built-in unit tests.-- This command runs the unit tests built in to hledger and hledger-lib,- printing the results on stdout. If any test fails, the exit code will- be non-zero.-- This is mainly used by hledger developers, but you can also use it to- sanity-check the installed hledger executable on your platform. All- tests are expected to pass - if you ever see a failure, please report- as a bug!-- This command also accepts tasty test runner options, written after a --- (double hyphen). Eg to run only the tests in Hledger.Data.Amount, with- ANSI colour codes disabled:-- $ hledger test -- -pData.Amount --color=never-- For help on these, see https://github.com/feuerbach/tasty#options (--- --help currently doesn't show them).-- Add-on commands- hledger also searches for external add-on commands, and will include- these in the commands list. These are programs or scripts in your PATH- whose name starts with hledger- and ends with a recognised file exten-- sion (currently: no extension, bat,com,exe, hs,lhs,pl,py,rb,rkt,sh).-- Add-ons can be invoked like any hledger command, but there are a few- things to be aware of. Eg if the hledger-web add-on is installed,-- o hledger -h web shows hledger's help, while hledger web -h shows- hledger-web's help.-- o Flags specific to the add-on must have a preceding -- to hide them- from hledger. So hledger web --serve --port 9000 will be rejected;- you must use hledger web -- --serve --port 9000.-- o You can always run add-ons directly if preferred: hledger-web --serve- --port 9000.-- Add-ons are a relatively easy way to add local features or experiment- with new ideas. They can be written in any language, but haskell- scripts have a big advantage: they can use the same hledger (and- haskell) library functions that built-in commands do, for command-line- options, journal parsing, reporting, etc.-- Two important add-ons are the hledger-ui and hledger-web user inter-- faces. These are maintained and released along with hledger:-- ui- hledger-ui provides an efficient terminal interface.-- web- hledger-web provides a simple web interface.-- Third party add-ons, maintained separately from hledger, include:-- iadd- hledger-iadd is a more interactive, terminal UI replacement for the add- command.-- interest- hledger-interest generates interest transactions for an account accord-- ing to various schemes.-- A few more experimental or old add-ons can be found in hledger's bin/- directory. These are typically prototypes and not guaranteed to work.--ENVIRONMENT- LEDGER_FILE The journal file path when not specified with -f. Default:- ~/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.jour-- nal).-- A typical value is ~/DIR/YYYY.journal, where DIR is a version-con-- trolled finance directory and YYYY is the current year. Or ~/DIR/cur-- rent.journal, where current.journal is a symbolic link to YYYY.journal.-- On Mac computers, you can set this and other environment variables in a- more thorough way that also affects applications started from the GUI- (say, an Emacs dock icon). Eg on MacOS Catalina I have a ~/.MacOSX/en-- vironment.plist file containing-- {- "LEDGER_FILE" : "~/finance/current.journal"- }-- To see the effect you may need to killall Dock, or reboot.-- COLUMNS The screen width used by the register command. Default: the- full terminal width.-- NO_COLOR If this variable exists with any value, hledger will not use- ANSI color codes in terminal output. This overrides the- --color/--colour option.--FILES- Reads data from one or more files in hledger journal, timeclock, time-- dot, or CSV format specified with -f, or $LEDGER_FILE, or- $HOME/.hledger.journal (on windows, perhaps- C:/Users/USER/.hledger.journal).--LIMITATIONS- The need to precede addon command options with -- when invoked from- hledger is awkward.-- When input data contains non-ascii characters, a suitable system locale- must be configured (or there will be an unhelpful error). Eg on POSIX,- set LANG to something other than C.-- In a Microsoft Windows CMD window, non-ascii characters and colours are- not supported.-- On Windows, non-ascii characters may not display correctly when running- a hledger built in CMD in MSYS/CYGWIN, or vice-versa.-- In a Cygwin/MSYS/Mintty window, the tab key is not supported in hledger- add.-- Not all of Ledger's journal file syntax is supported. See file format- differences.-- On large data files, hledger is slower and uses more memory than- Ledger.--TROUBLESHOOTING- Here are some issues you might encounter when you run hledger (and re-- member you can also seek help from the IRC channel, mail list or bug- tracker):-- Successfully installed, but "No command 'hledger' found"- stack and cabal install binaries into a special directory, which should- be added to your PATH environment variable. Eg on unix-like systems,- that is ~/.local/bin and ~/.cabal/bin respectively.-- I set a custom LEDGER_FILE, but hledger is still using the default file- LEDGER_FILE should be a real environment variable, not just a shell- variable. The command env | grep LEDGER_FILE should show it. You may- need to use export. Here's an explanation.-- Getting errors like "Illegal byte sequence" or "Invalid or incomplete- multibyte or wide character" or "commitAndReleaseBuffer: invalid argu-- ment (invalid character)"- Programs compiled with GHC (hledger, haskell build tools, etc.) need to- have a UTF-8-aware locale configured in the environment, otherwise they- will fail with these kinds of errors when they encounter non-ascii- characters.-- To fix it, set the LANG environment variable to some locale which sup-- ports UTF-8. The locale you choose must be installed on your system.-- Here's an example of setting LANG temporarily, on Ubuntu GNU/Linux:-- $ file my.journal- my.journal: UTF-8 Unicode text # the file is UTF8-encoded- $ echo $LANG- C # LANG is set to the default locale, which does not support UTF8- $ locale -a # which locales are installed ?- C- en_US.utf8 # here's a UTF8-aware one we can use- POSIX- $ LANG=en_US.utf8 hledger -f my.journal print # ensure it is used for this command-- If available, C.UTF-8 will also work. If your preferred locale isn't- listed by locale -a, you might need to install it. Eg on Ubuntu/De-- bian:-- $ apt-get install language-pack-fr- $ locale -a- C- en_US.utf8- fr_BE.utf8- fr_CA.utf8- fr_CH.utf8- fr_FR.utf8- fr_LU.utf8- POSIX- $ LANG=fr_FR.utf8 hledger -f my.journal print-- Here's how you could set it permanently, if you use a bash shell:-- $ echo "export LANG=en_US.utf8" >>~/.bash_profile- $ bash --login-- Exact spelling and capitalisation may be important. Note the differ-- ence on MacOS (UTF-8, not utf8). Some platforms (eg ubuntu) allow- variant spellings, but others (eg macos) require it to be exact:-- $ locale -a | grep -iE en_us.*utf- en_US.UTF-8- $ LANG=en_US.UTF-8 hledger -f my.journal print----REPORTING BUGS- Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel- or hledger mail list)---AUTHORS- Simon Michael <simon@joyful.com> and contributors---COPYRIGHT- Copyright (C) 2007-2019 Simon Michael.- Released under GNU GPL v3 or later.---SEE ALSO- hledger(1), hledger-ui(1), hledger-web(1), hledger-api(1),- hledger_csv(5), hledger_journal(5), hledger_timeclock(5), hledger_time-- dot(5), ledger(1)-- http://hledger.org----hledger 1.18.99 September 2020 hledger(1)+ -s --strict+ do extra error checking (check that all posted accounts are de-+ clared)++ General reporting options:++ -b --begin=DATE+ include postings/txns on or after this date++ -e --end=DATE+ include postings/txns before this date++ -D --daily+ multiperiod/multicolumn report by day++ -W --weekly+ multiperiod/multicolumn report by week++ -M --monthly+ multiperiod/multicolumn report by month++ -Q --quarterly+ multiperiod/multicolumn report by quarter++ -Y --yearly+ multiperiod/multicolumn report by year++ -p --period=PERIODEXP+ set start date, end date, and/or reporting interval all at once+ using period expressions syntax++ --date2+ match the secondary date instead (see command help for other ef-+ fects)++ -U --unmarked+ include only unmarked postings/txns (can combine with -P or -C)++ -P --pending+ include only pending postings/txns++ -C --cleared+ include only cleared postings/txns++ -R --real+ include only non-virtual postings++ -NUM --depth=NUM+ hide/aggregate accounts or postings more than NUM levels deep++ -E --empty+ show items with zero amount, normally hidden (and vice-versa in+ hledger-ui/hledger-web)++ -B --cost+ convert amounts to their cost/selling amount at transaction time++ -V --market+ convert amounts to their market value in default valuation com-+ modities++ -X --exchange=COMM+ convert amounts to their market value in commodity COMM++ --value+ convert amounts to cost or market value, more flexibly than+ -B/-V/-X++ --infer-value+ with -V/-X/--value, also infer market prices from transactions++ --auto apply automated posting rules to modify transactions.++ --forecast+ generate future transactions from periodic transaction rules,+ for the next 6 months or till report end date. In hledger-ui,+ also make ordinary future transactions visible.++ --color=WHEN (or --colour=WHEN)+ Should color-supporting commands use ANSI color codes in text+ output. 'auto' (default): whenever stdout seems to be a color-+ supporting terminal. 'always' or 'yes': always, useful eg when+ piping output into 'less -R'. 'never' or 'no': never. A+ NO_COLOR environment variable overrides this.++ When a reporting option appears more than once in the command line, the+ last one takes precedence.++ Some reporting options can also be written as query arguments.++ Command options+ To see options for a particular command, including command-specific op-+ tions, run: hledger COMMAND -h.++ Command-specific options must be written after the command name, eg:+ hledger print -x.++ Additionally, if the command is an addon, you may need to put its op-+ tions after a double-hyphen, eg: hledger ui -- --watch. Or, you can+ run the addon executable directly: hledger-ui --watch.++ Command arguments+ Most hledger commands accept arguments after the command name, which+ are often a query, filtering the data in some way.++ You can save a set of command line options/arguments in a file, and+ then reuse them by writing @FILENAME as a command line argument. Eg:+ hledger bal @foo.args. (To prevent this, eg if you have an argument+ that begins with a literal @, precede it with --, eg: hledger bal --+ @ARG).++ Inside the argument file, each line should contain just one option or+ argument. Avoid the use of spaces, except inside quotes (or you'll see+ a confusing error). Between a flag and its argument, use = (or noth-+ ing). Bad:++ assets depth:2+ -X USD++ Good:++ assets+ depth:2+ -X=USD++ For special characters (see below), use one less level of quoting than+ you would at the command prompt. Bad:++ -X"$"++ Good:++ -X$++ See also: Save frequently used options.++ Queries+ One of hledger's strengths is being able to quickly report on precise+ subsets of your data. Most commands accept an optional query expres-+ sion, written as arguments after the command name, to filter the data+ by date, account name or other criteria. The syntax is similar to a+ web search: one or more space-separated search terms, quotes to enclose+ whitespace, prefixes to match specific fields, a not: prefix to negate+ the match.++ We do not yet support arbitrary boolean combinations of search terms;+ instead most commands show transactions/postings/accounts which match+ (or negatively match):++ o any of the description terms AND++ o any of the account terms AND++ o any of the status terms AND++ o all the other terms.++ The print command instead shows transactions which:++ o match any of the description terms AND++ o have any postings matching any of the positive account terms AND++ o have no postings matching any of the negative account terms AND++ o match all the other terms.++ The following kinds of search terms can be used. Remember these can+ also be prefixed with not:, eg to exclude a particular subaccount.++ REGEX, acct:REGEX+ match account names by this regular expression. (With no pre-+ fix, acct: is assumed.) same as above++ amt:N, amt:<N, amt:<=N, amt:>N, amt:>=N+ match postings with a single-commodity amount that is equal to,+ less than, or greater than N. (Multi-commodity amounts are not+ tested, and will always match.) 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.++ code:REGEX+ match by transaction code (eg check number)++ cur:REGEX+ match postings or transactions including any amounts whose cur-+ rency/commodity symbol is fully matched by REGEX. (For a par-+ tial match, use .*REGEX.*). Note, to match characters which are+ regex-significant, like the dollar sign ($), you need to prepend+ \. And when using the command line you need to add one more+ level of quoting to hide it from the shell, so eg do: hledger+ print cur:'\$' or hledger print cur:\\$.++ desc:REGEX+ match transaction descriptions.++ date:PERIODEXPR+ match dates within the specified period. PERIODEXPR is a period+ expression (with no report interval). Examples: date:2016,+ date:thismonth, date:2000/2/1-2/15, date:lastweek-. If the+ --date2 command line flag is present, this matches secondary+ dates instead.++ date2:PERIODEXPR+ match secondary dates within the specified period.++ depth:N+ match (or display, depending on command) accounts at or above+ this depth++ note:REGEX+ match transaction notes (part of description right of |, or+ whole description when there's no |)++ payee:REGEX+ match transaction payee/payer names (part of description left of+ |, or whole description when there's no |)++ real:, real:0+ match real or virtual postings respectively++ status:, status:!, status:*+ match unmarked, pending, or cleared transactions respectively++ tag:REGEX[=REGEX]+ match by tag name, and optionally also by tag value. Note a+ tag: query is considered to match a transaction if it matches+ any of the postings. Also remember that postings inherit the+ tags of their parent transaction.++ The following special search term is used automatically in hledger-web,+ only:++ inacct:ACCTNAME+ tells hledger-web to show the transaction register for this ac-+ count. Can be filtered further with acct etc.++ Some of these can also be expressed as command-line options (eg depth:2+ is equivalent to --depth 2). Generally you can mix options and query+ arguments, and the resulting query will be their intersection (perhaps+ excluding the -p/--period option).++ Special characters in arguments and queries+ In shell command lines, option and argument values which contain "prob-+ lematic" characters, ie spaces, and also characters significant to your+ shell such as <, >, (, ), | and $, should be escaped by enclosing them+ in quotes or by writing backslashes before the characters. Eg:++ hledger register -p 'last year' "accounts receivable (receiv-+ able|payable)" amt:\>100.++ More escaping+ Characters significant both to the shell and in regular expressions may+ need one extra level of escaping. These include parentheses, the pipe+ symbol and the dollar sign. Eg, to match the dollar symbol, bash users+ should do:++ hledger balance cur:'\$'++ or:++ hledger balance cur:\\$++ Even more escaping+ When hledger runs an addon executable (eg you type hledger ui, hledger+ runs hledger-ui), it de-escapes command-line options and arguments+ once, so you might need to triple-escape. Eg in bash, running the ui+ command and matching the dollar sign, it's:++ hledger ui cur:'\\$'++ or:++ hledger ui cur:\\\\$++ If you asked why four slashes above, this may help:++ unescaped: $+ escaped: \$+ double-escaped: \\$+ triple-escaped: \\\\$++ (The number of backslashes in fish shell is left as an exercise for the+ reader.)++ You can always avoid the extra escaping for addons by running the addon+ directly:++ hledger-ui cur:\\$++ Less escaping+ Inside an argument file, or in the search field of hledger-ui or+ hledger-web, or at a GHCI prompt, you need one less level of escaping+ than at the command line. And backslashes may work better than quotes.+ Eg:++ ghci> :main balance cur:\$++ Unicode characters+ hledger is expected to handle non-ascii characters correctly:++ o they should be parsed correctly in input files and on the command+ line, by all hledger tools (add, iadd, hledger-web's search/add/edit+ forms, etc.)++ o they should be displayed correctly by all hledger tools, and on-+ screen alignment should be preserved.++ This requires a well-configured environment. Here are some tips:++ o A system locale must be configured, and it must be one that can de-+ code the characters being used. In bash, you can set a locale like+ this: export LANG=en_US.UTF-8. There are some more details in Trou-+ bleshooting. This step is essential - without it, hledger will quit+ on encountering a non-ascii character (as with all GHC-compiled pro-+ grams).++ o your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)+ must support unicode++ o the terminal must be using a font which includes the required unicode+ glyphs++ o the terminal should be configured to display wide characters as dou-+ ble width (for report alignment)++ o 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 stan-+ dard 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).++ Input files+ hledger reads transactions from a data file (and the add command writes+ to it). By default this file is $HOME/.hledger.journal (or on Windows,+ something like C:/Users/USER/.hledger.journal). You can override this+ with the $LEDGER_FILE environment variable:++ $ setenv LEDGER_FILE ~/finance/2016.journal+ $ hledger stats++ or with the -f/--file option:++ $ hledger -f /some/file stats++ The file name - (hyphen) means standard input:++ $ cat some.journal | hledger -f-++ Usually the data file is in hledger's journal format, but it can be in+ any of the supported file formats, which currently are:++ Reader: Reads: Used for file exten-+ sions:+ -----------------------------------------------------------------------------+ journal hledger journal files and some Ledger .journal .j .hledger+ journals, for transactions .ledger+ time- timeclock files, for precise time log- .timeclock+ clock ging+ timedot timedot files, for approximate time .timedot+ logging+ csv comma/semicolon/tab/other-separated .csv .ssv .tsv+ values, for data import++ hledger detects the format automatically based on the file extensions+ shown above. If it can't recognise the file extension, it assumes+ journal format. So for non-journal files, it's important to use a+ recognised file extension, so as to either read successfully or to show+ relevant error messages.++ When you can't ensure the right file extension, not to worry: you can+ force a specific reader/format by prefixing the file path with the for-+ mat and a colon. Eg to read a .dat file as csv:++ $ hledger -f csv:/some/csv-file.dat stats+ $ echo 'i 2009/13/1 08:00:00' | hledger print -ftimeclock:-++ You can specify multiple -f options, to read multiple files as one big+ journal. There are some limitations with this:++ o directives in one file will not affect the other files++ o balance assertions will not see any account balances from previous+ files++ If you need either of those things, you can++ o use a single parent file which includes the others++ o or concatenate the files into one before reading, eg: cat a.journal+ b.journal | hledger -f- CMD.++ Strict mode+ hledger checks input files for valid data. By default, the most impor-+ tant errors are detected, while still accepting easy journal files+ without a lot of declarations:++ o Are the input files parseable, with valid syntax ?++ o Are all transactions balanced ?++ o Do all balance assertions pass ?++ With the -s/--strict flag, additional checks are performed:++ o Are all accounts posted to, declared with an account directive ?+ (Account error checking)++ o Are all commodities declared with a commodity directive ? (Commodity+ error checking)++ See also: https://hledger.org/checking-for-errors.html++ experimental.++ 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:++ $ hledger print > foo.txt++ Some commands (print, register, stats, the balance commands) also pro-+ vide the -o/--output-file option, which does the same thing without+ needing the shell. Eg:++ $ hledger print -o foo.txt+ $ hledger print -o - # write to stdout (the default)++ Output format+ Some commands (print, register, the balance commands) offer a choice of+ output format. In addition to the usual plain text format (txt), there+ are CSV (csv), HTML (html), JSON (json) and SQL (sql). This is con-+ trolled by the -O/--output-format option:++ $ hledger print -O csv++ or, by a file extension specified with -o/--output-file:++ $ hledger balancesheet -o foo.html # write HTML to foo.html++ The -O option can be used to override the file extension if needed:++ $ hledger balancesheet -o foo.txt -O html # write HTML to foo.txt++ Some notes about JSON output:++ o This feature is marked experimental, and not yet much used; you+ should expect our JSON to evolve. Real-world feedback is welcome.++ o Our JSON is rather large and verbose, as it is quite a faithful rep-+ resentation of hledger's internal data types. To understand the+ JSON, read the Haskell type definitions, which are mostly in+ https://github.com/simonmichael/hledger/blob/master/hledger-+ lib/Hledger/Data/Types.hs.++ o hledger represents quantities as Decimal values storing up to 255+ significant digits, eg for repeating decimals. Such numbers can+ arise in practice (from automatically-calculated transaction prices),+ and would break most JSON consumers. So in JSON, we show quantities+ as simple Numbers with at most 10 decimal places. We don't limit the+ number of integer digits, but that part is under your control. We+ hope this approach will not cause problems in practice; if you find+ otherwise, please let us know. (Cf #1195)++ Notes about SQL output:++ o SQL output is also marked experimental, and much like JSON could use+ real-world feedback.++ o SQL output is expected to work with sqlite, MySQL and PostgreSQL++ o SQL output is structured with the expectations that statements will+ be executed in the empty database. If you already have tables cre-+ ated via SQL output of hledger, you would probably want to either+ clear tables of existing data (via delete or truncate SQL statements)+ or drop tables completely as otherwise your postings will be duped.++ Regular expressions+ hledger uses regular expressions in a number of places:++ o query terms, on the command line and in the hledger-web search form:+ REGEX, desc:REGEX, cur:REGEX, tag:...=REGEX++ o CSV rules conditional blocks: if REGEX ...++ o account alias directives and options: alias /REGEX/ = REPLACEMENT,+ --alias /REGEX/=REPLACEMENT++ hledger's regular expressions come from the regex-tdfa library. If+ they're not doing what you expect, it's important to know exactly what+ they support:++ 1. they are case insensitive++ 2. they are infix matching (they do not need to match the entire thing+ being matched)++ 3. they are POSIX ERE (extended regular expressions)++ 4. they also support GNU word boundaries (\b, \B, \<, \>)++ 5. they do not support backreferences; if you write \1, it will match+ the digit 1. Except when doing text replacement, eg in account+ aliases, where backreferences can be used in the replacement string+ to reference capturing groups in the search regexp.++ 6. they do not support mode modifiers ((?s)), character classes (\w,+ \d), or anything else not mentioned above.++ Some things to note:++ o In the alias directive and --alias option, regular expressions must+ be enclosed in forward slashes (/REGEX/). Elsewhere in hledger,+ these are not required.++ o In queries, to match a regular expression metacharacter like $ as a+ literal character, prepend a backslash. Eg to search for amounts+ with the dollar sign in hledger-web, write cur:\$.++ o On the command line, some metacharacters like $ have a special mean-+ ing to the shell and so must be escaped at least once more. See Spe-+ cial characters.++ Smart dates+ hledger's user interfaces accept a flexible "smart date" syntax (unlike+ dates in the journal file). Smart dates allow some english words, can+ be relative to today's date, and can have less-significant date parts+ omitted (defaulting to 1).++ Examples:++ 2004/10/1, 2004-01-01, exact date, several separators allowed. Year+ 2004.9.1 is 4+ digits, month is 1-12, day is 1-31+ 2004 start of year+ 2004/10 start of month+ 10/1 month and day in current year+ 21 day in current month+ october, oct start of month in current year++ yesterday, today, tomor- -1, 0, 1 days from today+ row+ last/this/next -1, 0, 1 periods from the current period+ day/week/month/quar-+ ter/year+ 20181201 8 digit YYYYMMDD with valid year month and day+ 201812 6 digit YYYYMM with valid year and month++ Counterexamples - malformed digit sequences might give surprising re-+ sults:++ 201813 6 digits with an invalid month is parsed as start of+ 6-digit year+ 20181301 8 digits with an invalid month is parsed as start of+ 8-digit year+ 20181232 8 digits with an invalid day gives an error+ 201801012 9+ digits beginning with a valid YYYYMMDD gives an error++ Report start & end date+ Most hledger reports show the full span of time represented by the+ journal data, by default. So, the effective report start and end dates+ will be the earliest and latest transaction or posting dates found in+ the journal.++ Often you will want to see a shorter time span, such as the current+ month. You can specify a start and/or end date using -b/--begin,+ -e/--end, -p/--period or a date: query (described below). All of these+ accept the smart date syntax.++ Some notes:++ o As in Ledger, end dates are exclusive, so you need to write the date+ after the last day you want to include.++ o As noted in reporting options: among start/end dates specified with+ options, the last (i.e. right-most) option takes precedence.++ o The effective report start and end dates are the intersection of the+ start/end dates from options and that from date: queries. That is,+ date:2019-01 date:2019 -p'2000 to 2030' yields January 2019, the+ smallest common time span.++ Examples:++ -b 2016/3/17 begin on St. Patrick's day 2016+ -e 12/1 end at the start of december 1st of the current year+ (11/30 will be the last date included)+ -b thismonth all transactions on or after the 1st of the current month+ -p thismonth all transactions in the current month+ date:2016/3/17.. the above written as queries instead (.. can also be re-+ placed with -)+ date:..12/1+ date:thismonth..+ date:thismonth++ Report intervals+ A report interval can be specified so that commands like register, bal-+ ance and activity will divide their reports into multiple subperiods.+ The basic intervals can be selected with one of -D/--daily,+ -W/--weekly, -M/--monthly, -Q/--quarterly, or -Y/--yearly. More com-+ plex intervals may be specified with a period expression. Report in-+ tervals can not be specified with a query.++ Period expressions+ The -p/--period option accepts period expressions, a shorthand way of+ expressing a start date, end date, and/or report interval all at once.++ Here's a basic period expression specifying the first quarter of 2009.+ Note, hledger always treats start dates as inclusive and end dates as+ exclusive:++ -p "from 2009/1/1 to 2009/4/1"++ Keywords like "from" and "to" are optional, and so are the spaces, as+ long as you don't run two dates together. "to" can also be written as+ ".." or "-". These are equivalent to the above:++ -p "2009/1/1 2009/4/1"+ -p2009/1/1to2009/4/1+ -p2009/1/1..2009/4/1++ Dates are smart dates, so if the current year is 2009, the above can+ also be written as:++ -p "1/1 4/1"+ -p "january-apr"+ -p "this year to 4/1"++ If you specify only one date, the missing start or end date will be the+ earliest or latest transaction in your journal:++ -p "from 2009/1/1" everything after january+ 1, 2009+ -p "from 2009/1" the same+ -p "from 2009" the same+ -p "to 2009" everything before january+ 1, 2009++ A single date with no "from" or "to" defines both the start and end+ date like so:++ -p "2009" the year 2009; equivalent+ to "2009/1/1 to 2010/1/1"+ -p "2009/1" the month of jan; equiva-+ lent to "2009/1/1 to+ 2009/2/1"+ -p "2009/1/1" just that day; equivalent+ to "2009/1/1 to 2009/1/2"++ Or you can specify a single quarter like so:++ -p "2009Q1" first quarter of 2009,+ equivalent to "2009/1/1 to+ 2009/4/1"+ -p "q4" fourth quarter of the cur-+ rent year++ The argument of -p can also begin with, or be, a report interval ex-+ pression. The basic report intervals are daily, weekly, monthly, quar-+ terly, or yearly, which have the same effect as the -D,-W,-M,-Q, or -Y+ flags. Between report interval and start/end dates (if any), the word+ in is optional. Examples:++ -p "weekly from 2009/1/1 to 2009/4/1"+ -p "monthly in 2008"+ -p "quarterly"++ Note that weekly, monthly, quarterly and yearly intervals will always+ start on the first day on week, month, quarter or year accordingly, and+ will end on the last day of same period, even if associated period ex-+ pression specifies different explicit start and end date.++ For example:++ -p "weekly from 2009/1/1 starts on 2008/12/29, closest preceding Mon-+ to 2009/4/1" day+ -p "monthly in starts on 2018/11/01+ 2008/11/25"+ -p "quarterly from starts on 2009/04/01, ends on 2009/06/30,+ 2009-05-05 to 2009-06-01" which are first and last days of Q2 2009+ -p "yearly from starts on 2009/01/01, first day of 2009+ 2009-12-29"++ The following more complex report intervals are also supported: bi-+ weekly, fortnightly, bimonthly, every day|week|month|quarter|year, ev-+ ery N days|weeks|months|quarters|years.++ All of these will start on the first day of the requested period and+ end on the last one, as described above.++ Examples:++ -p "bimonthly from 2008" periods will have boundaries on 2008/01/01,+ 2008/03/01, ...+ -p "every 2 weeks" starts on closest preceding Monday+ -p "every 5 month from periods will have boundaries on 2009/03/01,+ 2009/03" 2009/08/01, ...++ If you want intervals that start on arbitrary day of your choosing and+ span a week, month or year, you need to use any of the following:++ every Nth day of week, every WEEKDAYNAME (eg+ mon|tue|wed|thu|fri|sat|sun), every Nth day [of month], every Nth WEEK-+ DAYNAME [of month], every MM/DD [of year], every Nth MMM [of year], ev-+ ery MMM Nth [of year].++ Examples:++ -p "every 2nd day of periods will go from Tue to Tue+ week"+ -p "every Tue" same+ -p "every 15th day" period boundaries will be on 15th of each+ month+ -p "every 2nd Monday" period boundaries will be on second Monday of+ each month+ -p "every 11/05" yearly periods with boundaries on 5th of Nov+ -p "every 5th Nov" same+ -p "every Nov 5th" same++ Show historical balances at end of 15th each month (N is exclusive end+ date):++ hledger balance -H -p "every 16th day"++ Group postings from start of wednesday to end of next tuesday (N is+ start date and exclusive end date):++ hledger register checking -p "every 3rd day of week"++ Depth limiting+ With the --depth N option (short form: -N), commands like account, bal-+ ance and register will show only the uppermost accounts in the account+ tree, down to level N. Use this when you want a summary with less de-+ tail. This flag has the same effect as a depth: query argument (so -2,+ --depth=2 or depth:2 are equivalent).++ Pivoting+ Normally hledger sums amounts, and organizes them in a hierarchy, based+ on account name. The --pivot FIELD option causes it to sum and orga-+ nize hierarchy based on the value of some other field instead. FIELD+ can be: code, description, payee, note, or the full name (case insensi-+ tive) of any tag. As with account names, values containing colon:sepa-+ rated:parts will be displayed hierarchically in reports.++ --pivot is a general option affecting all reports; you can think of+ hledger transforming the journal before any other processing, replacing+ every posting's account name with the value of the specified field on+ that posting, inheriting it from the transaction or using a blank value+ if it's not present.++ An example:++ 2016/02/16 Member Fee Payment+ assets:bank account 2 EUR+ income:member fees -2 EUR ; member: John Doe++ Normal balance report showing account names:++ $ hledger balance+ 2 EUR assets:bank account+ -2 EUR income:member fees+ --------------------+ 0++ Pivoted balance report, using member: tag values instead:++ $ hledger balance --pivot member+ 2 EUR+ -2 EUR John Doe+ --------------------+ 0++ One way to show only amounts with a member: value (using a query, de-+ scribed below):++ $ hledger balance --pivot member tag:member=.+ -2 EUR John Doe+ --------------------+ -2 EUR++ Another way (the acct: query matches against the pivoted "account+ name"):++ $ hledger balance --pivot member acct:.+ -2 EUR John Doe+ --------------------+ -2 EUR++ Valuation+ Instead of reporting amounts in their original commodity, hledger can+ convert them to cost/sale amount (using the conversion rate recorded in+ the transaction), or to market value (using some market price on a cer-+ tain date). This is controlled by the --value=TYPE[,COMMODITY] option,+ but we also provide the simpler -B/-V/-X flags, and usually one of+ those is all you need.++ -B: Cost+ The -B/--cost flag converts amounts to their cost or sale amount at+ transaction time, if they have a transaction price specified.++ -V: Value+ The -V/--market flag converts amounts to market value in their default+ valuation commodity, using the market prices in effect on the valuation+ date(s), if any. More on these in a minute.++ -X: Value in specified commodity+ The -X/--exchange=COMM option is like -V, except you tell it which cur-+ rency you want to convert to, and it tries to convert everything to+ that.++ Valuation date+ Since market prices can change from day to day, market value reports+ have a valuation date (or more than one), which determines which market+ prices will be used.++ For single period reports, if an explicit report end date is specified,+ that will be used as the valuation date; otherwise the valuation date+ is "today".++ For multiperiod reports, each column/period is valued on the last day+ of the period, by default.++ Market prices+ (experimental)++ 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 :++ 1. A declared market price or inferred market price: A's latest market+ price in B on or before the valuation date as declared by a P direc-+ tive, or (with the --infer-value flag) inferred from transaction+ prices.++ 2. A reverse market price: the inverse of a declared or inferred market+ price from B to A.++ 3. A a forward chain of market prices: a synthetic price formed by com-+ bining the shortest chain of "forward" (only 1 above) market prices,+ leading from A to B.++ 4. A any chain of market prices: a chain of any market prices, includ-+ ing both forward and reverse prices (1 and 2 above), leading from A+ to B.++ Amounts for which no applicable market price can be found, are not con-+ verted.++ --infer-value: market prices from transactions+ (experimental)++ 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 transaction prices as additional market+ prices (as Ledger does) ? We could produce value reports without need-+ ing P directives at all.++ Adding the --infer-value flag to -V, -X or --value enables this. So+ for example, hledger bs -V --infer-value will get market prices both+ from P directives and from transactions.++ There is a downside: value reports can sometimes be affected in confus-+ ing/undesired ways by your journal entries. If this happens to you,+ read all of this Valuation section carefully, and try adding --debug or+ --debug=2 to troubleshoot.++ --infer-value can infer market prices from:++ o multicommodity transactions with explicit prices (@/@@)++ o multicommodity transactions with implicit prices (no @, two commodi-+ ties, unbalanced). (With these, the order of postings matters.+ hledger print -x can be useful for troubleshooting.)++ o but not, currently, from "more correct" multicommodity transactions+ (no @, multiple commodities, balanced).++ Valuation commodity+ (experimental)++ When you specify a valuation commodity (-X COMM or --value TYPE,COMM):+ hledger will convert all amounts to COMM, wherever it can find a suit-+ able market price (including by reversing or chaining prices).++ When you leave the valuation commodity unspecified (-V or --value+ TYPE):+ For each commodity A, hledger picks a default valuation commodity as+ follows, in this order of preference:++ 1. The price commodity from the latest P-declared market price for A on+ or before valuation date.++ 2. 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.)++ 3. If there are no P directives at all (any commodity or date) and the+ --infer-value flag is used: the price commodity from the latest+ transaction-inferred price for A on or before valuation date.++ This means:++ o If you have P directives, they determine which commodities -V will+ convert, and to what.++ o If you have no P directives, and use the --infer-value flag, transac-+ tion prices determine it.++ Amounts for which no valuation commodity can be found are not con-+ verted.++ Simple valuation examples+ Here are some quick examples of -V:++ ; one euro is worth this many dollars from nov 1+ P 2016/11/01 EUR $1.10++ ; purchase some euros on nov 3+ 2016/11/3+ assets:euros EUR100+ assets:checking++ ; the euro is worth fewer dollars by dec 21+ P 2016/12/21 EUR $1.03++ How many euros do I have ?++ $ hledger -f t.j bal -N euros+ EUR100 assets:euros++ What are they worth at end of nov 3 ?++ $ hledger -f t.j bal -N euros -V -e 2016/11/4+ $110.00 assets:euros++ What are they worth after 2016/12/21 ? (no report end date specified,+ defaults to today)++ $ hledger -f t.j bal -N euros -V+ $103.00 assets:euros++ --value: Flexible valuation+ -B, -V and -X are special cases of the more general --value option:++ --value=TYPE[,COMM] TYPE is cost, then, end, now or YYYY-MM-DD.+ COMM is an optional commodity symbol.+ Shows amounts converted to:+ - cost commodity using transaction prices (then optionally to COMM using market prices at period end(s))+ - 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++ The TYPE part selects cost or value and valuation date:++ --value=cost+ Convert amounts to cost, using the prices recorded in transac-+ tions.++ --value=then+ Convert amounts to their value in the default valuation commod-+ ity, using market prices on each posting's date. This is cur-+ rently supported only by the print and register commands.++ --value=end+ Convert amounts to their value in the default valuation commod-+ ity, using market prices on the last day of the report period+ (or if unspecified, the journal's end date); or in multiperiod+ reports, market prices on the last day of each subperiod.++ --value=now+ Convert amounts to their value in the default valuation commod-+ ity using current market prices (as of when report is gener-+ ated).++ --value=YYYY-MM-DD+ Convert amounts to their value in the default valuation commod-+ ity using market prices on this date.++ To select a different valuation commodity, add the optional ,COMM part:+ a comma, then the target commodity's symbol. Eg: --value=now,EUR.+ hledger will do its best to convert amounts to this commodity, deducing+ market prices as described above.++ More valuation examples+ Here are some examples showing the effect of --value, as seen with+ print:++ 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 @ 5 B++ 2000-02-01+ (a) 1 A @ 6 B++ 2000-03-01+ (a) 1 A @ 7 B++ Show the cost of each posting:++ $ hledger -f- print --value=cost+ 2000-01-01+ (a) 5 B++ 2000-02-01+ (a) 6 B++ 2000-03-01+ (a) 7 B++ Show the value as of the last day of the report period (2000-02-29):++ $ hledger -f- print --value=end date:2000/01-2000/03+ 2000-01-01+ (a) 2 B++ 2000-02-01+ (a) 2 B++ With no report period specified, that shows the value as of the last+ day of the journal (2000-03-01):++ $ hledger -f- print --value=end+ 2000-01-01+ (a) 3 B++ 2000-02-01+ (a) 3 B++ 2000-03-01+ (a) 3 B++ Show the current value (the 2000-04-01 price is still in effect today):++ $ hledger -f- print --value=now+ 2000-01-01+ (a) 4 B++ 2000-02-01+ (a) 4 B++ 2000-03-01+ (a) 4 B++ Show the value on 2000/01/15:++ $ 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++ You may need to explicitly set a commodity's display style, when re-+ verse prices are used. Eg this output might be surprising:++ P 2000-01-01 A 2B++ 2000-01-01+ a 1B+ b++ $ hledger print -x -X A+ 2000-01-01+ a 0+ b 0++ Explanation: because there's no amount or commodity directive specify-+ ing a display style for A, 0.5A gets the default style, which shows no+ decimal digits. Because the displayed amount looks like zero, the com-+ modity symbol and minus sign are not displayed either. Adding a com-+ modity directive sets a more useful display style for A:++ P 2000-01-01 A 2B+ commodity 0.00A++ 2000-01-01+ a 1B+ b++ $ hledger print -X A+ 2000-01-01+ a 0.50A+ b -0.50A++ Effect of valuation on reports+ Here is a reference for how valuation is supposed to affect each part+ of hledger's reports (and a glossary). (It's wide, you'll have to+ scroll sideways.) It may be useful when troubleshooting. If you find+ problems, please report them, ideally with a reproducible example. Re-+ lated: #329, #1083.++ Report type -B, -V, -X --value=then --value=end --value=DATE,+ --value=cost --value=now+ --------------------------------------------------------------------------------------------+ print+ posting cost value at re- value at value at re- value at+ amounts port end or posting date port or jour- DATE/today+ today nal end+ balance as- unchanged unchanged unchanged unchanged unchanged+ ser-+ tions/as-+ signments++ register+ starting cost value at day not sup- value at day value at+ balance before report ported before report DATE/today+ (-H) or journal or journal+ start start+ posting cost value at re- value at value at re- value at+ amounts port end or posting date port or jour- DATE/today+ today nal end+ summary summarised value at pe- sum of post- value at pe- value at+ posting cost riod ends ings in in- riod ends DATE/today+ amounts terval, val-+ with report ued at in-+ interval terval start+ running to- sum/average sum/average sum/average sum/average sum/average+ tal/average of displayed of displayed of displayed of displayed of displayed+ values values values values values++ balance+ (bs, bse,+ cf, is)+ balance sums of costs value at re- not sup- value at re- value at+ changes port end or ported port or jour- DATE/today of+ today of sums nal end of sums of post-+ of postings sums of post- ings+ ings+ budget like balance like balance not sup- like balances like balance+ amounts changes changes ported changes+ (--budget)+ grand total sum of dis- sum of dis- not sup- sum of dis- sum of dis-+ played values played values ported played values played values++ balance+ (bs, bse,+ cf, is)+ with report+ interval+ starting sums of costs value at re- not sup- value at re- sums of post-+ balances of postings port start of ported port start of ings before+ (-H) before report sums of all sums of all report start+ start postings be- postings be-+ fore report fore report+ start start+++++++ balance sums of costs same as not sup- balance value at+ changes of postings --value=end ported change in DATE/today of+ (bal, is, in period each period, sums of post-+ bs valued at pe- ings+ --change, riod ends+ cf+ --change)+ end bal- sums of costs same as not sup- period end value at+ ances (bal of postings --value=end ported balances, DATE/today of+ -H, is --H, from before valued at pe- sums of post-+ bs, cf) report start riod ends ings+ to period end+ budget like balance like balance not sup- like balances like balance+ amounts changes/end changes/end ported changes/end+ (--budget) balances balances balances+ row totals, sums, aver- sums, aver- not sup- sums, aver- sums, aver-+ row aver- ages of dis- ages of dis- ported ages of dis- ages of dis-+ ages (-T, played values played values played values played values+ -A)+ column to- sums of dis- sums of dis- not sup- sums of dis- sums of dis-+ tals played values played values ported played values played values+ grand to- sum, average sum, average not sup- sum, average sum, average+ tal, grand of column to- of column to- ported of column to- of column to-+ average tals tals tals tals+++ --cumulative is omitted to save space, it works like -H but with a zero+ starting balance.++ Glossary:++ cost calculated using price(s) recorded in the transaction(s).++ value market value using available market price declarations, or the+ unchanged amount if no conversion rate can be found.++ report start+ the first day of the report period specified with -b or -p or+ date:, otherwise today.++ report or journal start+ the first day of the report period specified with -b or -p or+ date:, otherwise the earliest transaction date in the journal,+ otherwise today.++ report end+ the last day of the report period specified with -e or -p or+ date:, otherwise today.++ report or journal end+ the last day of the report period specified with -e or -p or+ date:, otherwise the latest transaction date in the journal,+ otherwise today.++ report interval+ a flag (-D/-W/-M/-Q/-Y) or period expression that activates the+ report's multi-period mode (whether showing one or many subperi-+ ods).++COMMANDS+ hledger provides a number of subcommands; hledger with no arguments+ shows a list.++ If you install additional hledger-* packages, or if you put programs or+ scripts named hledger-NAME in your PATH, these will also be listed as+ subcommands.++ Run a subcommand by writing its name as first argument (eg hledger in-+ comestatement). You can also write one of the standard short aliases+ displayed in parentheses in the command list (hledger b), or any any+ unambiguous prefix of a command name (hledger inc).++ Here are all the builtin commands in alphabetical order. See also+ hledger for a more organised command list, and hledger CMD -h for de-+ tailed command help.++ accounts+ accounts, a+ Show account names.++ This command lists account names, either declared with account direc-+ tives (--declared), posted to (--used), or both (the default). With+ query arguments, only matched account names and account names refer-+ enced by matched postings are shown. It shows a flat list by default.+ With --tree, it uses indentation to show the account hierarchy. In+ flat mode you can add --drop N to omit the first few account name com-+ ponents. Account names can be depth-clipped with depth:N or --depth N+ or -N.++ Examples:++ $ hledger accounts+ assets:bank:checking+ assets:bank:saving+ assets:cash+ expenses:food+ expenses:supplies+ income:gifts+ income:salary+ liabilities:debts++ activity+ activity+ Show an ascii barchart of posting counts per interval.++ The activity command displays an ascii histogram showing transaction+ counts by day, week, month or other reporting interval (by day is the+ default). With query arguments, it counts only matched transactions.++ Examples:++ $ hledger activity --quarterly+ 2008-01-01 **+ 2008-04-01 *******+ 2008-07-01+ 2008-10-01 **++ add+ add+ Prompt for transactions and add them to the journal. Any arguments+ will be used as default inputs for the first N prompts.++ Many hledger users edit their journals directly with a text editor, or+ generate them from CSV. For more interactive data entry, there is the+ add command, which prompts interactively on the console for new trans-+ actions, and appends them to the journal file (if there are multiple -f+ FILE options, the first file is used.) Existing transactions are not+ changed. This is the only hledger command that writes to the journal+ file.++ To use it, just run hledger add and follow the prompts. You can add as+ many transactions as you like; when you are finished, enter . or press+ control-d or control-c to exit.++ Features:++ o add tries to provide useful defaults, using the most similar (by de-+ scription) recent transaction (filtered by the query, if any) as a+ template.++ o You can also set the initial defaults with command line arguments.++ o Readline-style edit keys can be used during data entry.++ o The tab key will auto-complete whenever possible - accounts, descrip-+ tions, dates (yesterday, today, tomorrow). If the input area is+ empty, it will insert the default value.++ o If the journal defines a default commodity, it will be added to any+ bare numbers entered.++ o A parenthesised transaction code may be entered following a date.++ o Comments and tags may be entered following a description or amount.++ o If you make a mistake, enter < at any prompt to go one step backward.++ o Input prompts are displayed in a different colour when the terminal+ supports it.++ Example (see the tutorial for a detailed explanation):++ $ hledger add+ Adding transactions to journal file /src/hledger/examples/sample.journal+ Any command line arguments will be used as defaults.+ Use tab key to complete, readline keys to edit, enter to accept defaults.+ An optional (CODE) may follow transaction dates.+ An optional ; COMMENT may follow descriptions or amounts.+ If you make a mistake, enter < at any prompt to go one step backward.+ To end a transaction, enter . when prompted.+ To quit, enter . at a date prompt or press control-d or control-c.+ Date [2015/05/22]:+ Description: supermarket+ Account 1: expenses:food+ Amount 1: $10+ Account 2: assets:checking+ Amount 2 [$-10.0]:+ Account 3 (or . or enter to finish this transaction): .+ 2015/05/22 supermarket+ expenses:food $10+ assets:checking $-10.0++ Save this transaction to the journal ? [y]:+ Saved.+ Starting the next transaction (. or ctrl-D/ctrl-C to quit)+ Date [2015/05/22]: <CTRL-D> $++ On Microsoft Windows, the add command makes sure that no part of the+ file path ends with a period, as that would cause problems (#1056).++ aregister+ aregister, areg+ Show transactions affecting a particular account, and the account's+ running balance.++ aregister shows the transactions affecting a particular account (and+ its subaccounts), from the point of view of that account. Each line+ shows:++ o the transaction's (or posting's, see below) date++ o the names of the other account(s) involved++ o the net change to this account's balance++ o the account's historical running balance (including balance from+ transactions before the report start date).++ With aregister, each line represents a whole transaction - as in+ hledger-ui, hledger-web, and your bank statement. By contrast, the+ register command shows individual postings, across all accounts. You+ might prefer aregister for reconciling with real-world asset/liability+ accounts, and register for reviewing detailed revenues/expenses.++ An account must be specified as the first argument, which should be the+ full account name or an account pattern (regular expression). aregis-+ ter will show transactions in this account (the first one matched) and+ any of its subaccounts.++ Any additional arguments form a query which will filter the transac-+ tions shown.++ Transactions making a net change of zero are not shown by default; add+ the -E/--empty flag to show them.++ aregister and custom posting dates+ Transactions whose date is outside the report period can still be+ shown, if they have a posting to this account dated inside the report+ period. (And in this case it's the posting date that is shown.) This+ ensures that aregister can show an accurate historical running balance,+ matching the one shown by register -H with the same arguments.++ To filter strictly by transaction date instead, add the --txn-dates+ flag. If you use this flag and some of your postings have custom+ dates, it's probably best to assume the running balance is wrong.++ Output format+ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, and json.++ Examples:++ Show all transactions and historical running balance in the first ac-+ count whose name contains "checking":++ $ hledger areg checking++ Show transactions and historical running balance in all asset accounts+ during july:++ $ hledger areg assets date:jul++ balance+ balance, bal, b+ Show accounts and their balances.++ The balance command is hledger's most versatile command. Note, despite+ the name, it is not always used for showing real-world account bal-+ ances; the more accounting-aware balancesheet and incomestatement may+ be more convenient for that.++ By default, it displays all accounts, and each account's change in bal-+ ance during the entire period of the journal. Balance changes are cal-+ culated by adding up the postings in each account. You can limit the+ postings matched, by a query, to see fewer accounts, changes over a+ different time period, changes from only cleared transactions, etc.++ If you include an account's complete history of postings in the report,+ the balance change is equivalent to the account's current ending bal-+ ance. For a real-world account, typically you won't have all transac-+ tions in the journal; instead you'll have all transactions after a cer-+ tain date, and an "opening balances" transaction setting the correct+ starting balance on that date. Then the balance command will show+ real-world account balances. In some cases the -H/--historical flag is+ used to ensure this (more below).++ The balance command can produce several styles of report:++ Classic balance report+ This is the original balance report, as found in Ledger. It usually+ looks like this:++ $ hledger balance+ $-1 assets+ $1 bank:saving+ $-2 cash+ $2 expenses+ $1 food+ $1 supplies+ $-2 income+ $-1 gifts+ $-1 salary+ $1 liabilities:debts+ --------------------+ 0++ By default, accounts are displayed hierarchically, with subaccounts in-+ dented below their parent, with accounts at each level of the tree+ sorted by declaration order if declared, then by account name.++ "Boring" accounts, which contain a single interesting subaccount and no+ balance of their own, are elided into the following line for more com-+ pact output. (Eg above, the "liabilities" account.) Use --no-elide to+ prevent this.++ Account balances are "inclusive" - they include the balances of any+ subaccounts.++ Accounts which have zero balance (and no non-zero subaccounts) are+ omitted. Use -E/--empty to show them.++ A final total is displayed by default; use -N/--no-total to suppress+ it, eg:++ $ hledger balance -p 2008/6 expenses --no-total+ $2 expenses+ $1 food+ $1 supplies++ Customising the classic balance report+ You can customise the layout of classic balance reports with --format+ FMT:++ $ hledger balance --format "%20(account) %12(total)"+ assets $-1+ bank:saving $1+ cash $-2+ expenses $2+ food $1+ supplies $1+ income $-2+ gifts $-1+ salary $-1+ liabilities:debts $1+ ---------------------------------+ 0++ The FMT format string (plus a newline) specifies the formatting applied+ to each account/balance pair. It may contain any suitable text, with+ data fields interpolated like so:++ %[MIN][.MAX](FIELDNAME)++ o MIN pads with spaces to at least this width (optional)++ o MAX truncates at this width (optional)++ o FIELDNAME must be enclosed in parentheses, and can be one of:++ o depth_spacer - a number of spaces equal to the account's depth, or+ if MIN is specified, MIN * depth spaces.++ o account - the account's name++ o total - the account's balance/posted total, right justified++ Also, FMT can begin with an optional prefix to control how multi-com-+ modity amounts are rendered:++ o %_ - render on multiple lines, bottom-aligned (the default)++ o %^ - render on multiple lines, top-aligned++ o %, - render on one line, comma-separated++ There are some quirks. Eg in one-line mode, %(depth_spacer) has no ef-+ fect, instead %(account) has indentation built in. Experimentation may+ be needed to get pleasing results.++ Some example formats:++ o %(total) - the account's total++ o %-20.20(account) - the account's name, left justified, padded to 20+ characters and clipped at 20 characters++ o %,%-50(account) %25(total) - account name padded to 50 characters,+ total padded to 20 characters, with multiple commodities rendered on+ one line++ o %20(total) %2(depth_spacer)%-(account) - the default format for the+ single-column balance report++ Colour support+ In terminal output, when colour is enabled, the balance command shows+ negative amounts in red.++ Flat mode+ To see a flat list instead of the default hierarchical display, use+ --flat. In this mode, accounts (unless depth-clipped) show their full+ names and "exclusive" balance, excluding any subaccount balances. In+ this mode, you can also use --drop N to omit the first few account name+ components.++ $ hledger balance -p 2008/6 expenses -N --flat --drop 1+ $1 food+ $1 supplies++ Depth limited balance reports+ With --depth N or depth:N or just -N, balance reports show accounts+ only to the specified numeric depth. This is very useful to summarise+ a complex set of accounts and get an overview.++ $ hledger balance -N -1+ $-1 assets+ $2 expenses+ $-2 income+ $1 liabilities++ Flat-mode balance reports, which normally show exclusive balances, show+ inclusive balances at the depth limit.++ Percentages+ With -% or --percent, balance reports show each account's value ex-+ pressed as a percentage of the column's total. This is useful to get+ an overview of the relative sizes of account balances. For example to+ obtain an overview of expenses:++ $ hledger balance expenses -%+ 100.0 % expenses+ 50.0 % food+ 50.0 % supplies+ --------------------+ 100.0 %++ Note that --tree does not have an effect on -%. The percentages are+ always relative to the total sum of each column, they are never rela-+ tive to the parent account.++ Since the percentages are relative to the columns sum, it is usually+ not useful to calculate percentages if the signs of the amounts are+ mixed. Although the results are technically correct, they are most+ likely useless. Especially in a balance report that sums up to zero+ (eg hledger balance -B) all percentage values will be zero.++ This flag does not work if the report contains any mixed commodity ac-+ counts. If there are mixed commodity accounts in the report be sure to+ use -V or -B to coerce the report into using a single commodity.++ Sorting by amount+ With -S/--sort-amount, accounts with the largest (most positive) bal-+ ances are shown first. For example, hledger bal expenses -MAS shows+ your biggest averaged monthly expenses first.++ Revenues and liability balances are typically negative, however, so -S+ shows these in reverse order. To work around this, you can add --in-+ vert to flip the signs. Or, use one of the sign-flipping reports like+ balancesheet or incomestatement, which also support -S. Eg: hledger is+ -MAS.++ Multicolumn balance report+ Multicolumn or tabular balance reports are a very useful hledger fea-+ ture, and usually the preferred style. They share many of the above+ features, but they show the report as a table, with columns represent-+ ing time periods. This mode is activated by providing a reporting in-+ terval.++ There are three types of multicolumn balance report, showing different+ information:++ 1. By default: each column shows the sum of postings in that period, ie+ the account's change of balance in that period. This is useful eg+ for a monthly income statement:++ $ hledger balance --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++ 2. With --cumulative: each column shows the ending balance for that pe-+ riod, accumulating the changes across periods, starting from 0 at+ the report start date:++ $ hledger balance --quarterly income expenses -E --cumulative+ Ending balances (cumulative) in 2008:++ || 2008/03/31 2008/06/30 2008/09/30 2008/12/31+ ===================++=================================================+ expenses:food || 0 $1 $1 $1+ expenses:supplies || 0 $1 $1 $1+ income:gifts || 0 $-1 $-1 $-1+ income:salary || $-1 $-1 $-1 $-1+ -------------------++-------------------------------------------------+ || $-1 0 0 0++ 3. With --historical/-H: each column shows the actual historical ending+ balance for that period, accumulating the changes across periods,+ starting from the actual balance at the report start date. This is+ useful eg for a multi-period balance sheet, and when you are showing+ only the data after a certain start date:++ $ hledger balance ^assets ^liabilities --quarterly --historical --begin 2008/4/1+ Ending balances (historical) in 2008/04/01-2008/12/31:++ || 2008/06/30 2008/09/30 2008/12/31+ ======================++=====================================+ assets:bank:checking || $1 $1 0+ assets:bank:saving || $1 $1 $1+ assets:cash || $-2 $-2 $-2+ liabilities:debts || 0 0 $1+ ----------------------++-------------------------------------+ || 0 0 0++ Note that --cumulative or --historical/-H disable --row-total/-T, since+ summing end balances generally does not make sense.++ Multicolumn balance reports display accounts in flat mode by default;+ to see the hierarchy, use --tree.++ With a reporting interval (like --quarterly above), the report+ start/end dates will be adjusted if necessary so that they encompass+ the displayed report periods. This is so that the first and last peri-+ ods will be "full" and comparable to the others.++ The -E/--empty flag does two things in multicolumn balance reports:+ first, the report will show all columns within the specified report pe-+ riod (without -E, leading and trailing columns with all zeroes are not+ shown). Second, all accounts which existed at the report start date+ will be considered, not just the ones with activity during the report+ period (use -E to include low-activity accounts which would otherwise+ would be omitted).++ The -T/--row-total flag adds an additional column showing the total for+ each row.++ The -A/--average flag adds a column showing the average value in each+ row.++ Here's an example of all three:++ $ hledger balance -Q income expenses --tree -ETA+ Balance changes in 2008:++ || 2008q1 2008q2 2008q3 2008q4 Total Average+ ============++===================================================+ expenses || 0 $2 0 0 $2 $1+ food || 0 $1 0 0 $1 0+ supplies || 0 $1 0 0 $1 0+ income || $-1 $-1 0 0 $-2 $-1+ gifts || 0 $-1 0 0 $-1 0+ salary || $-1 0 0 0 $-1 0+ ------------++---------------------------------------------------+ || $-1 $1 0 0 0 0++ (Average is rounded to the dollar here since all journal amounts are)++ The --transpose flag can be used to exchange the rows and columns of a+ multicolumn report.++ When showing multicommodity amounts, multicolumn balance reports will+ elide any amounts which have more than two commodities, since otherwise+ columns could get very wide. The --no-elide flag disables this. Hid-+ ing totals with the -N/--no-total flag can also help reduce the width+ of multicommodity reports.++ When the report is still too wide, a good workaround is to pipe it into+ less -RS (-R for colour, -S to chop long lines). Eg: hledger bal -D+ --color=yes | less -RS.++ Budget report+ With --budget, extra columns are displayed showing budget goals for+ each account and period, if any. Budget goals are defined by periodic+ transactions. This is very useful for comparing planned and actual in-+ come, expenses, time usage, etc. --budget is most often combined with+ a report interval.++ For example, you can take average monthly expenses in the common ex-+ pense categories to construct a minimal monthly budget:++ ;; Budget+ ~ monthly+ income $2000+ expenses:food $400+ expenses:bus $50+ expenses:movies $30+ assets:bank:checking++ ;; Two months worth of expenses+ 2017-11-01+ income $1950+ expenses:food $396+ expenses:bus $49+ expenses:movies $30+ expenses:supplies $20+ assets:bank:checking++ 2017-12-01+ income $2100+ expenses:food $412+ expenses:bus $53+ expenses:gifts $100+ assets:bank:checking++ You can now see a monthly budget report:++ $ hledger balance -M --budget+ Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec+ ======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ expenses || $495 [ 103% of $480] $565 [ 118% of $480]+ expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50]+ expenses:food || $396 [ 99% of $400] $412 [ 103% of $400]+ expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30]+ income || $1950 [ 98% of $2000] $2100 [ 105% of $2000]+ ----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0]++ This is different from a normal balance report in several ways:++ o Only accounts with budget goals during the report period are shown,+ by default.++ o In each column, in square brackets after the actual amount, budget+ goal amounts are shown, and the actual/goal percentage. (Note: bud-+ get goals should be in the same commodity as the actual amount.)++ o All parent accounts are always shown, even in flat mode. Eg assets,+ assets:bank, and expenses above.++ o Amounts always include all subaccounts, budgeted or unbudgeted, even+ in flat mode.++ This means that the numbers displayed will not always add up! Eg above,+ the expenses actual amount includes the gifts and supplies transac-+ tions, but the expenses:gifts and expenses:supplies accounts are not+ shown, as they have no budget amounts declared.++ This can be confusing. When you need to make things clearer, use the+ -E/--empty flag, which will reveal all accounts including unbudgeted+ ones, giving the full picture. Eg:++ $ hledger balance -M --budget --empty+ Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec+ ======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ expenses || $495 [ 103% of $480] $565 [ 118% of $480]+ expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50]+ expenses:food || $396 [ 99% of $400] $412 [ 103% of $400]+ expenses:gifts || 0 $100+ expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30]+ expenses:supplies || $20 0+ income || $1950 [ 98% of $2000] $2100 [ 105% of $2000]+ ----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0]++ You can roll over unspent budgets to next period with --cumulative:++ $ hledger balance -M --budget --cumulative+ Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec+ ======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]+ assets:bank || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]+ assets:bank:checking || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]+ expenses || $495 [ 103% of $480] $1060 [ 110% of $960]+ expenses:bus || $49 [ 98% of $50] $102 [ 102% of $100]+ expenses:food || $396 [ 99% of $400] $808 [ 101% of $800]+ expenses:movies || $30 [ 100% of $30] $30 [ 50% of $60]+ income || $1950 [ 98% of $2000] $4050 [ 101% of $4000]+ ----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0]++ For more examples and notes, see Budgeting.++ Budget report start date+ This might be a bug, but for now: when making budget reports, it's a+ good idea to explicitly set the report's start date to the first day of+ a reporting period, because a periodic rule like ~ monthly generates+ its transactions on the 1st of each month, and if your journal has no+ regular transactions on the 1st, the default report start date could+ exclude that budget goal, which can be a little surprising. Eg here+ the default report period is just the day of 2020-01-15:++ ~ monthly in 2020+ (expenses:food) $500++ 2020-01-15+ expenses:food $400+ assets:checking++ $ hledger bal expenses --budget+ Budget performance in 2020-01-15:++ || 2020-01-15+ ==============++============+ <unbudgeted> || $400+ --------------++------------+ || $400++ To avoid this, specify the budget report's period, or at least the+ start date, with -b/-e/-p/date:, to ensure it includes the budget goal+ transactions (periodic transactions) that you want. Eg, adding -b+ 2020/1/1 to the above:++ $ hledger bal expenses --budget -b 2020/1/1+ Budget performance in 2020-01-01..2020-01-15:++ || 2020-01-01..2020-01-15+ ===============++========================+ expenses:food || $400 [80% of $500]+ ---------------++------------------------+ || $400 [80% of $500]++ Nested budgets+ You can add budgets to any account in your account hierarchy. If you+ have budgets on both parent account and some of its children, then bud-+ get(s) of the child account(s) would be added to the budget of their+ parent, much like account balances behave.++ In the most simple case this means that once you add a budget to any+ account, all its parents would have budget as well.++ To illustrate this, consider the following budget:++ ~ monthly from 2019/01+ expenses:personal $1,000.00+ expenses:personal:electronics $100.00+ liabilities++ With this, monthly budget for electronics is defined to be $100 and+ budget for personal expenses is an additional $1000, which implicitly+ means that budget for both expenses:personal and expenses is $1100.++ Transactions in expenses:personal:electronics will be counted both to-+ wards its $100 budget and $1100 of expenses:personal , and transactions+ in any other subaccount of expenses:personal would be counted towards+ only towards the budget of expenses:personal.++ For example, let's consider these transactions:++ ~ monthly from 2019/01+ expenses:personal $1,000.00+ expenses:personal:electronics $100.00+ liabilities++ 2019/01/01 Google home hub+ expenses:personal:electronics $90.00+ liabilities $-90.00++ 2019/01/02 Phone screen protector+ expenses:personal:electronics:upgrades $10.00+ liabilities++ 2019/01/02 Weekly train ticket+ expenses:personal:train tickets $153.00+ liabilities++ 2019/01/03 Flowers+ expenses:personal $30.00+ liabilities++ As you can see, we have transactions in expenses:personal:electron-+ ics:upgrades and expenses:personal:train tickets, and since both of+ these accounts are without explicitly defined budget, these transac-+ tions would be counted towards budgets of expenses:personal:electronics+ and expenses:personal accordingly:++ $ hledger balance --budget -M+ Budget performance in 2019/01:++ || Jan+ ===============================++===============================+ expenses || $283.00 [ 26% of $1100.00]+ expenses:personal || $283.00 [ 26% of $1100.00]+ expenses:personal:electronics || $100.00 [ 100% of $100.00]+ liabilities || $-283.00 [ 26% of $-1100.00]+ -------------------------------++-------------------------------+ || 0 [ 0]++ And with --empty, we can get a better picture of budget allocation and+ consumption:++ $ hledger balance --budget -M --empty+ Budget performance in 2019/01:++ || Jan+ ========================================++===============================+ expenses || $283.00 [ 26% of $1100.00]+ expenses:personal || $283.00 [ 26% of $1100.00]+ expenses:personal:electronics || $100.00 [ 100% of $100.00]+ expenses:personal:electronics:upgrades || $10.00+ expenses:personal:train tickets || $153.00+ liabilities || $-283.00 [ 26% of $-1100.00]+ ----------------------------------------++-------------------------------+ || 0 [ 0]++ Output format+ This command also supports the output destination and output format op-+ tions The output formats supported are (in most modes): txt, csv, html,+ and json.++ balancesheet+ balancesheet, bs+ This command displays a balance sheet, showing historical ending bal-+ ances of asset and liability accounts. (To see equity as well, use the+ balancesheetequity command.) Amounts are shown with normal positive+ sign, as in conventional financial statements.++ The asset and liability accounts shown are those accounts declared with+ the Asset or Cash or Liability type, or otherwise all accounts under a+ top-level asset or liability account (case insensitive, plurals al-+ lowed).++ Example:++ $ hledger balancesheet+ Balance Sheet++ Assets:+ $-1 assets+ $1 bank:saving+ $-2 cash+ --------------------+ $-1++ Liabilities:+ $1 liabilities:debts+ --------------------+ $1++ Total:+ --------------------+ 0++ With a reporting interval, multiple columns will be shown, one for each+ report period. As with multicolumn balance reports, you can alter the+ report mode with --change/--cumulative/--historical. Normally bal-+ ancesheet shows historical ending balances, which is what you need for+ a balance sheet; note this means it ignores report begin dates (and+ -T/--row-total, since summing end balances generally does not make+ sense). Instead of absolute values percentages can be displayed with+ -%.++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, html, and (experimen-+ tal) json.++ balancesheetequity+ balancesheetequity, bse+ This command displays a balance sheet, showing historical ending bal-+ ances of asset, liability and equity accounts. Amounts are shown with+ normal positive sign, as in conventional financial statements.++ The asset, liability and equity accounts shown are those accounts de-+ clared with the Asset, Cash, Liability or Equity type, or otherwise all+ accounts under a top-level asset, liability or equity account (case in-+ sensitive, plurals allowed).++ Example:++ $ hledger balancesheetequity+ Balance Sheet With Equity++ Assets:+ $-2 assets+ $1 bank:saving+ $-3 cash+ --------------------+ $-2++ Liabilities:+ $1 liabilities:debts+ --------------------+ $1++ Equity:+ $1 equity:owner+ --------------------+ $1++ Total:+ --------------------+ 0++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, html, and (experimen-+ tal) json.++ cashflow+ cashflow, cf+ This command displays a cashflow statement, showing the inflows and+ outflows affecting "cash" (ie, liquid) assets. Amounts are shown with+ normal positive sign, as in conventional financial statements.++ The "cash" accounts shown are those accounts declared with the Cash+ type, or otherwise all accounts under a top-level asset account (case+ insensitive, plural allowed) which do not have fixed, investment, re-+ ceivable or A/R in their name.++ Example:++ $ hledger cashflow+ Cashflow Statement++ Cash flows:+ $-1 assets+ $1 bank:saving+ $-2 cash+ --------------------+ $-1++ Total:+ --------------------+ $-1++ With a reporting interval, multiple columns will be shown, one for each+ report period. Normally cashflow shows changes in assets per period,+ though as with multicolumn balance reports you can alter the report+ mode with --change/--cumulative/--historical. Instead of absolute val-+ ues percentages can be displayed with -%.++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, html, and (experimen-+ tal) json.++ check+ check+ Check for various kinds of errors in your data. experimental++ hledger provides a number of built-in error checks to help prevent+ problems in your data. Some of these are run automatically; or, you+ can use this check command to run them on demand, with no output and a+ zero exit code if all is well. Some examples:++ hledger check # basic checks+ hledger check -s # basic + strict checks+ hledger check ordereddates uniqueleafnames # basic + specified checks++ Here are the checks currently available:++ Basic checks+ These are always run by this command and other commands:++ o parseable - data files are well-formed and can be successfully parsed++ o autobalanced - all transactions are balanced, inferring missing+ amounts where necessary, and possibly converting commodities using+ transaction prices or automatically-inferred transaction prices++ o assertions - all balance assertions in the journal are passing.+ (This check can be disabled with -I/--ignore-assertions.)++ Strict checks+ These are always run by this and other commands when -s/--strict is+ used (strict mode):++ o accounts - all account names used by transactions have been declared++ o commodities - all commodity symbols used have been declared++ Other checks+ These checks can be run by specifying their names as arguments to the+ check command:++ o ordereddates - transactions are ordered by date (similar to the old+ check-dates command)++ o uniqueleafnames - all account leaf names are unique (similar to the+ old check-dupes command)++ Addon checks+ Some checks are not yet integrated with this command, but are available+ as add-on commands in https://github.com/simonmichael/hledger/tree/mas-+ ter/bin:++ o hledger-check-tagfiles - all tag values containing / (a forward+ slash) exist as file paths++ o hledger-check-fancyassertions - more complex balance assertions are+ passing++ You could make your own similar scripts to perform custom checks; Cook-+ book -> Scripting may be helpful.++ close+ close, equity+ Prints a "closing balances" transaction and an "opening balances"+ transaction that bring account balances to and from zero, respectively.+ These can be added to your journal file(s), eg to bring asset/liability+ balances forward into a new journal file, or to close out revenues/ex-+ penses to retained earnings at the end of a period.++ You can print just one of these transactions by using the --close or+ --open flag. You can customise their descriptions with the --close-+ desc and --open-desc options.++ One amountless posting to "equity:opening/closing balances" is added to+ balance the transactions, by default. You can customise this account+ name with --close-acct and --open-acct; if you specify only one of+ these, it will be used for both.++ With --x/--explicit, the equity posting's amount will be shown. And if+ it involves multiple commodities, a posting for each commodity will be+ shown, as with the print command.++ With --interleaved, the equity postings are shown next to the postings+ they balance, which makes troubleshooting easier.++ By default, transaction prices in the journal are ignored when generat-+ ing the closing/opening transactions. With --show-costs, this cost in-+ formation is preserved (balance -B reports will be unchanged after the+ transition). Separate postings are generated for each cost in each+ commodity. Note this can generate very large journal entries, if you+ have many foreign currency or investment transactions.++ close usage+ If you split your journal files by time (eg yearly), you will typically+ run this command at the end of the year, and save the closing transac-+ tion as last entry of the old file, and the opening transaction as the+ first entry of the new file. This makes the files self contained, so+ that correct balances are reported no matter which of them are loaded.+ Ie, if you load just one file, the balances are initialised correctly;+ or if you load several files, the redundant closing/opening transac-+ tions cancel each other out. (They will show up in print or register+ reports; you can exclude them with a query like not:desc:'(open-+ ing|closing) balances'.)++ If you're running a business, you might also use this command to "close+ the books" at the end of an accounting period, transferring income+ statement account balances to retained earnings. (You may want to+ change the equity account name to something like "equity:retained earn-+ ings".)++ By default, the closing transaction is dated yesterday, the balances+ are calculated as of end of yesterday, and the opening transaction is+ dated today. To close on some other date, use: hledger close -e OPEN-+ INGDATE. Eg, to close/open on the 2018/2019 boundary, use -e 2019.+ You can also use -p or date:PERIOD (any starting date is ignored).++ Both transactions will include balance assertions for the closed/re-+ opened accounts. You probably shouldn't use status or realness filters+ (like -C or -R or status:) with this command, or the generated balance+ assertions will depend on these flags. Likewise, if you run this com-+ mand with --auto, the balance assertions will probably always require+ --auto.++ Examples:++ Carrying asset/liability balances into a new file for 2019:++ $ hledger close -f 2018.journal -e 2019 assets liabilities --open+ # (copy/paste the output to the start of your 2019 journal file)+ $ hledger close -f 2018.journal -e 2019 assets liabilities --close+ # (copy/paste the output to the end of your 2018 journal file)++ Now:++ $ hledger bs -f 2019.journal # one file - balances are correct+ $ hledger bs -f 2018.journal -f 2019.journal # two files - balances still correct+ $ hledger bs -f 2018.journal not:desc:closing # to see year-end balances, must exclude closing txn++ Transactions spanning the closing date can complicate matters, breaking+ balance assertions:++ 2018/12/30 a purchase made in 2018, clearing the following year+ expenses:food 5+ assets:bank:checking -5 ; [2019/1/2]++ Here's one way to resolve that:++ ; in 2018.journal:+ 2018/12/30 a purchase made in 2018, clearing the following year+ expenses:food 5+ liabilities:pending++ ; in 2019.journal:+ 2019/1/2 clearance of last year's pending transactions+ liabilities:pending 5 = 0+ assets:checking++ codes+ codes+ List the codes seen in transactions, in the order parsed.++ This command prints the value of each transaction's 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.++ Transactions aren't required to have a code, and missing or empty codes+ will not be shown by default. With the -E/--empty flag, they will be+ printed as blank lines.++ You can add a query to select a subset of transactions.++ Examples:++ 1/1 (123)+ (a) 1++ 1/1 ()+ (a) 1++ 1/1+ (a) 1++ 1/1 (126)+ (a) 1++ $ hledger codes+ 123+ 124+ 126++ $ hledger codes -E+ 123+ 124+++ 126++ commodities+ commodities+ List all commodity/currency symbols used or declared in the journal.++ descriptions+ descriptions+ List the unique descriptions that appear in transactions.++ This command lists the unique descriptions that appear in transactions,+ in alphabetic order. You can add a query to select a subset of trans-+ actions.++ Example:++ $ hledger descriptions+ Store Name+ Gas Station | Petrol+ Person A++ diff+ diff+ Compares a particular account's transactions in two input files. It+ shows any transactions to this account which are in one file but not in+ the other.++ More precisely, for each posting affecting this account in either file,+ it looks for a corresponding posting in the other file which posts the+ same amount to the same account (ignoring date, description, etc.)+ Since postings not transactions are compared, this also works when mul-+ tiple bank transactions have been combined into a single journal entry.++ This is useful eg if you have downloaded an account's 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.++ Examples:++ $ 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:++ files+ files+ List all files included in the journal. With a REGEX argument, only+ file names matching the regular expression (case sensitive) are shown.++ help+ help+ Show any of the hledger manuals.++ The help command displays any of the main hledger manuals, in one of+ several ways. Run it with no argument to list the manuals, or provide+ a full or partial manual name to select one.++ hledger manuals are available in several formats. hledger help will+ use the first of these display methods that it finds: info, man,+ $PAGER, less, stdout (or when non-interactive, just stdout). You can+ force a particular viewer with the --info, --man, --pager, --cat flags.++ Examples:++ $ hledger help+ Please choose a manual by typing "hledger help MANUAL" (a substring is ok).+ Manuals: hledger hledger-ui hledger-web journal csv timeclock timedot++ $ hledger help h --man++ hledger(1) hledger User Manuals hledger(1)++ NAME+ hledger - a command-line accounting tool++ SYNOPSIS+ hledger [-f FILE] COMMAND [OPTIONS] [ARGS]+ hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]+ hledger++ DESCRIPTION+ hledger is a cross-platform program for tracking money, time, or any+ ...++ import+ import+ Read new transactions added to each FILE since last run, and add them+ to the main journal file. Or with --dry-run, just print the transac-+ tions that would be added. Or with --catchup, just mark all of the+ FILEs' transactions as imported, without actually importing any.++ The input files are specified as arguments - no need to write -f before+ each one. So eg to add new transactions from all CSV files to the main+ journal, it's just: hledger import *.csv++ New transactions are detected in the same way as print --new: by assum-+ ing transactions are always added to the input files in increasing date+ order, and by saving .latest.FILE state files.++ The --dry-run output is in journal format, so you can filter it, eg to+ see only uncategorised transactions:++ $ hledger import --dry ... | hledger -f- print unknown --ignore-assertions++ Importing balance assignments+ Entries added by import will have their posting amounts made explicit+ (like hledger print -x). This means that any balance assignments in+ imported files must be evaluated; but, imported files don't get to see+ the main file's account balances. As a result, importing entries with+ balance assignments (eg from an institution that provides only balances+ and not posting amounts) will probably generate incorrect posting+ amounts. To avoid this problem, use print instead of import:++ $ hledger print IMPORTFILE [--new] >> $LEDGER_FILE++ (If you think import should leave amounts implicit like print does,+ please test it and send a pull request.)++ Commodity display styles+ Imported amounts will be formatted according to the canonical commodity+ styles (declared or inferred) in the main journal file.++ incomestatement+ incomestatement, is+ This command displays an income statement, showing revenues and ex-+ penses during one or more periods. Amounts are shown with normal posi-+ tive sign, as in conventional financial statements.++ The revenue and expense accounts shown are those accounts declared with+ the Revenue or Expense type, or otherwise all accounts under a top-+ level revenue or income or expense account (case insensitive, plurals+ allowed).++ Example:++ $ hledger incomestatement+ Income Statement++ Revenues:+ $-2 income+ $-1 gifts+ $-1 salary+ --------------------+ $-2++ Expenses:+ $2 expenses+ $1 food+ $1 supplies+ --------------------+ $2++ Total:+ --------------------+ 0++ With a reporting interval, multiple columns will be shown, one for each+ report period. Normally incomestatement shows revenues/expenses per+ period, though as with multicolumn balance reports you can alter the+ report mode with --change/--cumulative/--historical. Instead of abso-+ lute values percentages can be displayed with -%.++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, html, and (experimen-+ tal) json.++ notes+ notes+ List the unique notes that appear in transactions.++ This command lists the unique notes that appear in transactions, in al-+ phabetic order. You can add a query to select a subset of transac-+ tions. The note is the part of the transaction description after a |+ character (or if there is no |, the whole description).++ Example:++ $ hledger notes+ Petrol+ Snacks++ payees+ payees+ List the unique payee/payer names that appear in transactions.++ This command lists the unique payee/payer names that appear in transac-+ tions, in alphabetic order. You can add a query to select a subset of+ transactions. The payee/payer is the part of the transaction descrip-+ tion before a | character (or if there is no |, the whole description).++ Example:++ $ hledger payees+ Store Name+ Gas Station+ Person A++ prices+ prices+ Print market price directives from the journal. With --costs, also+ print synthetic market prices based on transaction prices. With --in-+ verted-costs, also print inverse prices based on transaction prices.+ Prices (and postings providing prices) can be filtered by a query.+ Price amounts are always displayed with their full precision.++ print+ print, txns, p+ Show transaction journal entries, sorted by date.++ The print command displays full journal entries (transactions) from the+ journal file in date order, tidily formatted. With --date2, transac-+ tions are sorted by secondary date instead.++ print's output is always a valid hledger journal.+ It preserves all transaction information, but it does not preserve di-+ rectives or inter-transaction comments++ $ hledger print+ 2008/01/01 income+ assets:bank:checking $1+ income:salary $-1++ 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++ 2008/12/31 * pay off+ liabilities:debts $1+ assets:bank:checking $-1++ Normally, the journal entry's explicit or implicit amount style is pre-+ served. For example, when an amount is omitted in the journal, it will+ not appear in the output. Similarly, when a transaction price is im-+ plied but not written, it will not appear in the output. You can use+ the -x/--explicit flag to make all amounts and transaction prices ex-+ plicit, which can be useful for troubleshooting or for making your+ journal more readable and robust against data entry errors. -x is also+ implied by using any of -B,-V,-X,--value.++ Note, -x/--explicit will cause postings with a multi-commodity amount+ (these can arise when a multi-commodity transaction has an implicit+ amount) to be split into multiple single-commodity postings, keeping+ the output parseable.++ With -B/--cost, amounts with transaction prices are converted to cost+ using that price. This can be used for troubleshooting.++ With -m/--match and a STR argument, print will show at most one trans-+ action: the one one whose description is most similar to STR, and is+ most recent. STR should contain at least two characters. If there is+ no similar-enough match, no transaction will be shown.++ With --new, for each FILE being read, hledger reads (and writes) a spe-+ cial state file (.latest.FILE in the same directory), containing the+ latest transaction date(s) that were seen last time FILE was read.+ When this file is found, only transactions with newer dates (and new+ transactions on the latest date) are printed. This is useful for ig-+ noring already-seen entries in import data, such as downloaded CSV+ files. Eg:++ $ hledger -f bank1.csv print --new+ (shows transactions added since last print --new on this file)++ This assumes that transactions added to FILE always have same or in-+ creasing dates, and that transactions on the same day do not get re-+ ordered. See also the import command.++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, and (experimental)+ json and sql.++ Here's an example of print's CSV output:++ $ hledger print -Ocsv+ "txnidx","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","posting-status","posting-comment"+ "1","2008/01/01","","","","income","","assets:bank:checking","1","$","","1","",""+ "1","2008/01/01","","","","income","","income:salary","-1","$","1","","",""+ "2","2008/06/01","","","","gift","","assets:bank:checking","1","$","","1","",""+ "2","2008/06/01","","","","gift","","income:gifts","-1","$","1","","",""+ "3","2008/06/02","","","","save","","assets:bank:saving","1","$","","1","",""+ "3","2008/06/02","","","","save","","assets:bank:checking","-1","$","1","","",""+ "4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","","1","",""+ "4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","","1","",""+ "4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","2","","",""+ "5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","","1","",""+ "5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","1","","",""++ o There is one CSV record per posting, with the parent transaction's+ fields repeated.++ o The "txnidx" (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.)++ o The amount is separated into "commodity" (the symbol) and "amount"+ (numeric quantity) fields.++ o The numeric amount is repeated in either the "credit" or "debit" col-+ umn, for convenience. (Those names are not accurate in the account-+ ing sense; it just puts negative amounts under credit and zero or+ greater amounts under debit.)++ print-unique+ print-unique+ Print transactions which do not reuse an already-seen description.++ Example:++ $ cat unique.journal+ 1/1 test+ (acct:one) 1+ 2/2 test+ (acct:two) 2+ $ LEDGER_FILE=unique.journal hledger print-unique+ (-f option not supported)+ 2015/01/01 test+ (acct:one) 1++ register+ register, reg, r+ Show postings and their running total.++ The register command displays matched postings, across all accounts, in+ date order, with their running total or running historical balance.+ (See also the aregister command, which shows matched transactions in a+ specific account.)++ register normally shows line per posting, but note that multi-commodity+ amounts will occupy multiple lines (one line per commodity).++ It is typically used with a query selecting a particular account, to+ see that account's activity:++ $ 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++ With --date2, it shows and sorts by secondary date instead.++ The --historical/-H 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:++ $ 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++ The --depth option limits the amount of sub-account detail displayed.++ The --average/-A 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 --empty (see below). It+ is affected by --historical. It works best when showing just one ac-+ count and one commodity.++ The --related/-r flag shows the other postings in the transactions of+ the postings which would normally be shown.++ The --invert flag negates all amounts. For example, it can be used on+ an income account where amounts are normally displayed as negative num-+ bers. It's also useful to show postings on the checking account to-+ gether with the related account:++ $ hledger register --related --invert assets:checking++ With a reporting interval, register shows summary postings, one per in-+ terval, aggregating the postings to each account:++ $ hledger register --monthly income+ 2008/01 income:salary $-1 $-1+ 2008/06 income:gifts $-1 $-2++ Periods with no activity, and summary postings with a zero amount, are+ not shown by default; use the --empty/-E flag to see them:++ $ 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++ Often, you'll want to see just one line per interval. The --depth op-+ tion helps with this, causing subaccounts to be aggregated:++ $ hledger register --monthly assets --depth 1h+ 2008/01 assets $1 $1+ 2008/06 assets $-1 0+ 2008/12 assets $-1 $-1++ Note when using report intervals, if you specify start/end dates these+ will be adjusted outward if necessary to contain a whole number of in-+ tervals. This ensures that the first and last intervals are full+ length and comparable to the others in the report.++ Custom register output+ register uses the full terminal width by default, except on windows.+ You can override this by setting the COLUMNS environment variable (not+ a bash shell variable) or by using the --width/-w option.++ The description and account columns normally share the space equally+ (about half of (width - 40) each). You can adjust this by adding a de-+ scription width as part of --width's argument, comma-separated: --width+ W,D . Here's a diagram (won't display correctly in --help):++ <--------------------------------- width (W) ---------------------------------->+ date (10) description (D) account (W-41-D) amount (12) balance (12)+ DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA++ and some examples:++ $ hledger reg # use terminal width (or 80 on windows)+ $ hledger reg -w 100 # use width 100+ $ COLUMNS=100 hledger reg # set with one-time environment variable+ $ export COLUMNS=100; hledger reg # set till session end (or window resize)+ $ hledger reg -w 100,40 # set overall width 100, description width 40+ $ hledger reg -w $COLUMNS,40 # use terminal width, & description width 40++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, and (experimental)+ json.++ register-match+ register-match+ Print the one posting whose transaction description is closest to DESC,+ in the style of the register command. If there are multiple equally+ good matches, it shows the most recent. Query options (options, not+ arguments) can be used to restrict the search space. Helps ledger-au-+ tosync detect already-seen transactions when importing.++ rewrite+ rewrite+ Print all transactions, rewriting the postings of matched transactions.+ For now the only rewrite available is adding new postings, like print+ --auto.++ 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 transac-+ tion's first posting amount.++ Examples:++ $ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'+ $ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'+ $ hledger-rewrite.hs -f rewrites.hledger++ rewrites.hledger may consist of entries like:++ = ^income 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++ Note the single quotes to protect the dollar sign from bash, and the+ two spaces between account and amount.++ More:++ $ hledger rewrite -- [QUERY] --add-posting "ACCT AMTEXPR" ...+ $ hledger rewrite -- ^income --add-posting '(liabilities:tax) *.33'+ $ hledger rewrite -- expenses:gifts --add-posting '(budget:gifts) *-1"'+ $ hledger rewrite -- ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'++ Argument for --add-posting option is a usual posting of transaction+ with an exception for amount specification. More precisely, you can+ use '*' (star symbol) before the amount to indicate that that this is a+ factor for an amount of original matched posting. If the amount in-+ cludes a commodity name, the new posting amount will be in the new com-+ modity; otherwise, it will be in the matched posting amount's commod-+ ity.++ Re-write rules in a file+ During the run this tool will execute so called "Automated Transac-+ tions" found in any journal it process. I.e instead of specifying this+ operations in command line you can put them in a journal file.++ $ rewrite-rules.journal++ Make contents look like this:++ = ^income+ (liabilities:tax) *.33++ = expenses:gifts+ budget:gifts *-1+ assets:budget *1++ Note that '=' (equality symbol) that is used instead of date in trans-+ actions you usually write. It indicates the query by which you want to+ match the posting to add new ones.++ $ hledger rewrite -- -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal++ This is something similar to the commands pipeline:++ $ hledger rewrite -- -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \+ | hledger rewrite -- -f - expenses:gifts --add-posting 'budget:gifts *-1' \+ --add-posting 'assets:budget *1' \+ > rewritten-tidy-output.journal++ It is important to understand that relative order of such entries in+ journal is important. You can re-use result of previously added post-+ ings.++ Diff output format+ To use this tool for batch modification of your journal files you may+ find useful output in form of unified diff.++ $ hledger rewrite -- --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'++ Output might look like:++ --- /tmp/examples/sample.journal+ +++ /tmp/examples/sample.journal+ @@ -18,3 +18,4 @@+ 2008/01/01 income+ - assets:bank:checking $1+ + assets:bank:checking $1+ income:salary+ + (liabilities:tax) 0+ @@ -22,3 +23,4 @@+ 2008/06/01 gift+ - assets:bank:checking $1+ + assets:bank:checking $1+ income:gifts+ + (liabilities:tax) 0++ If you'll pass this through patch tool you'll get transactions contain-+ ing the posting that matches your query be updated. Note that multiple+ files might be update according to list of input files specified via+ --file options and include directives inside of these files.++ Be careful. Whole transaction being re-formatted in a style of output+ from hledger print.++ See also:++ https://github.com/simonmichael/hledger/issues/99++ rewrite vs. print --auto+ This command predates print --auto, and currently does much the same+ thing, but with these differences:++ o with multiple files, rewrite lets rules in any file affect all other+ files. print --auto uses standard directive scoping; rules affect+ only child files.++ o rewrite's query limits which transactions can be rewritten; all are+ printed. print --auto's query limits which transactions are printed.++ o rewrite applies rules specified on command line or in the journal.+ print --auto applies rules specified in the journal.++ roi+ roi+ Shows the time-weighted (TWR) and money-weighted (IRR) rate of return+ on your investments.++ This command assumes that you have account(s) that hold nothing but+ your investments and whenever you record current appraisal/valuation of+ these investments you offset unrealized profit and loss into account(s)+ that, again, hold nothing but unrealized profit and loss.++ Any transactions affecting balance of investment account(s) and not+ originating from unrealized profit and loss account(s) are assumed to+ be your investments or withdrawals.++ At a minimum, you need to supply a query (which could be just an ac-+ count name) to select your investments with --inv, and another query to+ identify your profit and loss transactions with --pnl.++ This command will compute and display the internalized rate of return+ (IRR) and time-weighted rate of return (TWR) for your investments for+ the time period requested. Both rates of return are annualized before+ display, regardless of the length of reporting interval.++ Note, in some cases this report can fail, for these reasons:++ o Error (NotBracketed): No solution for Internal Rate of Return (IRR).+ Possible causes: IRR is huge (>1000000%), balance of investment be-+ comes negative at some point in time.++ o Error (SearchFailed): Failed to find solution for Internal Rate of+ Return (IRR). Either search does not converge to a solution, or con-+ verges too slowly.++ Examples:++ o Using roi to report unrealised gains: https://github.com/simon-+ michael/hledger/blob/master/examples/roi-unrealised.ledger++ More background:++ "ROI" stands for "return on investment". Traditionally this was com-+ puted as a difference between current value of investment and its ini-+ tial value, expressed in percentage of the initial value.++ However, this approach is only practical in simple cases, where invest-+ ments receives no in-flows or out-flows of money, and where rate of+ growth is fixed over time. For more complex scenarios you need differ-+ ent ways to compute rate of return, and this command implements two of+ them: IRR and TWR.++ Internal rate of return, or "IRR" (also called "money-weighted rate of+ return") takes into account effects of in-flows and out-flows.+ Naively, if you are withdrawing from your investment, your future gains+ would be smaller (in absolute numbers), and will be a smaller percent-+ age of your initial investment, and if you are adding to your invest-+ ment, you will receive bigger absolute gains (but probably at the same+ rate of return). IRR is a way to compute rate of return for each pe-+ riod between in-flow or out-flow of money, and then combine them in a+ way that gives you an annual rate of return that investment is expected+ to generate.++ As mentioned before, in-flows and out-flows would be any cash that you+ personally put in or withdraw, and for the "roi" command, these are+ transactions that involve account(s) matching --inv argument and NOT+ involve account(s) matching --pnl argument.++ Presumably, you will also record changes in the value of your invest-+ ment, and balance them against "profit and loss" (or "unrealized+ gains") account. Note that in order for IRR to compute the precise ef-+ fect of your in-flows and out-flows on the rate of return, you will+ need to record the value of your investement on or close to the days+ when in- or out-flows occur.++ Implementation of IRR in hledger should match the XIRR formula in Ex-+ cel.++ Second way to compute rate of return that roi command implements is+ called "time-weighted rate of return" or "TWR". Like IRR, it will also+ break the history of your investment into periods between in-flows and+ out-flows to compute rate of return per each period and then a compound+ rate of return. However, internal workings of TWR are quite different.++ In technical terms, IRR uses the same approach as computation of net+ present value, and tries to find a discount rate that makes net present+ value of all the cash flows of your investment to add up to zero. This+ could be hard to wrap your head around, especially if you haven't done+ discounted cash flow analysis before.++ TWR represents your investment as an imaginary "unit fund" where in-+ flows/ out-flows lead to buying or selling "units" of your investment+ and changes in its value change the value of "investment unit". Change+ in "unit price" over the reporting period gives you rate of return of+ your investment.++ References: * Explanation of rate of return * Explanation of IRR * Ex-+ planation of TWR * Examples of computing IRR and TWR and discussion of+ the limitations of both metrics++ More examples:++ Lets say that we found an investment in Snake Oil that is proising to+ give us 10% annually:++ 2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++ 2019-12-24 Recording the growth of Snake Oil+ investment:snake oil = $110+ equity:unrealized gains++ For now, basic computation of the rate of return, as well as IRR and+ TWR, gives us the expected 10%:++ $ hledger roi -Y --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+-----++--------+--------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+=====++========+========++ | 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 110 | 10 || 10.00% | 10.00% |+ +---++------------+------------++---------------+----------+-------------+-----++--------+--------+++ However, lets say that shorty after investing in the Snake Oil we+ started to have second thoughs, so we prompty withdrew $90, leaving+ only $10 in. Before Christmas, though, we started to get the "fear of+ mission out", so we put the $90 back in. So for most of the year, our+ investment was just $10 dollars, and it gave us just $1 in growth:++ 2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++ 2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil++ 2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++ 2019-12-31 Recording the growth of Snake Oil+ investment:snake oil = $101+ equity:unrealized gains++ Now IRR and TWR are drastically different:++ $ hledger roi -Y --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+-----++-------+-------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+=====++=======+=======++ | 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101 | 1 || 9.32% | 1.00% |+ +---++------------+------------++---------------+----------+-------------+-----++-------+-------+++ Here, IRR tells us that we made close to 10% on the $10 dollars that we+ had in the account most of the time. And TWR is ... just 1%? Why?++ Based on the transactions in our journal, TWR "think" that we are buy-+ ing back $90 worst of Snake Oil at the same price that it had at the+ beginning of they year, and then after that our $100 investment gets $1+ increase in value, or 1% of $100. Let's take a closer look at what is+ happening here by asking for quarterly reports instead of annual:++ $ hledger roi -Q --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+-----++--------+-------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+=====++========+=======++ | 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10 | 0 || 0.00% | 0.00% |+ | 2 || 2019-04-01 | 2019-06-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+ | 3 || 2019-07-01 | 2019-09-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+ | 4 || 2019-10-01 | 2019-12-31 || 10 | 90 | 101 | 1 || 37.80% | 4.03% |+ +---++------------+------------++---------------+----------+-------------+-----++--------+-------+++ Now both IRR and TWR are thrown off by the fact that all of the growth+ for our investment happens in Q4 2019. This happes because IRR compu-+ tation is still yielding 9.32% and TWR is still 1%, but this time these+ are rates for three month period instead of twelve, so in order to get+ an annual rate they should be multiplied by four!++ Let's try to keep a better record of how Snake Oil grew in value:++ 2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++ 2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil++ 2019-02-28 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ 2019-06-30 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ 2019-09-30 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ 2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++ 2019-12-31 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ Would our quartery report look better now? Almost:++ $ hledger roi -Q --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+------++--------+--------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+======++========+========++ | 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+ | 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+ | 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+ | 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 1.00% |+ +---++------------+------------++---------------+----------+-------------+------++--------+--------+++ Something is still wrong with TWR computation for Q4, and if you have+ been paying attention you know what it is already: big $90 buy-back is+ recorded prior to the only transaction that captures the change of+ value of Snake Oil that happened in this time period. Lets combine+ transactions from 30th and 31st of Dec into one:++ 2019-12-30 Fear of missing out and growth of Snake Oil+ assets:cash -$90+ investment:snake oil+ equity:unrealized gains -$0.25++ Now growth of investment properly affects its price at the time of buy-+ back:++ $ hledger roi -Q --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+------++--------+--------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+======++========+========++ | 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+ | 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+ | 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+ | 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 9.57% |+ +---++------------+------------++---------------+----------+-------------+------++--------+--------+++ And for annual report, TWR now reports the exact profitability of our+ investment:++ $ hledger roi -Y --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+------++-------+--------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+======++=======+========++ | 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101.00 | 1.00 || 9.32% | 10.00% |+ +---++------------+------------++---------------+----------+-------------+------++-------+--------+++ stats+ stats+ Show some journal statistics.++ The stats command displays summary information for the whole journal,+ or a matched part of it. With a reporting interval, it shows a report+ for each report period.++ Example:++ $ hledger stats+ Main journal file : /src/hledger/examples/sample.journal+ Included journal files :+ Transactions span : 2008-01-01 to 2009-01-01 (366 days)+ Last transaction : 2008-12-31 (2333 days ago)+ Transactions : 5 (0.0 per day)+ Transactions last 30 days: 0 (0.0 per day)+ Transactions last 7 days : 0 (0.0 per day)+ Payees/descriptions : 5+ Accounts : 8 (depth 3)+ Commodities : 1 ($)+ Market prices : 12 ($)++ This command also supports output destination and output format selec-+ tion.++ tags+ tags+ List the unique tag names used in the journal. With a TAGREGEX argu-+ ment, only tag names matching the regular expression (case insensitive)+ are shown. With QUERY arguments, only transactions matching the query+ are considered.++ With the --values flag, the tags' unique values are listed instead.++ With --parsed flag, all tags or values are shown in the order they are+ parsed from the input data, including duplicates.++ With -E/--empty, any blank/empty values will also be shown, otherwise+ they are omitted.++ test+ test+ Run built-in unit tests.++ This command runs the unit tests built in to hledger and hledger-lib,+ printing the results on stdout. If any test fails, the exit code will+ be non-zero.++ This is mainly used by hledger developers, but you can also use it to+ sanity-check the installed hledger executable on your platform. All+ tests are expected to pass - if you ever see a failure, please report+ as a bug!++ This command also accepts tasty test runner options, written after a --+ (double hyphen). Eg to run only the tests in Hledger.Data.Amount, with+ ANSI colour codes disabled:++ $ hledger test -- -pData.Amount --color=never++ For help on these, see https://github.com/feuerbach/tasty#options (--+ --help currently doesn't show them).++ Add-on commands+ hledger also searches for external add-on commands, and will include+ these in the commands list. These are programs or scripts in your PATH+ whose name starts with hledger- and ends with a recognised file exten-+ sion (currently: no extension, bat,com,exe, hs,lhs,pl,py,rb,rkt,sh).++ Add-ons can be invoked like any hledger command, but there are a few+ things to be aware of. Eg if the hledger-web add-on is installed,++ o hledger -h web shows hledger's help, while hledger web -h shows+ hledger-web's help.++ o Flags specific to the add-on must have a preceding -- to hide them+ from hledger. So hledger web --serve --port 9000 will be rejected;+ you must use hledger web -- --serve --port 9000.++ o You can always run add-ons directly if preferred: hledger-web --serve+ --port 9000.++ Add-ons are a relatively easy way to add local features or experiment+ with new ideas. They can be written in any language, but haskell+ scripts have a big advantage: they can use the same hledger (and+ haskell) library functions that built-in commands do, for command-line+ options, journal parsing, reporting, etc.++ Two important add-ons are the hledger-ui and hledger-web user inter-+ faces. These are maintained and released along with hledger:++ ui+ hledger-ui provides an efficient terminal interface.++ web+ hledger-web provides a simple web interface.++ Third party add-ons, maintained separately from hledger, include:++ iadd+ hledger-iadd is a more interactive, terminal UI replacement for the add+ command.++ interest+ hledger-interest generates interest transactions for an account accord-+ ing to various schemes.++ A few more experimental or old add-ons can be found in hledger's bin/+ directory. These are typically prototypes and not guaranteed to work.++ENVIRONMENT+ LEDGER_FILE The journal file path when not specified with -f. Default:+ ~/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.jour-+ nal).++ A typical value is ~/DIR/YYYY.journal, where DIR is a version-con-+ trolled finance directory and YYYY is the current year. Or ~/DIR/cur-+ rent.journal, where current.journal is a symbolic link to YYYY.journal.++ On Mac computers, you can set this and other environment variables in a+ more thorough way that also affects applications started from the GUI+ (say, an Emacs dock icon). Eg on MacOS Catalina I have a ~/.MacOSX/en-+ vironment.plist file containing++ {+ "LEDGER_FILE" : "~/finance/current.journal"+ }++ To see the effect you may need to killall Dock, or reboot.++ COLUMNS The screen width used by the register command. Default: the+ full terminal width.++ NO_COLOR If this variable exists with any value, hledger will not use+ ANSI color codes in terminal output. This overrides the+ --color/--colour option.++FILES+ Reads data from one or more files in hledger journal, timeclock, time-+ dot, or CSV format specified with -f, or $LEDGER_FILE, or+ $HOME/.hledger.journal (on windows, perhaps+ C:/Users/USER/.hledger.journal).++LIMITATIONS+ The need to precede addon command options with -- when invoked from+ hledger is awkward.++ When input data contains non-ascii characters, a suitable system locale+ must be configured (or there will be an unhelpful error). Eg on POSIX,+ set LANG to something other than C.++ In a Microsoft Windows CMD window, non-ascii characters and colours are+ not supported.++ On Windows, non-ascii characters may not display correctly when running+ a hledger built in CMD in MSYS/CYGWIN, or vice-versa.++ In a Cygwin/MSYS/Mintty window, the tab key is not supported in hledger+ add.++ Not all of Ledger's journal file syntax is supported. See file format+ differences.++ On large data files, hledger is slower and uses more memory than+ Ledger.++TROUBLESHOOTING+ Here are some issues you might encounter when you run hledger (and re-+ member you can also seek help from the IRC channel, mail list or bug+ tracker):++ Successfully installed, but "No command 'hledger' found"+ stack and cabal install binaries into a special directory, which should+ be added to your PATH environment variable. Eg on unix-like systems,+ that is ~/.local/bin and ~/.cabal/bin respectively.++ I set a custom LEDGER_FILE, but hledger is still using the default file+ LEDGER_FILE should be a real environment variable, not just a shell+ variable. The command env | grep LEDGER_FILE should show it. You may+ need to use export. Here's an explanation.++ Getting errors like "Illegal byte sequence" or "Invalid or incomplete+ multibyte or wide character" or "commitAndReleaseBuffer: invalid argu-+ ment (invalid character)"+ Programs compiled with GHC (hledger, haskell build tools, etc.) need to+ have a UTF-8-aware locale configured in the environment, otherwise they+ will fail with these kinds of errors when they encounter non-ascii+ characters.++ To fix it, set the LANG environment variable to some locale which sup-+ ports UTF-8. The locale you choose must be installed on your system.++ Here's an example of setting LANG temporarily, on Ubuntu GNU/Linux:++ $ file my.journal+ my.journal: UTF-8 Unicode text # the file is UTF8-encoded+ $ echo $LANG+ C # LANG is set to the default locale, which does not support UTF8+ $ locale -a # which locales are installed ?+ C+ en_US.utf8 # here's a UTF8-aware one we can use+ POSIX+ $ LANG=en_US.utf8 hledger -f my.journal print # ensure it is used for this command++ If available, C.UTF-8 will also work. If your preferred locale isn't+ listed by locale -a, you might need to install it. Eg on Ubuntu/De-+ bian:++ $ apt-get install language-pack-fr+ $ locale -a+ C+ en_US.utf8+ fr_BE.utf8+ fr_CA.utf8+ fr_CH.utf8+ fr_FR.utf8+ fr_LU.utf8+ POSIX+ $ LANG=fr_FR.utf8 hledger -f my.journal print++ Here's how you could set it permanently, if you use a bash shell:++ $ echo "export LANG=en_US.utf8" >>~/.bash_profile+ $ bash --login++ Exact spelling and capitalisation may be important. Note the differ-+ ence on MacOS (UTF-8, not utf8). Some platforms (eg ubuntu) allow+ variant spellings, but others (eg macos) require it to be exact:++ $ locale -a | grep -iE en_us.*utf+ en_US.UTF-8+ $ LANG=en_US.UTF-8 hledger -f my.journal print++++REPORTING BUGS+ Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel+ or hledger mail list)+++AUTHORS+ Simon Michael <simon@joyful.com> and contributors+++COPYRIGHT+ Copyright (C) 2007-2019 Simon Michael.+ Released under GNU GPL v3 or later.+++SEE ALSO+ hledger(1), hledger-ui(1), hledger-web(1), hledger-api(1),+ hledger_csv(5), hledger_journal(5), hledger_timeclock(5), hledger_time-+ dot(5), ledger(1)++ http://hledger.org++++hledger 1.20 November 2020 hledger(1)
embeddedfiles/hledger_csv.5 view
@@ -1,6 +1,6 @@ .\"t -.TH "hledger_csv" "5" "September 2020" "hledger 1.18.99" "hledger User Manuals"+.TH "hledger_csv" "5" "November 2020" "hledger 1.20" "hledger User Manuals" @@ -75,9 +75,14 @@ T{ \f[B]\f[CB]date-format\f[B]\f[R] T}@T{-describe the format of CSV dates+how to parse dates in CSV records T} T{+\f[B]\f[CB]decimal-mark\f[B]\f[R]+T}@T{+the decimal mark used in CSV amounts, if ambiguous+T}+T{ \f[B]\f[CB]newest-first\f[B]\f[R] T}@T{ disambiguate record order when there\[aq]s only one date@@ -866,6 +871,27 @@ .P .PD https://hackage.haskell.org/package/time/docs/Data-Time-Format.html#v:formatTime+.SS \f[C]decimal-mark\f[R]+.IP+.nf+\f[C]+decimal-mark .+\f[R]+.fi+.PP+or:+.IP+.nf+\f[C]+decimal-mark ,+\f[R]+.fi+.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. .SS \f[C]newest-first\f[R] .PP hledger always sorts the generated transactions by date.@@ -1087,31 +1113,80 @@ .SS Setting currency/commodity .PP If the currency/commodity symbol is included in the CSV\[aq]s amount-field(s), you don\[aq]t have to do anything special.+field(s):+.IP+.nf+\f[C]+2020-01-01,foo,$123.00+\f[R]+.fi .PP-If the currency is provided as a separate CSV field, you can either:-.IP \[bu] 2-assign that to \f[C]currency\f[R], which adds it to all posting amounts.-The symbol will prepended to the amount quantity (on the left side).-If you write a trailing space after the symbol, there will be a space-between symbol and amount (an exception to the usual whitespace-stripping).-.IP \[bu] 2-or assign it to \f[C]currencyN\f[R] which adds it to posting N\[aq]s-amount only.-.IP \[bu] 2-or for more control, construct the amount from symbol and quantity using-field assignment, eg:-.RS 2+you don\[aq]t have to do anything special for the commodity symbol, it+will be assigned as part of the amount.+Eg: .IP .nf \f[C]-fields date,description,currency,quantity-# add currency symbol on the right:-amount %quantity %currency+fields date,description,amount \f[R] .fi-.RE+.IP+.nf+\f[C]+2020-01-01 foo+ expenses:unknown $123.00+ income:unknown $-123.00+\f[R]+.fi+.PP+If the currency is provided as a separate CSV field:+.IP+.nf+\f[C]+2020-01-01,foo,USD,123.00+\f[R]+.fi+.PP+You can assign that to the \f[C]currency\f[R] pseudo-field, which has+the special effect of prepending itself to every amount in the+transaction (on the left, with no separating space):+.IP+.nf+\f[C]+fields date,description,currency,amount+\f[R]+.fi+.IP+.nf+\f[C]+2020-01-01 foo+ expenses:unknown USD123.00+ income:unknown USD-123.00+\f[R]+.fi+.PP+Or, you can use a field assignment to construct the amount yourself,+with more control.+Eg to put the symbol on the right, and separated by a space:+.IP+.nf+\f[C]+fields date,description,cur,amt+amount %amt %cur+\f[R]+.fi+.IP+.nf+\f[C]+2020-01-01 foo+ expenses:unknown 123.00 USD+ income:unknown -123.00 USD+\f[R]+.fi+.PP+Note we used a temporary field name (\f[C]cur\f[R]) that is not+\f[C]currency\f[R] - that would trigger the prepending effect, which we+don\[aq]t want here. .SS Referencing other fields .PP In field assignments, you can interpolate only CSV fields, not hledger
embeddedfiles/hledger_csv.info view
@@ -3,8 +3,8 @@ File: hledger_csv.info, Node: Top, Next: EXAMPLES, Up: (dir) -hledger_csv(5) hledger 1.18.99-******************************+hledger_csv(5) hledger 1.20+*************************** CSV - how hledger reads CSV data, and the CSV rules file format @@ -42,7 +42,9 @@ *'if' table* apply some rules to CSV records matched by patterns, alternate syntax *'end'* skip the remaining CSV records-*'date-format'* describe the format of CSV dates+*'date-format'* how to parse dates in CSV records+*'decimal-mark'* the decimal mark used in CSV amounts,+ if ambiguous *'newest-first'* disambiguate record order when there's only one date *'include'* inline another CSV rules file@@ -387,6 +389,7 @@ * if table:: * end:: * date-format::+* decimal-mark:: * newest-first:: * include:: * balance-type::@@ -787,7 +790,7 @@ end -File: hledger_csv.info, Node: date-format, Next: newest-first, Prev: end, Up: CSV RULES+File: hledger_csv.info, Node: date-format, Next: decimal-mark, Prev: end, Up: CSV RULES 2.8 'date-format' =================@@ -818,11 +821,29 @@ https://hackage.haskell.org/package/time/docs/Data-Time-Format.html#v:formatTime -File: hledger_csv.info, Node: newest-first, Next: include, Prev: date-format, Up: CSV RULES+File: hledger_csv.info, Node: decimal-mark, Next: newest-first, Prev: date-format, Up: CSV RULES -2.9 'newest-first'+2.9 'decimal-mark' ================== +decimal-mark .++ or:++decimal-mark ,++ 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.+++File: hledger_csv.info, Node: newest-first, Next: include, Prev: decimal-mark, Up: CSV RULES++2.10 'newest-first'+===================+ hledger always sorts the generated transactions by date. Transactions on the same date should appear in the same order as their CSV records, as hledger can usually auto-detect whether the CSV's normal order is@@ -842,7 +863,7 @@ File: hledger_csv.info, Node: include, Next: balance-type, Prev: newest-first, Up: CSV RULES -2.10 'include'+2.11 'include' ============== include RULESFILE@@ -865,7 +886,7 @@ File: hledger_csv.info, Node: balance-type, Prev: include, Up: CSV RULES -2.11 'balance-type'+2.12 'balance-type' =================== Balance assertions generated by assigning to balanceN are of the simple@@ -1049,26 +1070,47 @@ ============================== If the currency/commodity symbol is included in the CSV's amount-field(s), you don't have to do anything special.+field(s): - If the currency is provided as a separate CSV field, you can either:+2020-01-01,foo,$123.00 - * assign that to 'currency', which adds it to all posting amounts.- The symbol will prepended to the amount quantity (on the left- side). If you write a trailing space after the symbol, there will- be a space between symbol and amount (an exception to the usual- whitespace stripping).+ you don't have to do anything special for the commodity symbol, it+will be assigned as part of the amount. Eg: - * or assign it to 'currencyN' which adds it to posting N's amount- only.+fields date,description,amount - * or for more control, construct the amount from symbol and quantity- using field assignment, eg:+2020-01-01 foo+ expenses:unknown $123.00+ income:unknown $-123.00 - fields date,description,currency,quantity- # add currency symbol on the right:- amount %quantity %currency+ If the currency is provided as a separate CSV field: +2020-01-01,foo,USD,123.00++ You can assign that to the 'currency' pseudo-field, which has the+special effect of prepending itself to every amount in the transaction+(on the left, with no separating space):++fields date,description,currency,amount++2020-01-01 foo+ expenses:unknown USD123.00+ income:unknown USD-123.00++ Or, you can use a field assignment to construct the amount yourself,+with more control. Eg to put the symbol on the right, and separated by+a space:++fields date,description,cur,amt+amount %amt %cur++2020-01-01 foo+ expenses:unknown 123.00 USD+ income:unknown -123.00 USD++ Note we used a temporary field name ('cur') that is not 'currency' -+that would trigger the prepending effect, which we don't want here.+ File: hledger_csv.info, Node: Referencing other fields, Next: How CSV rules are evaluated, Prev: Setting currency/commodity, Up: TIPS @@ -1150,84 +1192,86 @@ Tag Table: Node: Top72-Node: EXAMPLES2677-Ref: #examples2783-Node: Basic2991-Ref: #basic3091-Node: Bank of Ireland3633-Ref: #bank-of-ireland3768-Node: Amazon5230-Ref: #amazon5348-Node: Paypal7067-Ref: #paypal7161-Node: CSV RULES14805-Ref: #csv-rules14914-Node: skip15209-Ref: #skip15302-Node: fields15677-Ref: #fields15799-Node: Transaction field names16964-Ref: #transaction-field-names17124-Node: Posting field names17235-Ref: #posting-field-names17387-Node: account17457-Ref: #account17573-Node: amount18110-Ref: #amount18241-Node: currency19348-Ref: #currency19483-Node: balance19689-Ref: #balance19823-Node: comment20140-Ref: #comment20257-Node: field assignment20420-Ref: #field-assignment20563-Node: separator21381-Ref: #separator21516-Node: if block22056-Ref: #if-block22181-Node: Matching the whole record22582-Ref: #matching-the-whole-record22757-Node: Matching individual fields23561-Ref: #matching-individual-fields23765-Node: Combining matchers23989-Ref: #combining-matchers24185-Node: Rules applied on successful match24498-Ref: #rules-applied-on-successful-match24689-Node: if table25343-Ref: #if-table25462-Node: end27200-Ref: #end27312-Node: date-format27536-Ref: #date-format27668-Node: newest-first28417-Ref: #newest-first28555-Node: include29238-Ref: #include29369-Node: balance-type29813-Ref: #balance-type29933-Node: TIPS30633-Ref: #tips30715-Node: Rapid feedback30971-Ref: #rapid-feedback31088-Node: Valid CSV31548-Ref: #valid-csv31678-Node: File Extension31870-Ref: #file-extension32022-Node: Reading multiple CSV files32451-Ref: #reading-multiple-csv-files32636-Node: Valid transactions32877-Ref: #valid-transactions33055-Node: Deduplicating importing33683-Ref: #deduplicating-importing33862-Node: Setting amounts34895-Ref: #setting-amounts35064-Node: Setting currency/commodity36051-Ref: #setting-currencycommodity36243-Node: Referencing other fields37046-Ref: #referencing-other-fields37246-Node: How CSV rules are evaluated38143-Ref: #how-csv-rules-are-evaluated38316+Node: EXAMPLES2787+Ref: #examples2893+Node: Basic3101+Ref: #basic3201+Node: Bank of Ireland3743+Ref: #bank-of-ireland3878+Node: Amazon5340+Ref: #amazon5458+Node: Paypal7177+Ref: #paypal7271+Node: CSV RULES14915+Ref: #csv-rules15024+Node: skip15336+Ref: #skip15429+Node: fields15804+Ref: #fields15926+Node: Transaction field names17091+Ref: #transaction-field-names17251+Node: Posting field names17362+Ref: #posting-field-names17514+Node: account17584+Ref: #account17700+Node: amount18237+Ref: #amount18368+Node: currency19475+Ref: #currency19610+Node: balance19816+Ref: #balance19950+Node: comment20267+Ref: #comment20384+Node: field assignment20547+Ref: #field-assignment20690+Node: separator21508+Ref: #separator21643+Node: if block22183+Ref: #if-block22308+Node: Matching the whole record22709+Ref: #matching-the-whole-record22884+Node: Matching individual fields23688+Ref: #matching-individual-fields23892+Node: Combining matchers24116+Ref: #combining-matchers24312+Node: Rules applied on successful match24625+Ref: #rules-applied-on-successful-match24816+Node: if table25470+Ref: #if-table25589+Node: end27327+Ref: #end27439+Node: date-format27663+Ref: #date-format27795+Node: decimal-mark28544+Ref: #decimal-mark28687+Node: newest-first29026+Ref: #newest-first29167+Node: include29850+Ref: #include29981+Node: balance-type30425+Ref: #balance-type30545+Node: TIPS31245+Ref: #tips31327+Node: Rapid feedback31583+Ref: #rapid-feedback31700+Node: Valid CSV32160+Ref: #valid-csv32290+Node: File Extension32482+Ref: #file-extension32634+Node: Reading multiple CSV files33063+Ref: #reading-multiple-csv-files33248+Node: Valid transactions33489+Ref: #valid-transactions33667+Node: Deduplicating importing34295+Ref: #deduplicating-importing34474+Node: Setting amounts35507+Ref: #setting-amounts35676+Node: Setting currency/commodity36663+Ref: #setting-currencycommodity36855+Node: Referencing other fields38029+Ref: #referencing-other-fields38229+Node: How CSV rules are evaluated39126+Ref: #how-csv-rules-are-evaluated39299 End Tag Table
embeddedfiles/hledger_csv.txt view
@@ -39,26 +39,28 @@ if table apply some rules to CSV records matched by patterns, alternate syntax end skip the remaining CSV records- date-format describe the format of CSV dates- newest-first disambiguate record order when there's+ date-format how to parse dates in CSV records+ decimal-mark the decimal mark used in CSV amounts, if+ ambiguous+ newest-first disambiguate record order when there's only one date include inline another CSV rules file balance-type choose which type of balance assignments to use - Note, for best error messages when reading CSV files, use a .csv, .tsv+ Note, for best error messages when reading CSV files, use a .csv, .tsv or .ssv file extension or file prefix - see File Extension below. There's an introductory Convert CSV files tutorial on hledger.org. EXAMPLES- Here are some sample hledger CSV rules files. See also the full col-+ Here are some sample hledger CSV rules files. See also the full col- lection at: https://github.com/simonmichael/hledger/tree/master/examples/csv Basic- 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+ 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's a simple CSV file and a rules file for it: Date, Description, Id, Amount@@ -77,8 +79,8 @@ Default account names are chosen, since we didn't set them. Bank of Ireland- Here's a CSV with two amount fields (Debit and Credit), and a balance- field, which we can use to add balance assertions, which is not neces-+ Here's a CSV with two amount fields (Debit and Credit), and a balance+ field, which we can use to add balance assertions, which is not neces- sary but provides extra error checking: Date,Details,Debit,Credit,Balance@@ -120,13 +122,13 @@ assets:bank:boi:checking EUR-5.0 = EUR126.0 expenses:unknown EUR5.0 - The balance assertions don't raise an error above, because we're read-- ing directly from CSV, but they will be checked if these entries are+ The balance assertions don't raise an error above, because we're read-+ ing directly from CSV, but they will be checked if these entries are imported into a journal file. Amazon Here we convert amazon.com order history, and use an if block to gener-- ate a third posting if there's a fee. (In practice you'd probably get+ ate a third posting if there's a fee. (In practice you'd probably get this data from your bank instead, but it's an example.) "Date","Type","To/From","Name","Status","Amount","Fees","Transaction ID"@@ -178,7 +180,7 @@ expenses:fees $1.00 Paypal- Here's a real-world rules file for (customised) Paypal CSV, with some+ Here's a real-world rules file for (customised) Paypal CSV, with some Paypal-specific rules, and a second rules file included: "Date","Time","TimeZone","Name","Type","Status","Currency","Gross","Fee","Net","From Email Address","To Email Address","Transaction ID","Item Title","Item ID","Reference Txn ID","Receipt ID","Balance","Note"@@ -333,9 +335,9 @@ skip skip N - The word "skip" followed by a number (or no number, meaning 1) tells- hledger to ignore this many non-empty lines preceding the CSV data.- (Empty/blank lines are skipped automatically.) You'll need this when-+ The word "skip" followed by a number (or no number, meaning 1) tells+ hledger to ignore this many non-empty lines preceding the CSV data.+ (Empty/blank lines are skipped automatically.) You'll need this when- ever your CSV data contains header lines. It also has a second purpose: it can be used inside if blocks to ignore@@ -344,27 +346,27 @@ fields fields FIELDNAME1, FIELDNAME2, ... - A fields list (the word "fields" followed by comma-separated field- names) is the quick way to assign CSV field values to hledger fields.+ A fields list (the word "fields" followed by comma-separated field+ names) is the quick way to assign CSV field values to hledger fields. It does two things: - 1. it names the CSV fields. This is optional, but can be convenient+ 1. it names the CSV fields. This is optional, but can be convenient later for interpolating them. 2. when you use a standard hledger field name, it assigns the CSV value to that part of the hledger transaction. - Here's an example that says "use the 1st, 2nd and 4th fields as the- transaction's date, description and amount; name the last two fields+ Here's an example that says "use the 1st, 2nd and 4th fields as the+ transaction's date, description and amount; name the last two fields for later reference; and ignore the others": fields date, description, , amount, , , somefield, anotherfield - Field names may not contain whitespace. Fields you don't care about- can be left unnamed. Currently there must be least two items (there+ Field names may not contain whitespace. Fields you don't care about+ can be left unnamed. Currently there must be least two items (there must be at least one comma). - Note, always use comma in the fields list, even if your CSV uses an-+ Note, always use comma in the fields list, even if your CSV uses an- other separator character. Here are the standard hledger field/pseudo-field names. For more about@@ -377,52 +379,52 @@ Posting field names account- accountN, where N is 1 to 99, causes a posting to be generated, with+ accountN, where N is 1 to 99, causes a posting to be generated, with that account name. - Most often there are two postings, so you'll want to set account1 and- account2. Typically account1 is associated with the CSV file, and is- set once with a top-level assignment, while account2 is set based on+ Most often there are two postings, so you'll want to set account1 and+ account2. Typically account1 is associated with the CSV file, and is+ set once with a top-level assignment, while account2 is set based on each transaction's description, and in conditional blocks. - If a posting's account name is left unset but its amount is set (see- below), a default account name will be chosen (like "expenses:unknown"+ If a posting's account name is left unset but its amount is set (see+ below), a default account name will be chosen (like "expenses:unknown" or "income:unknown"). amount- amountN sets posting N's amount. If the CSV uses separate fields for- inflows and outflows, you can use amountN-in and amountN-out instead.- By assigning to amount1, amount2, ... etc. you can generate anywhere+ amountN sets posting N's amount. If the CSV uses separate fields for+ inflows and outflows, you can use amountN-in and amountN-out instead.+ By assigning to amount1, amount2, ... etc. you can generate anywhere from 0 to 99 postings. - There is also an older, unnumbered form of these names, suitable for+ There is also an older, unnumbered form of these names, suitable for 2-posting transactions, which sets both posting 1's and (negated) post-- ing 2's amount: amount, or amount-in and amount-out. This is still- supported because it keeps pre-hledger-1.17 csv rules files working,- and because it can be more succinct, and because it converts posting+ ing 2's amount: amount, or amount-in and amount-out. This is still+ supported because it keeps pre-hledger-1.17 csv rules files working,+ and because it can be more succinct, and because it converts posting 2's amount to cost if there's a transaction price, which can be useful. If you have an existing rules file using the unnumbered form, you might- want to use the numbered form in certain conditional blocks, without- having to update and retest all the old rules. To facilitate this,- posting 1 ignores amount/amount-in/amount-out if any of+ want to use the numbered form in certain conditional blocks, without+ having to update and retest all the old rules. To facilitate this,+ posting 1 ignores amount/amount-in/amount-out if any of amount1/amount1-in/amount1-out are assigned, and posting 2 ignores them- if any of amount2/amount2-in/amount2-out are assigned, avoiding con-+ if any of amount2/amount2-in/amount2-out are assigned, avoiding con- flicts. currency If the CSV has the currency symbol in a separate field (ie, not part of- the amount field), you can use currencyN to prepend it to posting N's+ the amount field), you can use currencyN to prepend it to posting N's amount. Or, currency with no number affects all postings. balance- balanceN sets a balance assertion amount (or if the posting amount is+ balanceN sets a balance assertion amount (or if the posting amount is left empty, a balance assignment) on posting N. - Also, for compatibility with hledger <1.17: balance with no number is+ Also, for compatibility with hledger <1.17: balance with no number is equivalent to balance1. - You can adjust the type of assertion/assignment with the balance-type+ You can adjust the type of assertion/assignment with the balance-type rule (see below). comment@@ -434,11 +436,11 @@ field assignment HLEDGERFIELDNAME FIELDVALUE - Instead of or in addition to a fields list, you can use a "field as-- signment" rule to set the value of a single hledger field, by writing- its name (any of the standard hledger field names above) followed by a- text value. The value may contain interpolated CSV fields, referenced- by their 1-based position in the CSV record (%N), or by the name they+ Instead of or in addition to a fields list, you can use a "field as-+ signment" rule to set the value of a single hledger field, by writing+ its name (any of the standard hledger field names above) followed by a+ text value. The value may contain interpolated CSV fields, referenced+ by their 1-based position in the CSV record (%N), or by the name they were given in the fields list (%CSVFIELDNAME). Some examples: # set the amount to the 4th CSV field, with " USD" appended@@ -447,14 +449,14 @@ # combine three fields to make a comment, containing note: and date: tags comment note: %somefield - %anotherfield, date: %1 - Interpolation strips outer whitespace (so a CSV value like " 1 " be-+ Interpolation strips outer whitespace (so a CSV value like " 1 " be- comes 1 when interpolated) (#1051). See TIPS below for more about ref- erencing other fields. separator- You can use the separator rule to read other kinds of character-sepa-- rated data. The argument is any single separator character, or the- words tab or space (case insensitive). Eg, for comma-separated values+ You can use the separator rule to read other kinds of character-sepa-+ rated data. The argument is any single separator character, or the+ words tab or space (case insensitive). Eg, for comma-separated values (CSV): separator ,@@ -467,7 +469,7 @@ separator TAB - If the input file has a .csv, .ssv or .tsv file extension (or a csv:,+ If the input file has a .csv, .ssv or .tsv file extension (or a csv:, ssv:, tsv: prefix), the appropriate separator will be inferred automat- ically, and you won't need this rule. @@ -482,8 +484,8 @@ RULE RULE - Conditional blocks ("if blocks") are a block of rules that are applied- only to CSV records which match certain patterns. They are often used+ Conditional blocks ("if blocks") are a block of rules that are applied+ only to CSV records which match certain patterns. They are often used for customising account names based on transaction descriptions. Matching the whole record@@ -491,16 +493,16 @@ REGEX - REGEX is a case-insensitive regular expression which tries to match- anywhere within the CSV record. It is a POSIX ERE (extended regular- expression) that also supports GNU word boundaries (\b, \B, \<, \>),+ REGEX is a case-insensitive regular expression which tries to match+ anywhere within the CSV record. It is a POSIX ERE (extended regular+ expression) that also supports GNU word boundaries (\b, \B, \<, \>), and nothing else. If you have trouble, be sure to check our https://hledger.org/hledger.html#regular-expressions doc. - Important note: the record that is matched is not the original record,- but a synthetic one, with any enclosing double quotes (but not enclos-+ Important note: the record that is matched is not the original record,+ but a synthetic one, with any enclosing double quotes (but not enclos- ing whitespace) removed, and always comma-separated (which means that a- field containing a comma will appear like two fields). Eg, if the+ field containing a comma will appear like two fields). Eg, if the original record is 2020-01-01; "Acme, Inc."; 1,000, the REGEX will ac- tually see 2020-01-01,Acme, Inc., 1,000). @@ -509,14 +511,14 @@ %CSVFIELD REGEX - which matches just the content of a particular CSV field. CSVFIELD is- a percent sign followed by the field's name or column number, like+ which matches just the content of a particular CSV field. CSVFIELD is+ a percent sign followed by the field's name or column number, like %date or %1. Combining matchers A single matcher can be written on the same line as the "if"; or multi- ple matchers can be written on the following lines, non-indented. Mul-- tiple matchers are OR'd (any one of them can match), unless one begins+ tiple matchers are OR'd (any one of them can match), unless one begins with an & symbol, in which case it is AND'ed with the previous matcher. if@@ -525,8 +527,8 @@ RULE Rules applied on successful match- After the patterns there should be one or more rules to apply, all in-- dented by at least one space. Three kinds of rule are allowed in con-+ After the patterns there should be one or more rules to apply, all in-+ dented by at least one space. Three kinds of rule are allowed in con- ditional blocks: o field assignments (to set a hledger field)@@ -556,11 +558,11 @@ MATCHER3,VALUE31,VALUE32,...,VALUE3n <empty line> - Conditional tables ("if tables") are a different syntax to specify- field assignments that will be applied only to CSV records which match+ Conditional tables ("if tables") are a different syntax to specify+ field assignments that will be applied only to CSV records which match certain patterns. - MATCHER could be either field or record matcher, as described above.+ MATCHER could be either field or record matcher, as described above. When MATCHER matches, values from that row would be assigned to the CSV fields named on the if line, in the same order. @@ -584,17 +586,17 @@ ... CSVFIELDNAMEn VALUE3n - Each line starting with MATCHER should contain enough (possibly empty)+ Each line starting with MATCHER should contain enough (possibly empty) values for all the listed fields. - Rules would be checked and applied in the order they are listed in the+ Rules would be checked and applied in the order they are listed in the table and, like with if blocks, later rules (in the same or another ta- ble) or if blocks could override the effect of any rule. - Instead of ',' you can use a variety of other non-alphanumeric charac-+ Instead of ',' you can use a variety of other non-alphanumeric charac- ters as a separator. First character after if is taken to be the sepa-- rator for the rest of the table. It is the responsibility of the user- to ensure that separator does not occur inside MATCHERs and values -+ rator for the rest of the table. It is the responsibility of the user+ to ensure that separator does not occur inside MATCHERs and values - there is no way to escape separator. Example:@@ -605,7 +607,7 @@ 2020/01/12.*Plumbing LLC,expenses:house:upkeep,emergency plumbing call-out end- This rule can be used inside if blocks (only), to make hledger stop+ This rule can be used inside if blocks (only), to make hledger stop reading this CSV file and move on to the next input file, or to command execution. Eg: @@ -616,10 +618,10 @@ date-format date-format DATEFMT - This is a helper for the date (and date2) fields. If your CSV dates- are not formatted like YYYY-MM-DD, YYYY/MM/DD or YYYY.MM.DD, you'll- need to add a date-format rule describing them with a strptime date- parsing pattern, which must parse the CSV date value completely. Some+ This is a helper for the date (and date2) fields. If your CSV dates+ are not formatted like YYYY-MM-DD, YYYY/MM/DD or YYYY.MM.DD, you'll+ need to add a date-format rule describing them with a strptime date+ parsing pattern, which must parse the CSV date value completely. Some examples: # MM/DD/YY@@ -640,16 +642,29 @@ https://hackage.haskell.org/package/time/docs/Data-Time-For- mat.html#v:formatTime + decimal-mark+ decimal-mark .++ or:++ decimal-mark ,++ 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.+ newest-first- hledger always sorts the generated transactions by date. Transactions- on the same date should appear in the same order as their CSV records,- as hledger can usually auto-detect whether the CSV's normal order is+ hledger always sorts the generated transactions by date. Transactions+ on the same date should appear in the same order as their CSV records,+ as hledger can usually auto-detect whether the CSV's normal order is oldest first or newest first. But if all of the following are true: - o the CSV might sometimes contain just one day of data (all records+ o the CSV might sometimes contain just one day of data (all records having the same date) - o the CSV records are normally in reverse chronological order (newest+ o the CSV records are normally in reverse chronological order (newest at the top) o and you care about preserving the order of same-day transactions@@ -662,9 +677,9 @@ include include RULESFILE - This includes the contents of another CSV rules file at this point.- RULESFILE is an absolute file path or a path relative to the current- file's directory. This can be useful for sharing common rules between+ This includes the contents of another CSV rules file at this point.+ RULESFILE is an absolute file path or a path relative to the current+ file's directory. This can be useful for sharing common rules between several rules files, eg: # someaccount.csv.rules@@ -679,10 +694,10 @@ balance-type Balance assertions generated by assigning to balanceN are of the simple- = type by default, which is a single-commodity, subaccount-excluding+ = 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+ eg if you have created some virtual subaccounts of checking to help+ with budgeting. You can select a different type of assertion with the balance-type rule: # balance assertions will consider all commodities and all subaccounts@@ -697,19 +712,19 @@ TIPS Rapid feedback- It's a good idea to get rapid feedback while creating/troubleshooting+ It's a good idea to get rapid feedback while creating/troubleshooting CSV rules. Here's a good way, using entr from http://eradman.com/entr- project : $ ls foo.csv* | entr bash -c 'echo ----; hledger -f foo.csv print desc:SOMEDESC' - A desc: query (eg) is used to select just one, or a few, transactions- of interest. "bash -c" is used to run multiple commands, so we can- echo a separator each time the command re-runs, making it easier to+ A desc: query (eg) is used to select just one, or a few, transactions+ of interest. "bash -c" 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. Valid CSV- hledger accepts CSV conforming to RFC 4180. When CSV values are en-+ hledger accepts CSV conforming to RFC 4180. When CSV values are en- closed in quotes, note: o they must be double quotes (not single quotes)@@ -717,9 +732,9 @@ o spaces outside the quotes are not allowed File Extension- To help hledger identify the format and show the right error messages,- CSV/SSV/TSV files should normally be named with a .csv, .ssv or .tsv- filename extension. Or, the file path should be prefixed with csv:,+ To help hledger identify the format and show the right error messages,+ CSV/SSV/TSV files should normally be named with a .csv, .ssv or .tsv+ filename extension. Or, the file path should be prefixed with csv:, ssv: or tsv:. Eg: $ hledger -f foo.ssv print@@ -728,48 +743,48 @@ $ cat foo | hledger -f ssv:- foo - You can override the file extension with a separator rule if needed.+ You can override the file extension with a separator rule if needed. See also: Input files in the hledger manual. Reading multiple CSV files- If you use multiple -f options to read multiple CSV files at once,- hledger will look for a correspondingly-named rules file for each CSV- file. But if you use the --rules-file option, that rules file will be+ If you use multiple -f options to read multiple CSV files at once,+ hledger will look for a correspondingly-named rules file for each CSV+ file. But if you use the --rules-file option, that rules file will be used for all the CSV files. Valid transactions After reading a CSV file, hledger post-processes and validates the gen- erated 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+ applying balance assignments, and canonicalising amount styles. Any+ errors at this stage will be reported in the usual way, displaying the problem entry. 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 as-+ 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 as- sertions generated from CSV right away, pipe into another hledger: $ hledger -f file.csv print | hledger -f- print 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+ 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. 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't have to remember how many times you ran it or with which version- of the CSV. (It keeps state in a hidden .latest.FILE.csv file.) This+ don't have to remember how many times you ran it or with which version+ of the CSV. (It keeps state in a hidden .latest.FILE.csv file.) This is the easiest way to import CSV data. Eg: # download the latest CSV files, then run this command. # Note, no -f flags needed here. $ hledger import *.csv [--dry] - This method works for most CSV files. (Where records have a stable+ This method works for most CSV files. (Where records have a stable chronological order, and new records appear only at the new end.) - A number of other tools and workflows, hledger-specific and otherwise,+ A number of other tools and workflows, hledger-specific and otherwise, exist for converting, deduplicating, classifying and managing CSV data. See: @@ -780,49 +795,71 @@ Setting amounts A posting amount can be set in one of these ways: - o by assigning (with a fields list or field assignment) to amountN+ o by assigning (with a fields list or field assignment) to amountN (posting N's amount) or amount (posting 1's amount) - o by assigning to amountN-in and amountN-out (or amount-in and amount-- out). For each CSV record, whichever of these has a non-zero value- will be used, with appropriate sign. If both contain a non-zero+ o by assigning to amountN-in and amountN-out (or amount-in and amount-+ out). For each CSV record, whichever of these has a non-zero value+ will be used, with appropriate sign. If both contain a non-zero value, this may not work. - o by assigning to balanceN (or balance) instead of the above, setting- the amount indirectly via a balance assignment. If you do this the+ o by assigning to balanceN (or balance) instead of the above, setting+ the amount indirectly via a balance assignment. If you do this the default account name may be wrong, so you should set that explicitly. There is some special handling for an amount's sign: - o If an amount value is parenthesised, it will be de-parenthesised and+ o If an amount value is parenthesised, it will be de-parenthesised and sign-flipped. - o If an amount value begins with a double minus sign, those cancel out+ o If an amount value begins with a double minus sign, those cancel out and are removed. o If an amount value begins with a plus sign, that will be removed Setting currency/commodity- If the currency/commodity symbol is included in the CSV's amount- field(s), you don't have to do anything special.+ If the currency/commodity symbol is included in the CSV's amount+ field(s): - If the currency is provided as a separate CSV field, you can either:+ 2020-01-01,foo,$123.00 - o assign that to currency, which adds it to all posting amounts. The- symbol will prepended to the amount quantity (on the left side). If- you write a trailing space after the symbol, there will be a space- between symbol and amount (an exception to the usual whitespace- stripping).+ you don't have to do anything special for the commodity symbol, it will+ be assigned as part of the amount. Eg: - o or assign it to currencyN which adds it to posting N's amount only.+ fields date,description,amount - o or for more control, construct the amount from symbol and quantity- using field assignment, eg:+ 2020-01-01 foo+ expenses:unknown $123.00+ income:unknown $-123.00 - fields date,description,currency,quantity- # add currency symbol on the right:- amount %quantity %currency+ If the currency is provided as a separate CSV field: + 2020-01-01,foo,USD,123.00++ You can assign that to the currency pseudo-field, which has the special+ effect of prepending itself to every amount in the transaction (on the+ left, with no separating space):++ fields date,description,currency,amount++ 2020-01-01 foo+ expenses:unknown USD123.00+ income:unknown USD-123.00++ Or, you can use a field assignment to construct the amount yourself,+ with more control. Eg to put the symbol on the right, and separated by+ a space:++ fields date,description,cur,amt+ amount %amt %cur++ 2020-01-01 foo+ expenses:unknown 123.00 USD+ income:unknown -123.00 USD++ Note we used a temporary field name (cur) that is not currency - that+ would trigger the prepending effect, which we don't want here.+ Referencing other fields In field assignments, you can interpolate only CSV fields, not hledger fields. In the example below, there's both a CSV field and a hledger@@ -922,4 +959,4 @@ -hledger 1.18.99 September 2020 hledger_csv(5)+hledger 1.20 November 2020 hledger_csv(5)
embeddedfiles/hledger_journal.5 view
@@ -1,6 +1,6 @@ .\"t -.TH "hledger_journal" "5" "September 2020" "hledger 1.18.99" "hledger User Manuals"+.TH "hledger_journal" "5" "November 2020" "hledger 1.20" "hledger User Manuals" @@ -584,40 +584,59 @@ commodity 1 000 000.9455 \f[R] .fi-.SS Amount display style .PP-For each commodity, hledger chooses a consistent format to use when+.SS Commodity display style+.PP+For each commodity, hledger chooses a consistent style to use when displaying amounts. (Except price amounts, which are always displayed as written). The display style is chosen as follows: .IP \[bu] 2 If there is a commodity directive (or default commodity directive) for-the commodity, that format is used (see examples above).+the commodity, its style is used (see examples above). .IP \[bu] 2-Otherwise the format of the first posting amount in that commodity seen-in the journal is used.-But the number of decimal places (\[dq]precision\[dq]) will be the-maximum from all posting amounts in that commodity.+Otherwise the style is inferred from the amounts in that commodity seen+in the journal. .IP \[bu] 2-Or if there are no such amounts in the journal, a default format is used+Or if there are no such amounts in the journal, a default style is used (like \f[C]$1000.00\f[R]). .PP-Transaction prices don\[aq]t affect the amount display style directly,-but occasionally they can do so indirectly (eg when an posting\[aq]s-amount is inferred using a transaction price).+A style is inferred from the journal amounts in a commodity as follows:+.IP \[bu] 2+Use the general style (decimal mark, symbol placement) of the first+amount+.IP \[bu] 2+Use the first-seen digit group style (digit group mark, digit group+sizes), if any+.IP \[bu] 2+Use the maximum number of decimal places of all.+.PP+Transaction price amounts don\[aq]t affect the commodity display style+directly, but occasionally they can do so indirectly (eg when a+posting\[aq]s amount is inferred using a transaction price). If you find this causing problems, use a commodity directive to fix the display style. .PP-In summary: amounts will be displayed much as they appear in your-journal, with the max observed number of decimal places.-If you want to see fewer decimal places in reports, use a commodity-directive to override that.+In summary, each commodity\[aq]s amounts will be normalised to+.IP \[bu] 2+the style declared by a \f[C]commodity\f[R] directive+.IP \[bu] 2+or, the style of the first posting amount in the journal, with the+first-seen digit group style and the maximum-seen number of decimal+places. .PP-hledger uses banker\[aq]s rounding: it rounds to the nearest even+If reports are showing amounts in a way you don\[aq]t like (eg, with too+many decimal places), use a commodity directive to set your preferred+style.+.SS Rounding+.PP+Amounts are stored internally as decimal numbers with up to 255 decimal+places, and displayed with the number of decimal places specified by the+commodity display style.+Note, hledger uses banker\[aq]s rounding: it rounds to the nearest even number, eg 0.5 displayed with zero decimal places is \[dq]0\[dq]).-(Note, prior to hledger 1.17.1 this could vary if hledger happened to be-built with an old version of Decimal (<0.5.1); since 1.17.1 it\[aq]s-guaranteed.)+(Guaranteed since hledger 1.17.1; in older versions this could vary if+hledger was built with Decimal < 0.5.1.) .SS Transaction prices .PP Within a transaction, you can note an amount\[aq]s price in another@@ -950,6 +969,8 @@ Directives\[aq] behaviour and interactions can get a little bit complex, so here is a table summarising the directives and their effects, with links to more detailed docs.+Note part of this table is hidden when viewed in a web browser - scroll+it sideways to see more. .PP .TS tab(@);@@ -984,8 +1005,7 @@ T}@T{ rewrite account names T}@T{-following inline/included entries until end of current file or end-directive+following entries until end of current file or end directive T} T{ \f[C]apply account\f[R]@@ -995,8 +1015,7 @@ T}@T{ prepend a common parent to account names T}@T{-following inline/included entries until end of current file or end-directive+following entries until end of current file or end directive T} T{ \f[C]comment\f[R]@@ -1006,8 +1025,7 @@ T}@T{ ignore part of journal T}@T{-following inline/included entries until end of current file or end-directive+following entries until end of current file or end directive T} T{ \f[C]commodity\f[R]@@ -1017,7 +1035,7 @@ T}@T{ declare a commodity and its number notation & display style T}@T{-number notation: following entries in that commodity in all files;+number notation: following entries in that commodity in all files ; display style: amounts of that commodity in reports T} T{@@ -1057,7 +1075,7 @@ T}@T{ declare a year for yearless dates T}@T{-following inline/included entries until end of current file+following entries until end of current file T} T{ \f[C]=\f[R]@@ -1199,7 +1217,7 @@ (Without this, hledger will parse both \f[C]1,000\f[R] and \f[C]1.000\f[R] as 1). .IP "3." 3-It declares the amount display style to use in output - decimal and+It declares a commodity\[aq]s display style in output - decimal and digit group marks, number of decimal places, symbol placement etc. .PP You are likely to run into one of the problems solved by commodity@@ -1245,7 +1263,14 @@ .PP Note hledger normally uses banker\[aq]s rounding, so 0.5 displayed with zero decimal digits is \[dq]0\[dq].-(More at Amount display style.)+(More at Commodity display style.)+.SS Commodity error checking+.PP+In strict mode, enabled with the \f[C]-s\f[R]/\f[C]--strict\f[R] flag,+hledger will report an error if a commodity symbol is used that has not+been declared by a \f[C]commodity\f[R] directive.+This works similarly to account error checking, see the notes there for+more details. .SS Default commodity .PP The \f[C]D\f[R] directive sets a default commodity, to be used for@@ -1314,15 +1339,13 @@ See Valuation. .SS Declaring accounts .PP-\f[C]account\f[R] directives can be used to pre-declare accounts.-Though not required, they can provide several benefits:+\f[C]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 extra information about accounts (account numbers, notes,-etc.)-.IP \[bu] 2 They can help hledger know your accounts\[aq] types (asset, liability, equity, revenue, expense), useful for reports like balancesheet and incomestatement.@@ -1330,17 +1353,54 @@ They control account display order in reports, allowing non-alphabetic sorting (eg Revenues to appear above Expenses). .IP \[bu] 2+They can store extra information about accounts (account numbers, notes,+etc.)+.IP \[bu] 2 They help with account name completion in the add command, hledger-iadd, hledger-web, ledger-mode etc.+.IP \[bu] 2+In strict mode, they restrict which accounts may be posted to by+transactions, which helps detect typos. .PP The simplest form is just the word \f[C]account\f[R] followed by a-hledger-style account name, eg:+hledger-style account name, eg this account directive declares the+\f[C]assets:bank:checking\f[R] account: .IP .nf \f[C] account assets:bank:checking \f[R] .fi+.SS Account error checking+.PP+By default, accounts come into existence when a transaction references+them by name.+This is convenient, but it means hledger can\[aq]t warn you when you+mis-spell an account name in the journal.+Usually you\[aq]ll find the error later, as an extra account in balance+reports, or an incorrect balance when reconciling.+.PP+In strict mode, enabled with the \f[C]-s\f[R]/\f[C]--strict\f[R] flag,+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+The account directive\[aq]s scope is \[dq]whole file and below\[dq] (see+directives).+This means it affects all of the current file, and any files it+includes, but not parent or sibling files.+The position of account directives within the file does not matter,+though it\[aq]s usual to put them at the top.+.IP \[bu] 2+Accounts can only be declared in \f[C]journal\f[R] files (but will+affect included files in other formats).+.IP \[bu] 2+It\[aq]s currently not possible to declare \[dq]all possible+subaccounts\[dq] with a wildcard; every account posted to must be+declared. .SS Account comments .PP Comments, beginning with a semicolon, can be added:@@ -1941,8 +2001,7 @@ (and also, a goal of depositing $2000 into checking) every month. Goals and actual performance can then be compared in budget reports. .PP-For more details, see: balance: Budget report and Budgeting and-Forecasting.+See also: Budgeting and Forecasting. .PP .SS Auto postings .PP
embeddedfiles/hledger_journal.info view
@@ -4,8 +4,8 @@ File: hledger_journal.info, Node: Top, Up: (dir) -hledger_journal(5) hledger 1.18.99-**********************************+hledger_journal(5) hledger 1.20+******************************* Journal - hledger's default file format, representing a General Journal @@ -487,10 +487,11 @@ * Menu: * Digit group marks::-* Amount display style::+* Commodity display style::+* Rounding:: -File: hledger_journal.info, Node: Digit group marks, Next: Amount display style, Up: Amounts+File: hledger_journal.info, Node: Digit group marks, Next: Commodity display style, Up: Amounts 1.8.1 Digit group marks -----------------------@@ -523,42 +524,64 @@ commodity 1 000 000.9455 -File: hledger_journal.info, Node: Amount display style, Prev: Digit group marks, Up: Amounts+File: hledger_journal.info, Node: Commodity display style, Next: Rounding, Prev: Digit group marks, Up: Amounts -1.8.2 Amount display style---------------------------+1.8.2 Commodity display style+----------------------------- -For each commodity, hledger chooses a consistent format to use when+For each commodity, hledger chooses a consistent style to use when displaying amounts. (Except price amounts, which are always displayed as written). The display style is chosen as follows: * If there is a commodity directive (or default commodity directive)- for the commodity, that format is used (see examples above).+ for the commodity, its style is used (see examples above). - * Otherwise the format of the first posting amount in that commodity- seen in the journal is used. But the number of decimal places- ("precision") will be the maximum from all posting amounts in that- commodity.+ * Otherwise the style is inferred from the amounts in that commodity+ seen in the journal. - * Or if there are no such amounts in the journal, a default format is+ * Or if there are no such amounts in the journal, a default style is used (like '$1000.00'). - Transaction prices don't affect the amount display style directly,-but occasionally they can do so indirectly (eg when an posting's amount-is inferred using a transaction price). If you find this causing-problems, use a commodity directive to fix the display style.+ A style is inferred from the journal amounts in a commodity as+follows: - In summary: amounts will be displayed much as they appear in your-journal, with the max observed number of decimal places. If you want to-see fewer decimal places in reports, use a commodity directive to-override that.+ * Use the general style (decimal mark, symbol placement) of the first+ amount+ * Use the first-seen digit group style (digit group mark, digit group+ sizes), if any+ * Use the maximum number of decimal places of all. - hledger uses banker's rounding: it rounds to the nearest even number,-eg 0.5 displayed with zero decimal places is "0"). (Note, prior to-hledger 1.17.1 this could vary if hledger happened to be built with an-old version of Decimal (<0.5.1); since 1.17.1 it's guaranteed.)+ Transaction price amounts don't affect the commodity display style+directly, but occasionally they can do so indirectly (eg when a+posting's amount is inferred using a transaction price). If you find+this causing problems, use a commodity directive to fix the display+style. + In summary, each commodity's amounts will be normalised to++ * the style declared by a 'commodity' directive+ * or, the style of the first posting amount in the journal, with the+ first-seen digit group style and the maximum-seen number of decimal+ places.++ If reports are showing amounts in a way you don't like (eg, with too+many decimal places), use a commodity directive to set your preferred+style.+ +File: hledger_journal.info, Node: Rounding, Prev: Commodity display style, Up: Amounts++1.8.3 Rounding+--------------++Amounts are stored internally as decimal numbers with up to 255 decimal+places, and displayed with the number of decimal places specified by the+commodity display style. Note, hledger uses banker's rounding: it+rounds to the nearest even number, eg 0.5 displayed with zero decimal+places is "0"). (Guaranteed since hledger 1.17.1; in older versions+this could vary if hledger was built with Decimal < 0.5.1.)++ File: hledger_journal.info, Node: Transaction prices, Next: Lot prices and lot dates, Prev: Amounts, Up: Transactions 1.9 Transaction prices@@ -888,7 +911,8 @@ Directives' behaviour and interactions can get a little bit complex, so here is a table summarising the directives and their effects, with-links to more detailed docs.+links to more detailed docs. Note part of this table is hidden when+viewed in a web browser - scroll it sideways to see more. directiveend subdirectivespurpose can affect (as of directive 2018/06)@@ -896,25 +920,22 @@ 'account' any document account names, all entries in text declare account types & all files, before display order or after-'alias' 'end rewrite account names following- aliases' inline/included- entries until end- of current file- or end directive-'apply 'end prepend a common parent to following-account' apply account names inline/included- account' entries until end- of current file- or end directive-'comment''end ignore part of journal following- comment' inline/included- entries until end- of current file- or end directive+'alias' 'end rewrite account names following entries+ aliases' until end of+ current file or+ end directive+'apply 'end prepend a common parent to following entries+account' apply account names until end of+ account' current file or+ end directive+'comment''end ignore part of journal following entries+ comment' until end of+ current file or+ end directive 'commodity' 'format'declare a commodity and its number notation: number notation & display following entries style in that commodity- in all files;+ in all files ; display style: amounts of that commodity in@@ -940,10 +961,9 @@ a commodity commodity in reports, when -V is used-'Y' declare a year for yearless following- dates inline/included- entries until end- of current file+'Y' declare a year for yearless following entries+ dates until end of+ current file '=' declare an auto posting all entries in rule, adding postings to parent/current/child other transactions files (but not@@ -1082,7 +1102,7 @@ formats in your data. (Without this, hledger will parse both '1,000' and '1.000' as 1). - 3. It declares the amount display style to use in output - decimal and+ 3. It declares a commodity's display style in output - decimal and digit group marks, number of decimal places, symbol placement etc. You are likely to run into one of the problems solved by commodity@@ -1117,9 +1137,24 @@ a comma, followed by 0 or more decimal digits. Note hledger normally uses banker's rounding, so 0.5 displayed with-zero decimal digits is "0". (More at Amount display style.)+zero decimal digits is "0". (More at Commodity display style.) +* Menu:++* Commodity error checking::+ +File: hledger_journal.info, Node: Commodity error checking, Up: Declaring commodities++1.13.5.1 Commodity error checking+.................................++In strict mode, enabled with the '-s'/'--strict' flag, hledger will+report an error if a commodity symbol is used that has not been declared+by a 'commodity' directive. This works similarly to account error+checking, see the notes there for more details.++ File: hledger_journal.info, Node: Default commodity, Next: Declaring market prices, Prev: Declaring commodities, Up: Directives 1.13.6 Default commodity@@ -1182,37 +1217,70 @@ 1.13.8 Declaring accounts ------------------------- -'account' directives can be used to pre-declare accounts. Though not-required, they can provide several benefits:+'account' 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: * They can document your intended chart of accounts, providing a reference.- * They can store extra information about accounts (account numbers,- notes, etc.) * They can help hledger know your accounts' types (asset, liability, equity, revenue, expense), useful for reports like balancesheet and incomestatement. * They control account display order in reports, allowing non-alphabetic sorting (eg Revenues to appear above Expenses).+ * They can store extra information about accounts (account numbers,+ notes, etc.) * They help with account name completion in the add command, hledger-iadd, hledger-web, ledger-mode etc.+ * In strict mode, they restrict which accounts may be posted to by+ transactions, which helps detect typos. The simplest form is just the word 'account' followed by a-hledger-style account name, eg:+hledger-style account name, eg this account directive declares the+'assets:bank:checking' account: account assets:bank:checking * Menu: +* Account error checking:: * Account comments:: * Account subdirectives:: * Account types:: * Account display order:: -File: hledger_journal.info, Node: Account comments, Next: Account subdirectives, Up: Declaring accounts+File: hledger_journal.info, Node: Account error checking, Next: Account comments, Up: Declaring accounts -1.13.8.1 Account comments+1.13.8.1 Account error checking+...............................++By default, accounts come into existence when a transaction references+them by name. This is convenient, but it means hledger can't warn you+when you mis-spell an account name in the journal. Usually you'll find+the error later, as an extra account in balance reports, or an incorrect+balance when reconciling.++ In strict mode, enabled with the '-s'/'--strict' flag, hledger will+report an error if any transaction uses an account name that has not+been declared by an account directive. Some notes:++ * The declaration is case-sensitive; transactions must use the+ correct account name capitalisation.+ * The account directive's scope is "whole file and below" (see+ directives). This means it affects all of the current file, and+ any files it includes, but not parent or sibling files. The+ position of account directives within the file does not matter,+ though it's usual to put them at the top.+ * Accounts can only be declared in 'journal' files (but will affect+ included files in other formats).+ * It's currently not possible to declare "all possible subaccounts"+ with a wildcard; every account posted to must be declared.+++File: hledger_journal.info, Node: Account comments, Next: Account subdirectives, Prev: Account error checking, Up: Declaring accounts++1.13.8.2 Account comments ......................... Comments, beginning with a semicolon, can be added:@@ -1232,7 +1300,7 @@ File: hledger_journal.info, Node: Account subdirectives, Next: Account types, Prev: Account comments, Up: Declaring accounts -1.13.8.2 Account subdirectives+1.13.8.3 Account subdirectives .............................. We also allow (and ignore) Ledger-style indented subdirectives, just for@@ -1250,7 +1318,7 @@ File: hledger_journal.info, Node: Account types, Next: Account display order, Prev: Account subdirectives, Up: Declaring accounts -1.13.8.3 Account types+1.13.8.4 Account types ...................... hledger recognises five main types of account, corresponding to the@@ -1329,7 +1397,7 @@ File: hledger_journal.info, Node: Account display order, Prev: Account types, Up: Declaring accounts -1.13.8.4 Account display order+1.13.8.5 Account display order .............................. Account directives also set the order in which accounts are displayed,@@ -1723,8 +1791,7 @@ checking) every month. Goals and actual performance can then be compared in budget reports. - For more details, see: balance: Budget report and Budgeting and-Forecasting.+ See also: Budgeting and Forecasting. File: hledger_journal.info, Node: Auto postings, Prev: Periodic transactions, Up: Transactions@@ -1865,124 +1932,130 @@ Tag Table: Node: Top76-Node: Transactions1875-Ref: #transactions1967-Node: Dates3251-Ref: #dates3350-Node: Simple dates3415-Ref: #simple-dates3541-Node: Secondary dates4050-Ref: #secondary-dates4204-Node: Posting dates5540-Ref: #posting-dates5669-Node: Status7041-Ref: #status7162-Node: Description8870-Ref: #description9004-Node: Payee and note9324-Ref: #payee-and-note9438-Node: Comments9773-Ref: #comments9899-Node: Tags11093-Ref: #tags11208-Node: Postings12601-Ref: #postings12729-Node: Virtual postings13755-Ref: #virtual-postings13872-Node: Account names15177-Ref: #account-names15318-Node: Amounts15805-Ref: #amounts15944-Node: Digit group marks17052-Ref: #digit-group-marks17200-Node: Amount display style18138-Ref: #amount-display-style18292-Node: Transaction prices19729-Ref: #transaction-prices19901-Node: Lot prices and lot dates22332-Ref: #lot-prices-and-lot-dates22529-Node: Balance assertions23017-Ref: #balance-assertions23203-Node: Assertions and ordering24236-Ref: #assertions-and-ordering24424-Node: Assertions and included files25124-Ref: #assertions-and-included-files25367-Node: Assertions and multiple -f options25700-Ref: #assertions-and-multiple--f-options25956-Node: Assertions and commodities26088-Ref: #assertions-and-commodities26320-Node: Assertions and prices27477-Ref: #assertions-and-prices27691-Node: Assertions and subaccounts28131-Ref: #assertions-and-subaccounts28360-Node: Assertions and virtual postings28684-Ref: #assertions-and-virtual-postings28926-Node: Assertions and precision29068-Ref: #assertions-and-precision29261-Node: Balance assignments29528-Ref: #balance-assignments29702-Node: Balance assignments and prices30866-Ref: #balance-assignments-and-prices31038-Node: Directives31262-Ref: #directives31421-Node: Directives and multiple files37112-Ref: #directives-and-multiple-files37295-Node: Comment blocks37959-Ref: #comment-blocks38142-Node: Including other files38318-Ref: #including-other-files38498-Node: Default year39422-Ref: #default-year39591-Node: Declaring commodities39998-Ref: #declaring-commodities40181-Node: Default commodity41987-Ref: #default-commodity42173-Node: Declaring market prices43062-Ref: #declaring-market-prices43257-Node: Declaring accounts44114-Ref: #declaring-accounts44300-Node: Account comments45225-Ref: #account-comments45388-Node: Account subdirectives45812-Ref: #account-subdirectives46007-Node: Account types46320-Ref: #account-types46504-Node: Account display order49550-Ref: #account-display-order49720-Node: Rewriting accounts50871-Ref: #rewriting-accounts51056-Node: Basic aliases51813-Ref: #basic-aliases51959-Node: Regex aliases52663-Ref: #regex-aliases52835-Node: Combining aliases53554-Ref: #combining-aliases53747-Node: Aliases and multiple files55023-Ref: #aliases-and-multiple-files55232-Node: end aliases55811-Ref: #end-aliases55968-Node: Default parent account56069-Ref: #default-parent-account56237-Node: Periodic transactions57121-Ref: #periodic-transactions57296-Node: Periodic rule syntax59168-Ref: #periodic-rule-syntax59374-Node: Two spaces between period expression and description!60078-Ref: #two-spaces-between-period-expression-and-description60397-Node: Forecasting with periodic transactions61081-Ref: #forecasting-with-periodic-transactions61386-Node: Budgeting with periodic transactions63441-Ref: #budgeting-with-periodic-transactions63680-Node: Auto postings64129-Ref: #auto-postings64269-Node: Auto postings and multiple files66448-Ref: #auto-postings-and-multiple-files66652-Node: Auto postings and dates66861-Ref: #auto-postings-and-dates67135-Node: Auto postings and transaction balancing / inferred amounts / balance assertions67310-Ref: #auto-postings-and-transaction-balancing-inferred-amounts-balance-assertions67661-Node: Auto posting tags68003-Ref: #auto-posting-tags68218+Node: Transactions1869+Ref: #transactions1961+Node: Dates3245+Ref: #dates3344+Node: Simple dates3409+Ref: #simple-dates3535+Node: Secondary dates4044+Ref: #secondary-dates4198+Node: Posting dates5534+Ref: #posting-dates5663+Node: Status7035+Ref: #status7156+Node: Description8864+Ref: #description8998+Node: Payee and note9318+Ref: #payee-and-note9432+Node: Comments9767+Ref: #comments9893+Node: Tags11087+Ref: #tags11202+Node: Postings12595+Ref: #postings12723+Node: Virtual postings13749+Ref: #virtual-postings13866+Node: Account names15171+Ref: #account-names15312+Node: Amounts15799+Ref: #amounts15938+Node: Digit group marks17062+Ref: #digit-group-marks17213+Node: Commodity display style18151+Ref: #commodity-display-style18331+Node: Rounding19874+Ref: #rounding19998+Node: Transaction prices20410+Ref: #transaction-prices20582+Node: Lot prices and lot dates23013+Ref: #lot-prices-and-lot-dates23210+Node: Balance assertions23698+Ref: #balance-assertions23884+Node: Assertions and ordering24917+Ref: #assertions-and-ordering25105+Node: Assertions and included files25805+Ref: #assertions-and-included-files26048+Node: Assertions and multiple -f options26381+Ref: #assertions-and-multiple--f-options26637+Node: Assertions and commodities26769+Ref: #assertions-and-commodities27001+Node: Assertions and prices28158+Ref: #assertions-and-prices28372+Node: Assertions and subaccounts28812+Ref: #assertions-and-subaccounts29041+Node: Assertions and virtual postings29365+Ref: #assertions-and-virtual-postings29607+Node: Assertions and precision29749+Ref: #assertions-and-precision29942+Node: Balance assignments30209+Ref: #balance-assignments30383+Node: Balance assignments and prices31547+Ref: #balance-assignments-and-prices31719+Node: Directives31943+Ref: #directives32102+Node: Directives and multiple files37600+Ref: #directives-and-multiple-files37783+Node: Comment blocks38447+Ref: #comment-blocks38630+Node: Including other files38806+Ref: #including-other-files38986+Node: Default year39910+Ref: #default-year40079+Node: Declaring commodities40486+Ref: #declaring-commodities40669+Node: Commodity error checking42513+Ref: #commodity-error-checking42673+Node: Default commodity42930+Ref: #default-commodity43116+Node: Declaring market prices44005+Ref: #declaring-market-prices44200+Node: Declaring accounts45057+Ref: #declaring-accounts45243+Node: Account error checking46445+Ref: #account-error-checking46621+Node: Account comments47800+Ref: #account-comments47994+Node: Account subdirectives48418+Ref: #account-subdirectives48613+Node: Account types48926+Ref: #account-types49110+Node: Account display order52156+Ref: #account-display-order52326+Node: Rewriting accounts53477+Ref: #rewriting-accounts53662+Node: Basic aliases54419+Ref: #basic-aliases54565+Node: Regex aliases55269+Ref: #regex-aliases55441+Node: Combining aliases56160+Ref: #combining-aliases56353+Node: Aliases and multiple files57629+Ref: #aliases-and-multiple-files57838+Node: end aliases58417+Ref: #end-aliases58574+Node: Default parent account58675+Ref: #default-parent-account58843+Node: Periodic transactions59727+Ref: #periodic-transactions59902+Node: Periodic rule syntax61774+Ref: #periodic-rule-syntax61980+Node: Two spaces between period expression and description!62684+Ref: #two-spaces-between-period-expression-and-description63003+Node: Forecasting with periodic transactions63687+Ref: #forecasting-with-periodic-transactions63992+Node: Budgeting with periodic transactions66047+Ref: #budgeting-with-periodic-transactions66286+Node: Auto postings66695+Ref: #auto-postings66835+Node: Auto postings and multiple files69014+Ref: #auto-postings-and-multiple-files69218+Node: Auto postings and dates69427+Ref: #auto-postings-and-dates69701+Node: Auto postings and transaction balancing / inferred amounts / balance assertions69876+Ref: #auto-postings-and-transaction-balancing-inferred-amounts-balance-assertions70227+Node: Auto posting tags70569+Ref: #auto-posting-tags70784 End Tag Table
embeddedfiles/hledger_journal.txt view
@@ -411,42 +411,60 @@ commodity INR 9,99,99,999.00 commodity 1 000 000.9455 - Amount display style- For each commodity, hledger chooses a consistent format to use when- displaying amounts. (Except price amounts, which are always displayed- as written). The display style is chosen as follows:+ Commodity display style+ For each commodity, hledger chooses a consistent style to use when dis-+ playing amounts. (Except price amounts, which are always displayed as+ written). The display style is chosen as follows: o If there is a commodity directive (or default commodity directive)- for the commodity, that format is used (see examples above).+ for the commodity, its style is used (see examples above). - o Otherwise the format of the first posting amount in that commodity- seen in the journal is used. But the number of decimal places ("pre-- cision") will be the maximum from all posting amounts in that commod-- ity.+ o Otherwise the style is inferred from the amounts in that commodity+ seen in the journal. - o Or if there are no such amounts in the journal, a default format is+ o Or if there are no such amounts in the journal, a default style is used (like $1000.00). - Transaction prices don't affect the amount display style directly, but- occasionally they can do so indirectly (eg when an posting's amount is- inferred using a transaction price). If you find this causing prob-- lems, use a commodity directive to fix the display style.+ A style is inferred from the journal amounts in a commodity as follows: - In summary: amounts will be displayed much as they appear in your jour-- nal, with the max observed number of decimal places. If you want to- see fewer decimal places in reports, use a commodity directive to over-- ride that.+ o Use the general style (decimal mark, symbol placement) of the first+ amount - hledger uses banker's rounding: it rounds to the nearest even number,- eg 0.5 displayed with zero decimal places is "0"). (Note, prior to- hledger 1.17.1 this could vary if hledger happened to be built with an- old version of Decimal (<0.5.1); since 1.17.1 it's guaranteed.)+ o Use the first-seen digit group style (digit group mark, digit group+ sizes), if any + o Use the maximum number of decimal places of all.++ Transaction price amounts don't affect the commodity display style di-+ rectly, but occasionally they can do so indirectly (eg when a posting's+ amount is inferred using a transaction price). If you find this caus-+ ing problems, use a commodity directive to fix the display style.++ In summary, each commodity's amounts will be normalised to++ o the style declared by a commodity directive++ o or, the style of the first posting amount in the journal, with the+ first-seen digit group style and the maximum-seen number of decimal+ places.++ If reports are showing amounts in a way you don't like (eg, with too+ many decimal places), use a commodity directive to set your preferred+ style.++ Rounding+ Amounts are stored internally as decimal numbers with up to 255 decimal+ places, and displayed with the number of decimal places specified by+ the commodity display style. Note, hledger uses banker's rounding: it+ rounds to the nearest even number, eg 0.5 displayed with zero decimal+ places is "0"). (Guaranteed since hledger 1.17.1; in older versions+ this could vary if hledger was built with Decimal < 0.5.1.)+ Transaction prices Within a transaction, you can note an amount's price in another commod-- ity. This can be used to document the cost (in a purchase) or selling- price (in a sale). For example, transaction prices are useful to- record purchases of a foreign currency. Note transaction prices are+ ity. This can be used to document the cost (in a purchase) or selling+ price (in a sale). For example, transaction prices are useful to+ record purchases of a foreign currency. Note transaction prices are fixed at the time of the transaction, and do not change over time. See also market prices, which represent prevailing exchange rates on a cer- tain date.@@ -472,14 +490,14 @@ assets:euros EUR100 ; one hundred euros purchased assets:dollars $-135 ; for $135 - 4. Like 1, but the @ is parenthesised, i.e. (@); this is for compati-- bility with Ledger journals (Virtual posting costs), and is equiva-+ 4. Like 1, but the @ is parenthesised, i.e. (@); this is for compati-+ bility with Ledger journals (Virtual posting costs), and is equiva- lent to 1 in hledger. 5. Like 2, but as in 4 the @@ is parenthesised, i.e. (@@); in hledger, this is equivalent to 2. - Use the -B/--cost flag to convert amounts to their transaction price's+ Use the -B/--cost flag to convert amounts to their transaction price's commodity, if any. (mnemonic: "B" is from "cost Basis", as in Ledger). Eg here is how -B affects the balance report for the example above: @@ -490,8 +508,8 @@ $-135 assets:dollars $135 assets:euros # <- the euros' cost - Note -B is sensitive to the order of postings when a transaction price- is inferred: the inferred price will be in the commodity of the last+ Note -B is sensitive to the order of postings when a transaction price+ is inferred: the inferred price will be in the commodity of the last amount. So if example 3's postings are reversed, while the transaction is equivalent, -B shows something different: @@ -504,18 +522,18 @@ EUR100 assets:euros Lot prices and lot dates- Ledger allows another kind of price, lot price (four variants: {UNIT-+ Ledger allows another kind of price, lot price (four variants: {UNIT- PRICE}, {{TOTALPRICE}}, {=FIXEDUNITPRICE}, {{=FIXEDTOTALPRICE}}), and/or a lot date ([DATE]) to be specified. These are normally used to- select a lot when selling investments. hledger will parse these, for- compatibility with Ledger journals, but currently ignores them. A- transaction price, lot price and/or lot date may appear in any order,+ select a lot when selling investments. hledger will parse these, for+ compatibility with Ledger journals, but currently ignores them. A+ transaction price, lot price and/or lot date may appear in any order, after the posting amount and before the balance assertion if any. Balance assertions- hledger supports Ledger-style balance assertions in journal files.- These look like, for example, = EXPECTEDBALANCE following a posting's- amount. Eg here we assert the expected dollar balance in accounts a+ hledger supports Ledger-style balance assertions in journal files.+ These look like, for example, = EXPECTEDBALANCE following a posting's+ amount. Eg here we assert the expected dollar balance in accounts a and b after each posting: 2013/1/1@@ -527,32 +545,32 @@ b $-1 =$-2 After reading a journal file, hledger will check all balance assertions- and report an error if any of them fail. Balance assertions can pro-- tect you from, eg, inadvertently disrupting reconciled balances while- cleaning up old entries. You can disable them temporarily with the+ and report an error if any of them fail. Balance assertions can pro-+ tect you from, eg, inadvertently disrupting reconciled balances while+ cleaning up old entries. You can disable them temporarily with the -I/--ignore-assertions flag, which can be useful for troubleshooting or- for reading Ledger files. (Note: this flag currently does not disable+ for reading Ledger files. (Note: this flag currently does not disable balance assignments, below). Assertions and ordering- hledger sorts an account's postings and assertions first by date and- then (for postings on the same day) by parse order. Note this is dif-+ hledger sorts an account's postings and assertions first by date and+ then (for postings on the same day) by parse order. Note this is dif- ferent from Ledger, which sorts assertions only by parse order. (Also,- Ledger assertions do not see the accumulated effect of repeated post-+ Ledger assertions do not see the accumulated effect of repeated post- ings to the same account within a transaction.) So, hledger balance assertions keep working if you reorder differently-- dated transactions within the journal. But if you reorder same-dated- transactions or postings, assertions might break and require updating.+ dated transactions within the journal. But if you reorder same-dated+ transactions or postings, assertions might break and require updating. This order dependence does bring an advantage: precise control over the order of postings and assertions within a day, so you can assert intra- day balances. Assertions and included files- With included files, things are a little more complicated. Including- preserves the ordering of postings and assertions. If you have multi-- ple postings to an account on the same day, split across different- files, and you also want to assert the account's balance on the same+ With included files, things are a little more complicated. Including+ preserves the ordering of postings and assertions. If you have multi-+ ple postings to an account on the same day, split across different+ files, and you also want to assert the account's balance on the same day, you'll have to put the assertion in the right file. Assertions and multiple -f options@@ -560,15 +578,15 @@ -f options. Use include or concatenate the files instead. Assertions and commodities- The asserted balance must be a simple single-commodity amount, and in- fact the assertion checks only this commodity's balance within the- (possibly multi-commodity) account balance. This is how assertions+ The asserted balance must be a simple single-commodity amount, and in+ fact the assertion checks only this commodity's balance within the+ (possibly multi-commodity) account balance. This is how assertions work in Ledger also. We could call this a "partial" balance assertion. To assert the balance of more than one commodity in an account, you can write multiple postings, each asserting one commodity's balance. - You can make a stronger "total" balance assertion by writing a double+ You can make a stronger "total" balance assertion by writing a double equals sign (== EXPECTEDBALANCE). This asserts that there are no other unasserted commodities in the account (or, that their balance is 0). @@ -588,7 +606,7 @@ a 0 == $1 It's not yet possible to make a complete assertion about a balance that- has multiple commodities. One workaround is to isolate each commodity+ has multiple commodities. One workaround is to isolate each commodity into its own subaccount: 2013/1/1@@ -602,21 +620,21 @@ a:euro 0 == 1EUR Assertions and prices- Balance assertions ignore transaction prices, and should normally be+ Balance assertions ignore transaction prices, and should normally be written without one: 2019/1/1 (a) $1 @ EUR1 = $1 - We do allow prices to be written there, however, and print shows them,- even though they don't affect whether the assertion passes or fails.- This is for backward compatibility (hledger's close command used to- generate balance assertions with prices), and because balance assign-+ We do allow prices to be written there, however, and print shows them,+ even though they don't affect whether the assertion passes or fails.+ This is for backward compatibility (hledger's close command used to+ generate balance assertions with prices), and because balance assign- ments do use them (see below). Assertions and subaccounts- The balance assertions above (= and ==) do not count the balance from- subaccounts; they check the account's exclusive balance only. You can+ The balance assertions above (= and ==) do not count the balance from+ subaccounts; they check the account's exclusive balance only. You can assert the balance including subaccounts by writing =* or ==*, eg: 2019/1/1@@ -630,16 +648,16 @@ tual. They are not affected by the --real/-R flag or real: query. 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 asser-+ 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 asser- tions. Balance assertion failure messages show exact amounts. 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+ 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: ; starting a new journal, set asset account balances@@ -657,14 +675,14 @@ expenses:misc The calculated amount depends on the account's 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 assign-+ at that point (which depends on the previously-dated postings of the+ commodity to that account since the last balance assertion or assign- ment). Note that using balance assignments makes your journal a little less explicit; to know the exact amount posted, you have to run hledger or do the calculations yourself, instead of just reading it. Balance assignments and prices- A transaction price in a balance assignment will cause the calculated+ A transaction price in a balance assignment will cause the calculated amount to have that price attached: 2019/1/1@@ -675,14 +693,15 @@ (a) $1 @ EUR2 = $1 @ EUR2 Directives- A directive is a line in the journal beginning with a special keyword,+ A directive is a line in the journal beginning with a special keyword, that influences how the journal is processed. hledger's directives are based on a subset of Ledger's, but there are many differences (and also some differences between hledger versions). Directives' behaviour and interactions can get a little bit complex, so- here is a table summarising the directives and their effects, with- links to more detailed docs.+ here is a table summarising the directives and their effects, with+ links to more detailed docs. Note part of this table is hidden when+ viewed in a web browser - scroll it sideways to see more. direc- end di- subdi- purpose can affect (as of tive rective rec- 2018/06)@@ -691,54 +710,48 @@ account any document account names, de- all entries in all text clare account types & dis- files, before or play order after- alias end rewrite account names following in-- aliases line/included en-- tries until end of- current file or end+ alias end rewrite account names following entries+ aliases until end of cur-+ rent file or end directive- apply end apply prepend a common parent to following in-- account account account names line/included en-- tries until end of- current file or end+ apply end apply prepend a common parent to following entries+ account account account names until end of cur-+ rent file or end directive- comment end com- ignore part of journal following in-- ment line/included en-- tries until end of- current file or end+ comment end com- ignore part of journal following entries+ ment until end of cur-+ rent file or end directive- commod- format declare a commodity and its number notation:+ commod- format declare a commodity and its number notation: ity number notation & display following entries style in that commodity- in all files; dis-+ in all files ; dis- play style: amounts of that commodity in reports- D declare a commodity to be default commodity:+++ D declare a commodity to be default commodity: used for commodityless following commod-- amounts, and its number no- ityless entries un-- tation & display style til end of current- file; number nota-+ amounts, and its number no- ityless entries un-+ tation & display style til end of current+ file; number nota- tion: following en-- tries in that com-+ tries in that com- modity until end of- current file; dis-+ current file; dis- play style: amounts of that commodity in reports include include entries/directives what the included from another file directives affect P declare a market price for a amounts of that- commodity commodity in re-- ports, when -V is+ commodity commodity in re-+ ports, when -V is used----- Y declare a year for yearless following in-- dates line/included en-- tries until end of- current file+ Y declare a year for yearless following entries+ dates until end of cur-+ rent file = declare an auto posting all entries in par- rule, adding postings to ent/current/child other transactions files (but not sib-@@ -842,7 +855,7 @@ formats in your data. (Without this, hledger will parse both 1,000 and 1.000 as 1). - 3. It declares the amount display style to use in output - decimal and+ 3. It declares a commodity's display style in output - decimal and digit group marks, number of decimal places, symbol placement etc. You are likely to run into one of the problems solved by commodity di-@@ -877,18 +890,24 @@ comma, followed by 0 or more decimal digits. Note hledger normally uses banker's rounding, so 0.5 displayed with- zero decimal digits is "0". (More at Amount display style.)+ zero decimal digits is "0". (More at Commodity display style.) + Commodity error checking+ In strict mode, enabled with the -s/--strict flag, hledger will report+ an error if a commodity symbol is used that has not been declared by a+ commodity directive. This works similarly to account error checking,+ see the notes there for more details.+ Default commodity- The D directive sets a default commodity, to be used for amounts with-+ The D directive sets a default commodity, to be used for amounts with- out a commodity symbol (ie, plain numbers). This commodity will be ap- plied to all subsequent commodity-less amounts, or until the next D di- rective. (Note, this is different from Ledger's D.) - For compatibility/historical reasons, D also acts like a commodity di-+ For compatibility/historical reasons, D also acts like a commodity di- rective, setting the commodity's display style (for output) and decimal mark (for parsing input). As with commodity, the amount must always be- written with a decimal mark (period or comma). If both directives are+ written with a decimal mark (period or comma). If both directives are used, commodity's style takes precedence. The syntax is D AMOUNT. Eg:@@ -902,9 +921,9 @@ b Declaring market prices- The P directive declares a market price, which is an exchange rate be-- tween two commodities on a certain date. (In Ledger, they are called- "historical prices".) These are often obtained from a stock exchange,+ The P directive declares a market price, which is an exchange rate be-+ tween two commodities on a certain date. (In Ledger, they are called+ "historical prices".) These are often obtained from a stock exchange, cryptocurrency exchange, or the foreign exchange market. Here is the format:@@ -915,47 +934,78 @@ o COMMODITYA is the symbol of the commodity being priced - o COMMODITYBAMOUNT is an amount (symbol and quantity) in a second com-+ o COMMODITYBAMOUNT is an amount (symbol and quantity) in a second com- modity, giving the price in commodity B of one unit of commodity A. - These two market price directives say that one euro was worth 1.35 US+ These two market price directives say that one euro was worth 1.35 US dollars during 2009, and $1.40 from 2010 onward: P 2009/1/1 EUR $1.35 P 2010/1/1 EUR $1.40 - The -V, -X and --value flags use these market prices to show amount+ The -V, -X and --value flags use these market prices to show amount values in another commodity. See Valuation. Declaring accounts- account directives can be used to pre-declare accounts. Though not re-- quired, they can provide several benefits:+ account directives can be used to declare accounts (ie, the places that+ amounts are transferred from and to). Though not required, these dec-+ larations can provide several benefits: o They can document your intended chart of accounts, providing a refer- ence. - o They can store extra information about accounts (account numbers,- notes, etc.)-- o They can help hledger know your accounts' types (asset, liability,- equity, revenue, expense), useful for reports like balancesheet and+ o They can help hledger know your accounts' types (asset, liability,+ equity, revenue, expense), useful for reports like balancesheet and incomestatement. - o They control account display order in reports, allowing non-alpha-+ o They control account display order in reports, allowing non-alpha- betic sorting (eg Revenues to appear above Expenses). + o They can store extra information about accounts (account numbers,+ notes, etc.)+ o They help with account name completion in the add command, hledger- iadd, hledger-web, ledger-mode etc. - The simplest form is just the word account followed by a hledger-style- account name, eg:+ o In strict mode, they restrict which accounts may be posted to by+ transactions, which helps detect typos. + The simplest form is just the word account followed by a hledger-style+ account name, eg this account directive declares the assets:bank:check-+ ing account:+ account assets:bank:checking + Account error checking+ By default, accounts come into existence when a transaction references+ them by name. This is convenient, but it means hledger can't warn you+ when you mis-spell an account name in the journal. Usually you'll find+ the error later, as an extra account in balance reports, or an incor-+ rect balance when reconciling.++ In strict mode, enabled with the -s/--strict flag, hledger will report+ an error if any transaction uses an account name that has not been de-+ clared by an account directive. Some notes:++ o The declaration is case-sensitive; transactions must use the correct+ account name capitalisation.++ o The account directive's scope is "whole file and below" (see direc-+ tives). This means it affects all of the current file, and any files+ it includes, but not parent or sibling files. The position of ac-+ count directives within the file does not matter, though it's usual+ to put them at the top.++ o Accounts can only be declared in journal files (but will affect in-+ cluded files in other formats).++ o It's currently not possible to declare "all possible subaccounts"+ with a wildcard; every account posted to must be declared.+ Account comments Comments, beginning with a semicolon, can be added: - o on the same line, after two or more spaces (because ; is allowed in+ o on the same line, after two or more spaces (because ; is allowed in account names) o on the next lines, indented@@ -969,7 +1019,7 @@ Same-line comments are not supported by Ledger, or hledger <1.13. Account subdirectives- We also allow (and ignore) Ledger-style indented subdirectives, just+ We also allow (and ignore) Ledger-style indented subdirectives, just for compatibility.: account assets:bank:checking@@ -988,21 +1038,21 @@ Asset, Liability, Equity, Revenue, Expense. These account types are important for controlling which accounts appear- in the balancesheet, balancesheetequity, incomestatement reports (and+ in the balancesheet, balancesheetequity, incomestatement reports (and probably for other things in future). - Additionally, we recognise the Cash type, which is also an Asset, and- which causes accounts to appear in the cashflow report. ("Cash" here- means liquid assets, eg bank balances but typically not investments or+ Additionally, we recognise the Cash type, which is also an Asset, and+ which causes accounts to appear in the cashflow report. ("Cash" here+ means liquid assets, eg bank balances but typically not investments or receivables.) Declaring account types Generally, to make these reports work you should declare your top-level accounts and their types, using account directives with type: tags. - The tag's value should be one of: Asset, Liability, Equity, Revenue,- Expense, Cash, A, L, E, R, X, C (all case insensitive). The type is- inherited by all subaccounts except where they override it. Here's a+ The tag's value should be one of: Asset, Liability, Equity, Revenue,+ Expense, Cash, A, L, E, R, X, C (all case insensitive). The type is+ inherited by all subaccounts except where they override it. Here's a complete example: account assets ; type: Asset@@ -1014,8 +1064,8 @@ account expenses ; type: Expense Auto-detected account types- If you happen to use common english top-level account names, you may- not need to declare account types, as they will be detected automati-+ If you happen to use common english top-level account names, you may+ not need to declare account types, as they will be detected automati- cally using the following rules: If name matches regular account type is:@@ -1025,10 +1075,11 @@ ^(debts?|lia- Liability bilit(y|ies))(:|$) ^equity(:|$) Equity+ ^(income|revenue)s?(:|$) Revenue ^expenses?(:|$) Expense - If account type is Asset and name does not contain regu- account type+ If account type is Asset and name does not contain regu- account type lar expression: is: -------------------------------------------------------------------------- (investment|receivable|:A/R|:fixed) Cash@@ -1038,9 +1089,9 @@ Interference from auto-detected account types If you assign any account type, it's a good idea to assign all of them,- to prevent any confusion from mixing declared and auto-detected types.- Although it's unlikely to happen in real life, here's an example: with- the following journal, balancesheetequity shows "liabilities" in both+ to prevent any confusion from mixing declared and auto-detected types.+ Although it's unlikely to happen in real life, here's an example: with+ the following journal, balancesheetequity shows "liabilities" in both Liabilities and Equity sections. Declaring another account as type:Li- ability would fix it: @@ -1052,8 +1103,8 @@ equity -2 Old account type syntax- In some hledger journals you might instead see this old syntax (the- letters ALERX, separated from the account name by two or more spaces);+ In some hledger journals you might instead see this old syntax (the+ letters ALERX, separated from the account name by two or more spaces); this is deprecated and may be removed soon: account assets A@@ -1063,8 +1114,8 @@ account expenses X Account display order- Account directives also set the order in which accounts are displayed,- eg in reports, the hledger-ui accounts screen, and the hledger-web+ Account directives also set the order in which accounts are displayed,+ eg in reports, the hledger-ui accounts screen, and the hledger-web sidebar. By default accounts are listed in alphabetical order. But if you have these account directives in the journal: @@ -1086,20 +1137,20 @@ Undeclared accounts, if any, are displayed last, in alphabetical order. - Note that sorting is done at each level of the account tree (within- each group of sibling accounts under the same parent). And currently,+ Note that sorting is done at each level of the account tree (within+ each group of sibling accounts under the same parent). And currently, this directive: account other:zoo - would influence the position of zoo among other's subaccounts, but not+ would influence the position of zoo among other's subaccounts, but not the position of other among the top-level accounts. This means: - o you will sometimes declare parent accounts (eg account other above)+ o you will sometimes declare parent accounts (eg account other above) that you don't intend to post to, just to customize their display or- der - o sibling accounts stay together (you couldn't display x:y in between+ o sibling accounts stay together (you couldn't display x:y in between a:b and a:c). Rewriting accounts@@ -1117,14 +1168,14 @@ o customising reports Account aliases also rewrite account names in account directives. They- do not affect account names being entered via hledger add or hledger-+ do not affect account names being entered via hledger add or hledger- web. See also Rewrite account names. Basic aliases- To set an account alias, use the alias directive in your journal file.- This affects all subsequent journal entries in the current file or its+ To set an account alias, use the alias directive in your journal file.+ This affects all subsequent journal entries in the current file or its included files. The spaces around the = are optional: alias OLD = NEW@@ -1132,49 +1183,49 @@ Or, you can use the --alias 'OLD=NEW' option on the command line. This affects all entries. It's useful for trying out aliases interactively. - OLD and NEW are case sensitive full account names. hledger will re-- place any occurrence of the old account name with the new one. Subac-+ OLD and NEW are case sensitive full account names. hledger will re-+ place any occurrence of the old account name with the new one. Subac- counts are also affected. Eg: alias checking = assets:bank:wells fargo:checking ; rewrites "checking" to "assets:bank:wells fargo:checking", or "checking:a" to "assets:bank:wells fargo:checking:a" Regex aliases- There is also a more powerful variant that uses a regular expression,+ There is also a more powerful variant that uses a regular expression, indicated by the forward slashes: alias /REGEX/ = REPLACEMENT or --alias '/REGEX/=REPLACEMENT'. - REGEX is a case-insensitive regular expression. Anywhere it matches- inside an account name, the matched part will be replaced by REPLACE-- MENT. If REGEX contains parenthesised match groups, these can be ref-+ REGEX is a case-insensitive regular expression. Anywhere it matches+ inside an account name, the matched part will be replaced by REPLACE-+ MENT. If REGEX contains parenthesised match groups, these can be ref- erenced by the usual numeric backreferences in REPLACEMENT. Eg: alias /^(.+):bank:([^:]+):(.*)/ = \1:\2 \3 ; rewrites "assets:bank:wells fargo:checking" to "assets:wells fargo checking" - Also note that REPLACEMENT continues to the end of line (or on command- line, to end of option argument), so it can contain trailing white-+ Also note that REPLACEMENT continues to the end of line (or on command+ line, to end of option argument), so it can contain trailing white- space. Combining aliases- You can define as many aliases as you like, using journal directives+ You can define as many aliases as you like, using journal directives and/or command line options. - Recursive aliases - where an account name is rewritten by one alias,- then by another alias, and so on - are allowed. Each alias sees the+ 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. - 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+ 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: - 1. alias directives preceding the journal entry, most recently parsed+ 1. alias directives preceding the journal entry, most recently parsed first (ie, reading upward from the journal entry, bottom to top) - 2. --alias options, in the order they appeared on the command line+ 2. --alias options, in the order they appeared on the command line (left to right). In other words, for (an account name in) a given journal entry:@@ -1185,20 +1236,20 @@ o aliases defined after/below the entry do not affect it. - This gives nearby aliases precedence over distant ones, and helps pro-- vide semantic stability - aliases will keep working the same way inde-+ This gives nearby aliases precedence over distant ones, and helps pro-+ vide semantic stability - aliases will keep working the same way inde- pendent of which files are being read and in which order. - In case of trouble, adding --debug=6 to the command line will show+ In case of trouble, adding --debug=6 to the command line will show which aliases are being applied when. Aliases and multiple files- As explained at Directives and multiple files, alias directives do not+ As explained at Directives and multiple files, alias directives do not affect parent or sibling files. Eg in this command, hledger -f a.aliases -f b.journal - account aliases defined in a.aliases will not affect b.journal. In-+ account aliases defined in a.aliases will not affect b.journal. In- cluding the aliases doesn't work either: include a.aliases@@ -1220,14 +1271,14 @@ include c.journal ; also affected end aliases- You can clear (forget) all currently defined aliases with the end+ You can clear (forget) all currently defined aliases with the end aliases directive: end aliases Default parent account- You can specify a parent account which will be prepended to all ac-- counts within a section of the journal. Use the apply account and end+ You can specify a parent account which will be prepended to all ac-+ counts within a section of the journal. Use the apply account and end apply account directives like so: apply account home@@ -1244,7 +1295,7 @@ home:food $10 home:cash $-10 - If end apply account is omitted, the effect lasts to the end of the+ If end apply account is omitted, the effect lasts to the end of the file. Included files are also affected, eg: apply account business@@ -1253,50 +1304,50 @@ apply account personal include personal.journal - Prior to hledger 1.0, legacy account and end spellings were also sup-+ Prior to hledger 1.0, legacy account and end spellings were also sup- ported. - A default parent account also affects account directives. It does not- affect account names being entered via hledger add or hledger-web. If- account aliases are present, they are applied after the default parent+ A default parent account also affects account directives. It does not+ affect account names being entered via hledger add or hledger-web. If+ account aliases are present, they are applied after the default parent account. Periodic transactions- Periodic transaction rules describe transactions that recur. They al-- low hledger to generate temporary future transactions to help with- forecasting, so you don't have to write out each one in the journal,- and it's easy to try out different forecasts. Secondly, they are also+ Periodic transaction rules describe transactions that recur. They al-+ low hledger to generate temporary future transactions to help with+ forecasting, so you don't have to write out each one in the journal,+ and it's easy to try out different forecasts. Secondly, they are also used to define the budgets shown in budget reports. - Periodic transactions can be a little tricky, so before you use them,+ Periodic transactions can be a little tricky, so before you use them, read this whole section - or at least these tips: - 1. Two spaces accidentally added or omitted will cause you trouble -+ 1. Two spaces accidentally added or omitted will cause you trouble - read about this below. - 2. For troubleshooting, show the generated transactions with hledger- print --forecast tag:generated or hledger register --forecast+ 2. For troubleshooting, show the generated transactions with hledger+ print --forecast tag:generated or hledger register --forecast tag:generated. - 3. Forecasted transactions will begin only after the last non-fore-+ 3. Forecasted transactions will begin only after the last non-fore- casted transaction's date. - 4. Forecasted transactions will end 6 months from today, by default.+ 4. Forecasted transactions will end 6 months from today, by default. See below for the exact start/end rules. - 5. period expressions can be tricky. Their documentation needs im-+ 5. period expressions can be tricky. Their documentation needs im- provement, but is worth studying. - 6. Some period expressions with a repeating interval must begin on a- natural boundary of that interval. Eg in weekly from DATE, DATE- must be a monday. ~ weekly from 2019/10/1 (a tuesday) will give an+ 6. Some period expressions with a repeating interval must begin on a+ natural boundary of that interval. Eg in weekly from DATE, DATE+ must be a monday. ~ weekly from 2019/10/1 (a tuesday) will give an error. 7. Other period expressions with an interval are automatically expanded- to cover a whole number of that interval. (This is done to improve+ to cover a whole number of that interval. (This is done to improve reports, but it also affects periodic transactions. Yes, it's a bit- inconsistent with the above.) Eg: ~ every 10th day of month from- 2020/01, which is equivalent to ~ every 10th day of month from+ inconsistent with the above.) Eg: ~ every 10th day of month from+ 2020/01, which is equivalent to ~ every 10th day of month from 2020/01/01, will be adjusted to start on 2019/12/10. Periodic rule syntax@@ -1308,17 +1359,17 @@ expenses:rent $2000 assets:bank:checking - There is an additional constraint on the period expression: the start- date must fall on a natural boundary of the interval. Eg monthly from+ There is an additional constraint on the period expression: the start+ date must fall on a natural boundary of the interval. Eg monthly from 2018/1/1 is valid, but monthly from 2018/1/15 is not. - Partial or relative dates (M/D, D, tomorrow, last week) in the period- expression can work (useful or not). They will be relative to today's- date, unless a Y default year directive is in effect, in which case+ Partial or relative dates (M/D, D, tomorrow, last week) in the period+ expression can work (useful or not). They will be relative to today's+ date, unless a Y default year directive is in effect, in which case they will be relative to Y/1/1. Two spaces between period expression and description!- If the period expression is followed by a transaction description,+ If the period expression is followed by a transaction description, these must be separated by two or more spaces. This helps hledger know where the period expression ends, so that descriptions can not acciden- tally alter their meaning, as in this example:@@ -1332,64 +1383,63 @@ So, - o Do write two spaces between your period expression and your transac-+ o Do write two spaces between your period expression and your transac- tion description, if any. - o Don't accidentally write two spaces in the middle of your period ex-+ o Don't accidentally write two spaces in the middle of your period ex- pression. Forecasting with periodic transactions- The --forecast flag activates any periodic transaction rules in the- journal. They will generate temporary recurring transactions, which- are not saved in the journal, but will appear in all reports (eg+ The --forecast flag activates any periodic transaction rules in the+ journal. They will generate temporary recurring transactions, which+ are not saved in the journal, but will appear in all reports (eg print). This can be useful for estimating balances into the future, or- experimenting with different scenarios. Or, it can be used as a data+ experimenting with different scenarios. Or, it can be used as a data entry aid: describe recurring transactions, and every so often copy the output of print --forecast into the journal. - These transactions will have an extra tag indicating which periodic+ These transactions will have an extra tag indicating which periodic rule generated them: generated-transaction:~ PERIODICEXPR. And a simi-- lar, hidden tag (beginning with an underscore) which, because it's- never displayed by print, can be used to match transactions generated+ lar, hidden tag (beginning with an underscore) which, because it's+ never displayed by print, can be used to match transactions generated "just now": _generated-transaction:~ PERIODICEXPR. - Periodic transactions are generated within some forecast period. By+ Periodic transactions are generated within some forecast period. By default, this o begins on the later of o the report start date if specified with -b/-p/date: - o the day after the latest normal (non-periodic) transaction in the+ o the day after the latest normal (non-periodic) transaction in the journal, or today if there are no normal transactions. - o ends on the report end date if specified with -e/-p/date:, or 6+ o ends on the report end date if specified with -e/-p/date:, or 6 months (180 days) from today. - This means that periodic transactions will begin only after the latest- recorded transaction. And a recorded transaction dated in the future- can prevent generation of periodic transactions. (You can avoid that+ This means that periodic transactions will begin only after the latest+ recorded transaction. And a recorded transaction dated in the future+ can prevent generation of periodic transactions. (You can avoid that by writing the future transaction as a one-time periodic rule instead - put tilde before the date, eg ~ YYYY-MM-DD ...). Or, you can set your own arbitrary "forecast period", which can overlap- recorded transactions, and need not be in the future, by providing an- option argument, like --forecast=PERIODEXPR. Note the equals sign is+ recorded transactions, and need not be in the future, by providing an+ option argument, like --forecast=PERIODEXPR. Note the equals sign is required, a space won't work. PERIODEXPR is a period expression, which- can specify the start date, end date, or both, like in a date: query.- (See also hledger.1 -> Report start & end date). Some examples:+ can specify the start date, end date, or both, like in a date: query.+ (See also hledger.1 -> Report start & end date). Some examples: --forecast=202001-202004, --forecast=jan-, --forecast=2020. Budgeting with periodic transactions- With the --budget flag, currently supported by the balance command,- each periodic transaction rule declares recurring budget goals for the- specified accounts. Eg the first example above declares a goal of- spending $2000 on rent (and also, a goal of depositing $2000 into- checking) every month. Goals and actual performance can then be com-+ With the --budget flag, currently supported by the balance command,+ each periodic transaction rule declares recurring budget goals for the+ specified accounts. Eg the first example above declares a goal of+ spending $2000 on rent (and also, a goal of depositing $2000 into+ checking) every month. Goals and actual performance can then be com- pared in budget reports. - For more details, see: balance: Budget report and Budgeting and Fore-- casting.+ See also: Budgeting and Forecasting. Auto postings "Automated postings" or "auto postings" are extra postings which get@@ -1526,4 +1576,4 @@ -hledger 1.18.99 September 2020 hledger_journal(5)+hledger 1.20 November 2020 hledger_journal(5)
embeddedfiles/hledger_timeclock.5 view
@@ -1,5 +1,5 @@ -.TH "hledger_timeclock" "5" "September 2020" "hledger 1.18.99" "hledger User Manuals"+.TH "hledger_timeclock" "5" "November 2020" "hledger 1.20" "hledger User Manuals"
embeddedfiles/hledger_timeclock.info view
@@ -4,8 +4,8 @@ File: hledger_timeclock.info, Node: Top, Up: (dir) -hledger_timeclock(5) hledger 1.18.99-************************************+hledger_timeclock(5) hledger 1.20+********************************* Timeclock - the time logging format of timeclock.el, as read by hledger
embeddedfiles/hledger_timeclock.txt view
@@ -78,4 +78,4 @@ -hledger 1.18.99 September 2020 hledger_timeclock(5)+hledger 1.20 November 2020 hledger_timeclock(5)
embeddedfiles/hledger_timedot.5 view
@@ -1,5 +1,5 @@ -.TH "hledger_timedot" "5" "September 2020" "hledger 1.18.99" "hledger User Manuals"+.TH "hledger_timedot" "5" "November 2020" "hledger 1.20" "hledger User Manuals" @@ -168,7 +168,7 @@ .IP .nf \f[C]-$ hledger -f t.timedot --alias /\[rs]\[rs]./=: bal date:2016/2/4+$ hledger -f t.timedot --alias /\[rs]\[rs]./=: bal date:2016/2/4 --tree 4.50 fos 4.00 hledger:timedot 0.50 ledger
embeddedfiles/hledger_timedot.info view
@@ -4,8 +4,8 @@ File: hledger_timedot.info, Node: Top, Up: (dir) -hledger_timedot(5) hledger 1.18.99-**********************************+hledger_timedot(5) hledger 1.20+******************************* Timedot - hledger's human-friendly time logging format @@ -129,7 +129,7 @@ fos.hledger.timedot 4 fos.ledger .. -$ hledger -f t.timedot --alias /\\./=: bal date:2016/2/4+$ hledger -f t.timedot --alias /\\./=: bal date:2016/2/4 --tree 4.50 fos 4.00 hledger:timedot 0.50 ledger
embeddedfiles/hledger_timedot.txt view
@@ -127,7 +127,7 @@ fos.hledger.timedot 4 fos.ledger .. - $ hledger -f t.timedot --alias /\\./=: bal date:2016/2/4+ $ hledger -f t.timedot --alias /\\./=: bal date:2016/2/4 --tree 4.50 fos 4.00 hledger:timedot 0.50 ledger@@ -161,4 +161,4 @@ -hledger 1.18.99 September 2020 hledger_timedot(5)+hledger 1.20 November 2020 hledger_timedot(5)
hledger.1 view
@@ -1,6 +1,6 @@ .\"t -.TH "hledger" "1" "September 2020" "hledger 1.18.99" "hledger User Manuals"+.TH "hledger" "1" "November 2020" "hledger 1.20" "hledger User Manuals" @@ -566,6 +566,9 @@ \f[B]\f[CB]-I --ignore-assertions\f[B]\f[R] disable balance assertion checks (note: does not disable balance assignments)+.TP+\f[B]\f[CB]-s --strict\f[B]\f[R]+do extra error checking (check that all posted accounts are declared) .PP General reporting options: .TP@@ -1060,6 +1063,31 @@ .IP \[bu] 2 or concatenate the files into one before reading, eg: \f[C]cat a.journal b.journal | hledger -f- CMD\f[R].+.SS Strict mode+.PP+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[C]-s\f[R]/\f[C]--strict\f[R] flag, additional checks are+performed:+.IP \[bu] 2+Are all accounts posted to, declared with an \f[C]account\f[R] directive+?+(Account error checking)+.IP \[bu] 2+Are all commodities declared with a \f[C]commodity\f[R] directive ?+(Commodity error checking)+.PP+See also: https://hledger.org/checking-for-errors.html+.PP+\f[I]experimental.\f[R] .SS Output destination .PP hledger commands send their output to the terminal by default.@@ -1588,10 +1616,12 @@ If you want intervals that start on arbitrary day of your choosing and span a week, month or year, you need to use any of the following: .PP-\f[C]every Nth day of week\f[R], \f[C]every <weekday>\f[R],+\f[C]every Nth day of week\f[R], \f[C]every WEEKDAYNAME\f[R] (eg+\f[C]mon|tue|wed|thu|fri|sat|sun\f[R]), \f[C]every Nth day [of month]\f[R],-\f[C]every Nth weekday [of month]\f[R], \f[C]every MM/DD [of year]\f[R],-\f[C]every Nth MMM [of year]\f[R], \f[C]every MMM Nth [of year]\f[R].+\f[C]every Nth WEEKDAYNAME [of month]\f[R],+\f[C]every MM/DD [of year]\f[R], \f[C]every Nth MMM [of year]\f[R],+\f[C]every MMM Nth [of year]\f[R]. .PP Examples: .PP@@ -1761,7 +1791,7 @@ \[dq]today\[dq]. .PP For multiperiod reports, each column/period is valued on the last day of-the period.+the period, by default. .SS Market prices .PP \f[I](experimental)\f[R]@@ -1772,15 +1802,19 @@ .IP "1." 3 A \f[I]declared market price\f[R] or \f[I]inferred market price\f[R]: A\[aq]s latest market price in B on or before the valuation date as-declared by a P directive, or (if the \f[C]--infer-value\f[R] flag is-used) inferred from transaction prices.+declared by a P directive, or (with the \f[C]--infer-value\f[R] flag)+inferred from transaction prices. .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]chained market price\f[R]: a synthetic price formed by combining-the shortest chain of market prices (any of the above types) leading-from A to B.+A \f[I]a forward chain of market prices\f[R]: a synthetic price formed+by combining the shortest chain of \[dq]forward\[dq] (only 1 above)+market prices, leading from A to B.+.IP "4." 3+A \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. .PP Amounts for which no applicable market price can be found, are not converted.@@ -2113,7 +2147,7 @@ .PP .TS tab(@);-lw(11.7n) lw(11.2n) lw(11.9n) lw(13.1n) lw(12.4n) lw(9.8n).+lw(10.6n) lw(13.2n) lw(13.4n) lw(11.0n) lw(13.4n) lw(8.2n). T{ Report type T}@T{@@ -2150,7 +2184,7 @@ value at DATE/today T} T{-balance assertions / assignments+balance assertions/assignments T}@T{ unchanged T}@T{@@ -2178,7 +2212,7 @@ T}@T{ T} T{-starting balance (with -H)+starting balance (-H) T}@T{ cost T}@T{@@ -2191,7 +2225,7 @@ value at DATE/today T} T{-posting amounts (no report interval)+posting amounts T}@T{ cost T}@T{@@ -2204,7 +2238,7 @@ value at DATE/today T} T{-summary posting amounts (with report interval)+summary posting amounts with report interval T}@T{ summarised cost T}@T{@@ -2237,7 +2271,7 @@ T}@T{ T} T{-\f[B]balance (bs, bse, cf, is..)\f[R]+\f[B]balance (bs, bse, cf, is)\f[R] T}@T{ T}@T{ T}@T{@@ -2245,7 +2279,7 @@ T}@T{ T} T{-balances (no report interval)+balance changes T}@T{ sums of costs T}@T{@@ -2258,71 +2292,112 @@ value at DATE/today of sums of postings T} T{-balances (with report interval)+budget amounts (--budget) T}@T{-sums of costs+like balance changes T}@T{-value at period ends of sums of postings+like balance changes T}@T{ not supported T}@T{-value at period ends of sums of postings+like balances T}@T{-value at DATE/today of sums of postings+like balance changes T} T{-starting balances (with report interval and -H)+grand total T}@T{+sum of displayed values+T}@T{+sum of displayed values+T}@T{+not supported+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{-sums of postings before report start+value at report start of sums of all postings before report start T}@T{ not supported T}@T{-sums of postings before report start+value at report start of sums of all postings before report start T}@T{ sums of postings before report start T} T{-budget amounts with --budget+balance changes (bal, is, bs --change, cf --change) T}@T{-like balances+sums of costs of postings in period T}@T{-like balances+same as --value=end T}@T{ not supported T}@T{-like balances+balance change in each period, valued at period ends T}@T{-like balances+value at DATE/today of sums of postings T} T{-grand total (no report interval)+end balances (bal -H, is --H, bs, cf) T}@T{-sum of displayed values+sums of costs of postings from before report start to period end T}@T{-sum of displayed values+same as --value=end T}@T{ not supported T}@T{-sum of displayed values+period end balances, valued at period ends T}@T{-sum of displayed values+value at DATE/today of sums of postings T} T{-row totals/averages (with report interval)+budget amounts (--budget) T}@T{-sums/averages of displayed values+like balance changes/end balances T}@T{-sums/averages of displayed values+like balance changes/end balances T}@T{ not supported T}@T{-sums/averages of displayed values+like balances T}@T{-sums/averages of displayed values+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{+not supported+T}@T{+sums, averages of displayed values+T}@T{+sums, averages of displayed values+T}+T{ column totals T}@T{ sums of displayed values@@ -2336,17 +2411,17 @@ sums of displayed values T} T{-grand total/average+grand total, grand average T}@T{-sum/average of column totals+sum, average of column totals T}@T{-sum/average of column totals+sum, average of column totals T}@T{ not supported T}@T{-sum/average of column totals+sum, average of column totals T}@T{-sum/average of column totals+sum, average of column totals T} T{ T}@T{@@ -2357,6 +2432,9 @@ T} .TE .PP+\f[C]--cumulative\f[R] is omitted to save space, it works like+\f[C]-H\f[R] but with a zero starting balance.+.PP \f[B]Glossary:\f[R] .TP \f[I]cost\f[R]@@ -2680,11 +2758,8 @@ .fi .PP By default, accounts are displayed hierarchically, with subaccounts-indented below their parent.-At each level of the tree, accounts are sorted by account code if any,-then by account name.-Or with \f[C]-S/--sort-amount\f[R], by their balance amount, largest-first.+indented below their parent, with accounts at each level of the tree+sorted by declaration order if declared, then by account name. .PP \[dq]Boring\[dq] accounts, which contain a single interesting subaccount and no balance of their own, are elided into the following line for more@@ -2856,6 +2931,19 @@ If there are mixed commodity accounts in the report be sure to use \f[C]-V\f[R] or \f[C]-B\f[R] to coerce the report into using a single commodity.+.SS Sorting by amount+.PP+With \f[C]-S\f[R]/\f[C]--sort-amount\f[R], accounts with the largest+(most positive) balances are shown first.+For example, \f[C]hledger bal expenses -MAS\f[R] shows your biggest+averaged monthly expenses first.+.PP+Revenues and liability balances are typically negative, however, so+\f[C]-S\f[R] shows these in reverse order.+To work around this, you can add \f[C]--invert\f[R] to flip the signs.+Or, use one of the sign-flipping reports like \f[C]balancesheet\f[R] or+\f[C]incomestatement\f[R], which also support \f[C]-S\f[R].+Eg: \f[C]hledger is -MAS\f[R]. .SS Multicolumn balance report .PP Multicolumn or tabular balance reports are a very useful hledger@@ -3133,7 +3221,60 @@ \f[R] .fi .PP-For more examples, see Budgeting and Forecasting.+For more examples and notes, see Budgeting.+.SS Budget report start date+.PP+This might be a bug, but for now: when making budget reports, it\[aq]s a+good idea to explicitly set the report\[aq]s start date to the first day+of a reporting period, because a periodic rule like+\f[C]\[ti] monthly\f[R] generates its transactions on the 1st of each+month, and if your journal has no regular transactions on the 1st, the+default report start date could exclude that budget goal, which can be a+little surprising.+Eg here the default report period is just the day of 2020-01-15:+.IP+.nf+\f[C]+\[ti] monthly in 2020+ (expenses:food) $500++2020-01-15+ expenses:food $400+ assets:checking+\f[R]+.fi+.IP+.nf+\f[C]+$ hledger bal expenses --budget+Budget performance in 2020-01-15:++ || 2020-01-15 +==============++============+ <unbudgeted> || $400 +--------------++------------+ || $400 +\f[R]+.fi+.PP+To avoid this, specify the budget report\[aq]s period, or at least the+start date, with \f[C]-b\f[R]/\f[C]-e\f[R]/\f[C]-p\f[R]/\f[C]date:\f[R],+to ensure it includes the budget goal transactions (periodic+transactions) that you want.+Eg, adding \f[C]-b 2020/1/1\f[R] to the above:+.IP+.nf+\f[C]+$ hledger bal expenses --budget -b 2020/1/1+Budget performance in 2020-01-01..2020-01-15:++ || 2020-01-01..2020-01-15 +===============++========================+ expenses:food || $400 [80% of $500] +---------------++------------------------+ || $400 [80% of $500] +\f[R]+.fi .SS Nested budgets .PP You can add budgets to any account in your account hierarchy.@@ -3239,9 +3380,8 @@ .SS Output format .PP This command also supports the output destination and output format-options The output formats supported are \f[C]txt\f[R], \f[C]csv\f[R],-(multicolumn non-budget reports only) \f[C]html\f[R], and (experimental)-\f[C]json\f[R].+options The output formats supported are (in most modes): \f[C]txt\f[R],+\f[C]csv\f[R], \f[C]html\f[R], and \f[C]json\f[R]. .SS balancesheet .PP balancesheet, bs@@ -3396,28 +3536,79 @@ This command also supports the output destination and output format options The output formats supported are \f[C]txt\f[R], \f[C]csv\f[R], \f[C]html\f[R], and (experimental) \f[C]json\f[R].-.SS check-dates+.SS check .PP-check-dates+check .PD 0 .P .PD-Check that transactions are sorted by increasing date.-With --date2, checks secondary dates instead.-With --strict, dates must also be unique.-With a query, only matched transactions\[aq] dates are checked.-Reads the default journal file, or another specified with -f.-.SS check-dupes+Check for various kinds of errors in your data.+\f[I]experimental\f[R] .PP-check-dupes-.PD 0-.P-.PD-Reports account names having the same leaf but different prefixes.-In other words, two or more leaves that are categorized differently.-Reads the default journal file, or another specified as an argument.+hledger provides a number of built-in error checks to help prevent+problems in your data.+Some of these are run automatically; or, you can use this+\f[C]check\f[R] command to run them on demand, with no output and a zero+exit code if all is well.+Some examples:+.IP+.nf+\f[C]+hledger check # basic checks+hledger check -s # basic + strict checks+hledger check ordereddates uniqueleafnames # basic + specified checks+\f[R]+.fi .PP-An example: http://stefanorodighiero.net/software/hledger-dupes.html+Here are the checks currently available:+.SS Basic checks+.PP+These are always run by this command and other commands:+.IP \[bu] 2+\f[B]parseable\f[R] - data files are well-formed and can be successfully+parsed+.IP \[bu] 2+\f[B]autobalanced\f[R] - all transactions are balanced, inferring+missing amounts where necessary, and possibly converting commodities+using transaction prices or automatically-inferred transaction prices+.IP \[bu] 2+\f[B]assertions\f[R] - all balance assertions in the journal are+passing.+(This check can be disabled with+\f[C]-I\f[R]/\f[C]--ignore-assertions\f[R].)+.SS Strict checks+.PP+These are always run by this and other commands when+\f[C]-s\f[R]/\f[C]--strict\f[R] is used (strict mode):+.IP \[bu] 2+\f[B]accounts\f[R] - all account names used by transactions have been+declared+.IP \[bu] 2+\f[B]commodities\f[R] - all commodity symbols used have been declared+.SS Other checks+.PP+These checks can be run by specifying their names as arguments to the+check command:+.IP \[bu] 2+\f[B]ordereddates\f[R] - transactions are ordered by date (similar to+the old \f[C]check-dates\f[R] command)+.IP \[bu] 2+\f[B]uniqueleafnames\f[R] - all account leaf names are unique (similar+to the old \f[C]check-dupes\f[R] command)+.SS Addon checks+.PP+Some checks are not yet integrated with this command, but are available+as add-on commands in+https://github.com/simonmichael/hledger/tree/master/bin:+.IP \[bu] 2+\f[B]hledger-check-tagfiles\f[R] - all tag values containing / (a+forward slash) exist as file paths+.IP \[bu] 2+\f[B]hledger-check-fancyassertions\f[R] - more complex balance+assertions are passing+.PP+You could make your own similar scripts to perform custom checks;+Cookbook -> Scripting may be helpful. .SS close .PP close, equity@@ -3773,6 +3964,10 @@ .PP (If you think import should leave amounts implicit like print does, please test it and send a pull request.)+.SS Commodity display styles+.PP+Imported amounts will be formatted according to the canonical commodity+styles (declared or inferred) in the main journal file. .SS incomestatement .PP incomestatement, is@@ -4410,11 +4605,295 @@ name) to select your investments with \f[C]--inv\f[R], and another query to identify your profit and loss transactions with \f[C]--pnl\f[R]. .PP-It will compute and display the internalized rate of return (IRR) and-time-weighted rate of return (TWR) for your investments for the time-period requested.+This command will compute and display the internalized rate of return+(IRR) and time-weighted rate of return (TWR) for your investments for+the time period requested. Both rates of return are annualized before display, regardless of the length of reporting interval.+.PP+Note, in some cases this report can fail, for these reasons:+.IP \[bu] 2+Error (NotBracketed): 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+Error (SearchFailed): Failed to find solution for Internal Rate of+Return (IRR).+Either search does not converge to a solution, or converges too slowly.+.PP+Examples:+.IP \[bu] 2+Using roi to report unrealised gains:+https://github.com/simonmichael/hledger/blob/master/examples/roi-unrealised.ledger+.PP+More background:+.PP+\[dq]ROI\[dq] stands for \[dq]return 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+investments receives no in-flows or out-flows of money, and where 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+Internal rate of return, or \[dq]IRR\[dq] (also called+\[dq]money-weighted rate of return\[dq]) takes into account effects of+in-flows and out-flows.+Naively, if you are withdrawing from your investment, your future gains+would be smaller (in absolute numbers), and will be a smaller percentage+of your initial investment, and if you are adding to your investment,+you will receive bigger absolute gains (but probably at the same rate of+return).+IRR is a way to compute rate of return for each period between in-flow+or out-flow of money, and then combine them in a way that gives you an+annual rate of return that investment is expected to generate.+.PP+As mentioned before, in-flows and out-flows would be any cash that you+personally put in or withdraw, and for the \[dq]roi\[dq] command, these+are transactions that involve account(s) matching \f[C]--inv\f[R]+argument and NOT involve account(s) matching \f[C]--pnl\f[R] argument.+.PP+Presumably, you will also record changes in the value of your+investment, and balance them against \[dq]profit and loss\[dq] (or+\[dq]unrealized gains\[dq]) account.+Note that in order for IRR to compute the precise effect of your+in-flows and out-flows on the rate of return, you will need to record+the value of your investement on or close to the days when in- or+out-flows occur.+.PP+Implementation of IRR in hledger should match the \f[C]XIRR\f[R] formula+in Excel.+.PP+Second way to compute rate of return that \f[C]roi\f[R] command+implements is called \[dq]time-weighted rate of return\[dq] or+\[dq]TWR\[dq].+Like IRR, it will also break the history of your investment into periods+between in-flows and out-flows to compute rate of return per each period+and then a compound rate of return.+However, internal workings of TWR are quite different.+.PP+In technical terms, IRR uses the same approach as computation of net+present value, and tries to find a discount rate that makes net present+value of all the cash flows of your investment to add up to zero.+This could be hard to wrap your head around, especially if you+haven\[aq]t done discounted cash flow analysis before.+.PP+TWR represents your investment as an imaginary \[dq]unit fund\[dq] where+in-flows/ out-flows lead to buying or selling \[dq]units\[dq] of your+investment and changes in its value change the value of \[dq]investment+unit\[dq].+Change in \[dq]unit price\[dq] over the reporting period gives you rate+of return of your investment.+.PP+References: * Explanation of rate of return * Explanation of IRR *+Explanation of TWR * Examples of computing IRR and TWR and discussion of+the limitations of both metrics+.PP+More examples:+.PP+Lets say that we found an investment in Snake Oil that is proising to+give us 10% annually:+.IP+.nf+\f[C]+2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-12-24 Recording the growth of Snake Oil+ investment:snake oil = $110+ equity:unrealized gains+\f[R]+.fi+.PP+For now, basic computation of the rate of return, as well as IRR and+TWR, gives us the expected 10%:+.IP+.nf+\f[C]+$ hledger roi -Y --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+-----++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 110 | 10 || 10.00% | 10.00% |++---++------------+------------++---------------+----------+-------------+-----++--------+--------++\f[R]+.fi+.PP+However, lets say that shorty after investing in the Snake Oil we+started to have second thoughs, so we prompty withdrew $90, leaving only+$10 in.+Before Christmas, though, we started to get the \[dq]fear of mission+out\[dq], so we put the $90 back in.+So for most of the year, our investment was just $10 dollars, and it+gave us just $1 in growth:+.IP+.nf+\f[C]+2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil+ +2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil = $101+ equity:unrealized gains+\f[R]+.fi+.PP+Now IRR and TWR are drastically different:+.IP+.nf+\f[C]+$ hledger roi -Y --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+-----++-------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++=======+=======++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101 | 1 || 9.32% | 1.00% |++---++------------+------------++---------------+----------+-------------+-----++-------+-------++\f[R]+.fi+.PP+Here, IRR tells us that we made close to 10% on the $10 dollars that we+had in the account most of the time.+And TWR is ...+just 1%?+Why?+.PP+Based on the transactions in our journal, TWR \[dq]think\[dq] that we+are buying back $90 worst of Snake Oil at the same price that it had at+the beginning of they year, and then after that our $100 investment gets+$1 increase in value, or 1% of $100.+Let\[aq]s take a closer look at what is happening here by asking for+quarterly reports instead of annual:+.IP+.nf+\f[C]+$ hledger roi -Q --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+-----++--------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+=======++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10 | 0 || 0.00% | 0.00% |+| 2 || 2019-04-01 | 2019-06-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 3 || 2019-07-01 | 2019-09-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 4 || 2019-10-01 | 2019-12-31 || 10 | 90 | 101 | 1 || 37.80% | 4.03% |++---++------------+------------++---------------+----------+-------------+-----++--------+-------++\f[R]+.fi+.PP+Now both IRR and TWR are thrown off by the fact that all of the growth+for our investment happens in Q4 2019.+This happes because IRR computation is still yielding 9.32% and TWR is+still 1%, but this time these are rates for three month period instead+of twelve, so in order to get an annual rate they should be multiplied+by four!+.PP+Let\[aq]s try to keep a better record of how Snake Oil grew in value:+.IP+.nf+\f[C]+2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil++2019-02-28 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-06-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-09-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25+\f[R]+.fi+.PP+Would our quartery report look better now?+Almost:+.IP+.nf+\f[C]+$ hledger roi -Q --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 1.00% |++---++------------+------------++---------------+----------+-------------+------++--------+--------++\f[R]+.fi+.PP+Something is still wrong with TWR computation for Q4, and if you have+been paying attention you know what it is already: big $90 buy-back is+recorded prior to the only transaction that captures the change of value+of Snake Oil that happened in this time period.+Lets combine transactions from 30th and 31st of Dec into one:+.IP+.nf+\f[C]+2019-12-30 Fear of missing out and growth of Snake Oil+ assets:cash -$90+ investment:snake oil+ equity:unrealized gains -$0.25+\f[R]+.fi+.PP+Now growth of investment properly affects its price at the time of+buy-back:+.IP+.nf+\f[C]+$ hledger roi -Q --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 9.57% |++---++------------+------------++---------------+----------+-------------+------++--------+--------++\f[R]+.fi+.PP+And for annual report, TWR now reports the exact profitability of our+investment:+.IP+.nf+\f[C]+$ hledger roi -Y --inv investment --pnl \[dq]unrealized\[dq]++---++------------+------------++---------------+----------+-------------+------++-------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++=======+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101.00 | 1.00 || 9.32% | 10.00% |++---++------------+------------++---------------+----------+-------------+------++-------+--------++\f[R]+.fi .SS stats .PP stats
hledger.cabal view
@@ -4,10 +4,10 @@ -- -- see: https://github.com/sol/hpack ----- hash: 6318476983e12bab8c8835a0781d94162a98e306fa19d4a916a2c750d4e353c4+-- hash: 319788ae329418b91462e0c768f9862096ceb831dfec8de2c8ab98e81f0998a1 name: hledger-version: 1.19.1+version: 1.20 synopsis: Command-line interface for the hledger accounting system description: The command-line interface for the hledger accounting system. Its basic function is to read a plain text file describing@@ -66,6 +66,7 @@ Hledger/Cli/Commands/Balancesheet.txt Hledger/Cli/Commands/Balancesheetequity.txt Hledger/Cli/Commands/Cashflow.txt+ Hledger/Cli/Commands/Check.txt Hledger/Cli/Commands/Checkdates.txt Hledger/Cli/Commands/Checkdupes.txt Hledger/Cli/Commands/Close.txt@@ -122,6 +123,7 @@ Hledger.Cli.Commands.Balancesheet Hledger.Cli.Commands.Balancesheetequity Hledger.Cli.Commands.Cashflow+ Hledger.Cli.Commands.Check Hledger.Cli.Commands.Checkdates Hledger.Cli.Commands.Checkdupes Hledger.Cli.Commands.Close@@ -148,7 +150,7 @@ other-modules: Paths_hledger ghc-options: -Wall -fno-warn-unused-do-bind -fno-warn-name-shadowing -fno-warn-missing-signatures -fno-warn-type-defaults -fno-warn-orphans -optP-Wno-nonportable-include-path- cpp-options: -DVERSION="1.19.1"+ cpp-options: -DVERSION="1.20" build-depends: Decimal >=0.5.1 , Diff@@ -165,14 +167,13 @@ , filepath , hashable >=1.2.4 , haskeline >=0.6- , hledger-lib >=1.19.1 && <1.20+ , hledger-lib >=1.20 && <1.21 , lucid , math-functions >=0.3.3.0 , megaparsec >=7.0.0 && <9.1 , mtl >=2.2.1 , old-time , parsec >=3- , pretty-show >=1.6.4 , process , regex-tdfa , safe >=0.2@@ -201,7 +202,7 @@ hs-source-dirs: app ghc-options: -Wall -fno-warn-unused-do-bind -fno-warn-name-shadowing -fno-warn-missing-signatures -fno-warn-type-defaults -fno-warn-orphans -optP-Wno-nonportable-include-path- cpp-options: -DVERSION="1.19.1"+ cpp-options: -DVERSION="1.20" build-depends: Decimal >=0.5.1 , aeson >=1@@ -217,13 +218,12 @@ , filepath , haskeline >=0.6 , hledger- , hledger-lib >=1.19.1 && <1.20+ , hledger-lib >=1.20 && <1.21 , math-functions >=0.3.3.0 , megaparsec >=7.0.0 && <9.1 , mtl >=2.2.1 , old-time , parsec >=3- , pretty-show >=1.6.4 , process , regex-tdfa , safe >=0.2@@ -253,7 +253,7 @@ hs-source-dirs: test ghc-options: -Wall -fno-warn-unused-do-bind -fno-warn-name-shadowing -fno-warn-missing-signatures -fno-warn-type-defaults -fno-warn-orphans -optP-Wno-nonportable-include-path- cpp-options: -DVERSION="1.19.1"+ cpp-options: -DVERSION="1.20" build-depends: Decimal >=0.5.1 , aeson >=1@@ -269,13 +269,12 @@ , filepath , haskeline >=0.6 , hledger- , hledger-lib >=1.19.1 && <1.20+ , hledger-lib >=1.20 && <1.21 , math-functions >=0.3.3.0 , megaparsec >=7.0.0 && <9.1 , mtl >=2.2.1 , old-time , parsec >=3- , pretty-show >=1.6.4 , process , regex-tdfa , safe >=0.2@@ -319,14 +318,13 @@ , filepath , haskeline >=0.6 , hledger- , hledger-lib >=1.19.1 && <1.20+ , hledger-lib >=1.20 && <1.21 , html , math-functions >=0.3.3.0 , megaparsec >=7.0.0 && <9.1 , mtl >=2.2.1 , old-time , parsec >=3- , pretty-show >=1.6.4 , process , regex-tdfa , safe >=0.2
hledger.info view
@@ -3,4263 +3,4698 @@ File: hledger.info, Node: Top, Next: COMMON TASKS, Up: (dir) -hledger(1) hledger 1.18.99-**************************--hledger - a command-line accounting tool-- 'hledger [-f FILE] COMMAND [OPTIONS] [ARGS]'-'hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]'-'hledger'-- hledger is a reliable, 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).-- This is hledger's command-line interface (there are also terminal and-web interfaces). Its basic function is to read a plain text file-describing financial transactions (in accounting terms, a general-journal) and print useful reports on standard output, or export them as-CSV. hledger can also read some other file formats such as CSV files,-translating them to journal format. Additionally, hledger lists other-hledger-* executables found in the user's $PATH and can invoke them as-subcommands.-- hledger reads data from one or more files in hledger journal,-timeclock, timedot, or CSV format specified with '-f', or-'$LEDGER_FILE', or '$HOME/.hledger.journal' (on windows, perhaps-'C:/Users/USER/.hledger.journal'). If using '$LEDGER_FILE', note this-must be a real environment variable, not a shell variable. You can-specify standard input with '-f-'.-- Transactions are dated movements of money between two (or more) named-accounts, and are recorded with journal entries like this:--2015/10/16 bought food- expenses:food $10- assets:cash-- For more about this format, see hledger_journal(5).-- Most users use a text editor to edit the journal, usually with an-editor mode such as ledger-mode for added convenience. hledger's-interactive add command is another way to record new transactions.-hledger never changes existing transactions.-- To get started, you can either save some entries like the above in-'~/.hledger.journal', or run 'hledger add' and follow the prompts. Then-try some commands like 'hledger print' or 'hledger balance'. Run-'hledger' with no arguments for a list of commands.--* Menu:--* COMMON TASKS::-* OPTIONS::-* COMMANDS::-* ENVIRONMENT::-* FILES::-* LIMITATIONS::-* TROUBLESHOOTING::---File: hledger.info, Node: COMMON TASKS, Next: OPTIONS, Prev: Top, Up: Top--1 COMMON TASKS-**************--Here are some quick examples of how to do some basic tasks with hledger.-For more details, see the reference section below, the-hledger_journal(5) manual, or the more extensive docs at-https://hledger.org.--* Menu:--* Getting help::-* Constructing command lines::-* Starting a journal file::-* Setting opening balances::-* Recording transactions::-* Reconciling::-* Reporting::-* Migrating to a new file::---File: hledger.info, Node: Getting help, Next: Constructing command lines, Up: COMMON TASKS--1.1 Getting help-================--$ hledger # show available commands-$ hledger --help # show common options-$ hledger CMD --help # show common and command options, and command help-$ hledger help # show available manuals/topics-$ hledger help hledger # show hledger manual as info/man/text (auto-chosen)-$ hledger help journal --man # show the journal manual as a man page-$ hledger help --help # show more detailed help for the help command-- Find more docs, chat, mail list, reddit, issue tracker:-https://hledger.org#help-feedback---File: hledger.info, Node: Constructing command lines, Next: Starting a journal file, Prev: Getting help, Up: COMMON TASKS--1.2 Constructing command lines-==============================--hledger has an extensive and powerful command line interface. We strive-to keep it simple and ergonomic, but you may run into one of the-confusing real world details described in OPTIONS, below. If that-happens, here are some tips that may help:-- * command-specific options must go after the command (it's fine to- put all options there) ('hledger CMD OPTS ARGS')- * running add-on executables directly simplifies command line parsing- ('hledger-ui OPTS ARGS')- * enclose "problematic" args in single quotes- * if needed, also add a backslash to hide regular expression- metacharacters from the shell- * to see how a misbehaving command is being parsed, add '--debug=2'.---File: hledger.info, Node: Starting a journal file, Next: Setting opening balances, Prev: Constructing command lines, Up: COMMON TASKS--1.3 Starting a journal file-===========================--hledger looks for your accounting data in a journal file,-'$HOME/.hledger.journal' by default:--$ hledger stats-The hledger journal file "/Users/simon/.hledger.journal" was not found.-Please create it first, eg with "hledger add" or a text editor.-Or, specify an existing journal file with -f or LEDGER_FILE.-- You can override this by setting the 'LEDGER_FILE' environment-variable. It's a good practice to keep this important file under-version control, and to start a new file each year. So you could do-something like this:--$ mkdir ~/finance-$ cd ~/finance-$ git init-Initialized empty Git repository in /Users/simon/finance/.git/-$ touch 2020.journal-$ echo "export LEDGER_FILE=$HOME/finance/2020.journal" >> ~/.bashrc-$ source ~/.bashrc-$ hledger stats-Main file : /Users/simon/finance/2020.journal-Included files : -Transactions span : to (0 days)-Last transaction : none-Transactions : 0 (0.0 per day)-Transactions last 30 days: 0 (0.0 per day)-Transactions last 7 days : 0 (0.0 per day)-Payees/descriptions : 0-Accounts : 0 (depth 0)-Commodities : 0 ()-Market prices : 0 ()---File: hledger.info, Node: Setting opening balances, Next: Recording transactions, Prev: Starting a journal file, Up: COMMON TASKS--1.4 Setting opening balances-============================--Pick a starting date for which you can look up the balances of some-real-world assets (bank accounts, wallet..) and liabilities (credit-cards..).-- To avoid a lot of data entry, you may want to start with just one or-two accounts, like your checking account or cash wallet; and pick a-recent starting date, like today or the start of the week. You can-always come back later and add more accounts and older transactions, eg-going back to january 1st.-- Add an opening balances transaction to the journal, declaring the-balances on this date. Here are two ways to do it:-- * The first way: open the journal in any text editor and save an- entry like this:-- 2020-01-01 * opening balances- assets:bank:checking $1000 = $1000- assets:bank:savings $2000 = $2000- assets:cash $100 = $100- liabilities:creditcard $-50 = $-50- equity:opening/closing balances-- These are start-of-day balances, ie whatever was in the account at- the end of the previous day.-- The * after the date is an optional status flag. Here it means- "cleared & confirmed".-- The currency symbols are optional, but usually a good idea as- you'll be dealing with multiple currencies sooner or later.-- The = amounts are optional balance assertions, providing extra- error checking.-- * The second way: run 'hledger add' and follow the prompts to record- a similar transaction:-- $ hledger add- Adding transactions to journal file /Users/simon/finance/2020.journal- Any command line arguments will be used as defaults.- Use tab key to complete, readline keys to edit, enter to accept defaults.- An optional (CODE) may follow transaction dates.- An optional ; COMMENT may follow descriptions or amounts.- If you make a mistake, enter < at any prompt to go one step backward.- To end a transaction, enter . when prompted.- To quit, enter . at a date prompt or press control-d or control-c.- Date [2020-02-07]: 2020-01-01- Description: * opening balances- Account 1: assets:bank:checking- Amount 1: $1000- Account 2: assets:bank:savings- Amount 2 [$-1000]: $2000- Account 3: assets:cash- Amount 3 [$-3000]: $100- Account 4: liabilities:creditcard- Amount 4 [$-3100]: $-50- Account 5: equity:opening/closing balances- Amount 5 [$-3050]: - Account 6 (or . or enter to finish this transaction): .- 2020-01-01 * opening balances- assets:bank:checking $1000- assets:bank:savings $2000- assets:cash $100- liabilities:creditcard $-50- equity:opening/closing balances $-3050- - Save this transaction to the journal ? [y]: - Saved.- Starting the next transaction (. or ctrl-D/ctrl-C to quit)- Date [2020-01-01]: .-- If you're using version control, this could be a good time to commit-the journal. Eg:--$ git commit -m 'initial balances' 2020.journal---File: hledger.info, Node: Recording transactions, Next: Reconciling, Prev: Setting opening balances, Up: COMMON TASKS--1.5 Recording transactions-==========================--As you spend or receive money, you can record these transactions using-one of the methods above (text editor, hledger add) or by using the-hledger-iadd or hledger-web add-ons, or by using the import command to-convert CSV data downloaded from your bank.-- Here are some simple transactions, see the hledger_journal(5) manual-and hledger.org for more ideas:--2020/1/10 * gift received- assets:cash $20- income:gifts--2020.1.12 * farmers market- expenses:food $13- assets:cash--2020-01-15 paycheck- income:salary- assets:bank:checking $1000---File: hledger.info, Node: Reconciling, Next: Reporting, Prev: Recording transactions, Up: COMMON TASKS--1.6 Reconciling-===============--Periodically you should reconcile - compare your hledger-reported-balances against external sources of truth, like bank statements or your-bank's 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.-- A typical workflow:-- 1. Reconcile cash. Count what's in your wallet. Compare with what- hledger reports ('hledger bal cash'). 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- ('hledger reg cash'). If you can't find the error, add an- adjustment transaction. Eg if you have $105 after the above, and- can't explain the missing $2, it could be:-- 2020-01-16 * adjust cash- assets:cash $-2 = $105- expenses:misc-- 2. Reconcile checking. Log in to your bank's website. Compare- today's (cleared) balance with hledger's cleared balance ('hledger- bal checking -C'). 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 'hledger reg checking -C'. This will be- easier if you generally record transaction dates quite similar to- your bank's clearing dates.-- 3. Repeat for other asset/liability accounts.-- Tip: instead of the register command, use hledger-ui to see a-live-updating register while you edit the journal: 'hledger-ui --watch---register checking -C'-- After reconciling, it could be a good time to mark the reconciled-transactions' status as "cleared and confirmed", if you want to track-that, by adding the '*' marker. Eg in the paycheck transaction above,-insert '*' between '2020-01-15' and 'paycheck'-- If you're using version control, this can be another good time to-commit:--$ git commit -m 'txns' 2020.journal---File: hledger.info, Node: Reporting, Next: Migrating to a new file, Prev: Reconciling, Up: COMMON TASKS--1.7 Reporting-=============--Here are some basic reports.-- Show all transactions:--$ hledger print-2020-01-01 * opening balances- assets:bank:checking $1000- assets:bank:savings $2000- assets:cash $100- liabilities:creditcard $-50- equity:opening/closing balances $-3050--2020-01-10 * gift received- assets:cash $20- income:gifts--2020-01-12 * farmers market- expenses:food $13- assets:cash--2020-01-15 * paycheck- income:salary- assets:bank:checking $1000--2020-01-16 * adjust cash- assets:cash $-2 = $105- expenses:misc-- Show account names, and their hierarchy:--$ hledger accounts --tree-assets- bank- checking- savings- cash-equity- opening/closing balances-expenses- food- misc-income- gifts- salary-liabilities- creditcard-- Show all account totals:--$ hledger balance- $4105 assets- $4000 bank- $2000 checking- $2000 savings- $105 cash- $-3050 equity:opening/closing balances- $15 expenses- $13 food- $2 misc- $-1020 income- $-20 gifts- $-1000 salary- $-50 liabilities:creditcard---------------------- 0-- Show only asset and liability balances, as a flat list, limited to-depth 2:--$ hledger bal assets liabilities --flat -2- $4000 assets:bank- $105 assets:cash- $-50 liabilities:creditcard---------------------- $4055-- Show the same thing without negative numbers, formatted as a simple-balance sheet:--$ hledger bs --flat -2-Balance Sheet 2020-01-16-- || 2020-01-16 -========================++============- Assets || -------------------------++------------- assets:bank || $4000 - assets:cash || $105 -------------------------++------------- || $4105 -========================++============- Liabilities || -------------------------++------------- liabilities:creditcard || $50 -------------------------++------------- || $50 -========================++============- Net: || $4055 -- The final total is your "net worth" on the end date. (Or use 'bse'-for a full balance sheet with equity.)-- Show income and expense totals, formatted as an income statement:--hledger is -Income Statement 2020-01-01-2020-01-16-- || 2020-01-01-2020-01-16 -===============++=======================- Revenues || ----------------++------------------------ income:gifts || $20 - income:salary || $1000 ----------------++------------------------ || $1020 -===============++=======================- Expenses || ----------------++------------------------ expenses:food || $13 - expenses:misc || $2 ----------------++------------------------ || $15 -===============++=======================- Net: || $1005 -- The final total is your net income during this period.-- Show transactions affecting your wallet, with running total:--$ hledger register cash-2020-01-01 opening balances assets:cash $100 $100-2020-01-10 gift received assets:cash $20 $120-2020-01-12 farmers market assets:cash $-13 $107-2020-01-16 adjust cash assets:cash $-2 $105-- Show weekly posting counts as a bar chart:--$ hledger activity -W-2019-12-30 *****-2020-01-06 ****-2020-01-13 ****---File: hledger.info, Node: Migrating to a new file, Prev: Reporting, Up: COMMON TASKS--1.8 Migrating to a new file-===========================--At the end of the year, you may want to continue your journal in a new-file, so that old transactions don't slow down or clutter your reports,-and to help ensure the integrity of your accounting history. See the-close command.-- If using version control, don't forget to 'git add' the new file.---File: hledger.info, Node: OPTIONS, Next: COMMANDS, Prev: COMMON TASKS, Up: Top--2 OPTIONS-*********--* Menu:--* General options::-* Command options::-* Command arguments::-* Queries::-* Special characters in arguments and queries::-* Unicode characters::-* Input files::-* Output destination::-* Output format::-* Regular expressions::-* Smart dates::-* Report start & end date::-* Report intervals::-* Period expressions::-* Depth limiting::-* Pivoting::-* Valuation::---File: hledger.info, Node: General options, Next: Command options, Up: OPTIONS--2.1 General options-===================--To see general usage help, including general options which are supported-by most hledger commands, run 'hledger -h'.-- General help options:--'-h --help'-- show general usage (or after COMMAND, command usage)-'--version'-- show version-'--debug[=N]'-- show debug output (levels 1-9, default: 1)-- General input options:--'-f FILE --file=FILE'-- use a different input file. For stdin, use - (default:- '$LEDGER_FILE' or '$HOME/.hledger.journal')-'--rules-file=RULESFILE'-- Conversion rules file to use when reading CSV (default: FILE.rules)-'--separator=CHAR'-- Field separator to expect when reading CSV (default: ',')-'--alias=OLD=NEW'-- rename accounts named OLD to NEW-'--anon'-- anonymize accounts and payees-'--pivot FIELDNAME'-- use some other field or tag for the account name-'-I --ignore-assertions'-- disable balance assertion checks (note: does not disable balance- assignments)-- General reporting options:--'-b --begin=DATE'-- include postings/txns on or after this date-'-e --end=DATE'-- include postings/txns before this date-'-D --daily'-- multiperiod/multicolumn report by day-'-W --weekly'-- multiperiod/multicolumn report by week-'-M --monthly'-- multiperiod/multicolumn report by month-'-Q --quarterly'-- multiperiod/multicolumn report by quarter-'-Y --yearly'-- multiperiod/multicolumn report by year-'-p --period=PERIODEXP'-- set start date, end date, and/or reporting interval all at once- using period expressions syntax-'--date2'-- match the secondary date instead (see command help for other- effects)-'-U --unmarked'-- include only unmarked postings/txns (can combine with -P or -C)-'-P --pending'-- include only pending postings/txns-'-C --cleared'-- include only cleared postings/txns-'-R --real'-- include only non-virtual postings-'-NUM --depth=NUM'-- hide/aggregate accounts or postings more than NUM levels deep-'-E --empty'-- show items with zero amount, normally hidden (and vice-versa in- hledger-ui/hledger-web)-'-B --cost'-- convert amounts to their cost/selling amount at transaction time-'-V --market'-- convert amounts to their market value in default valuation- commodities-'-X --exchange=COMM'-- convert amounts to their market value in commodity COMM-'--value'-- convert amounts to cost or market value, more flexibly than- -B/-V/-X-'--infer-value'-- with -V/-X/-value, also infer market prices from transactions-'--auto'-- apply automated posting rules to modify transactions.-'--forecast'-- generate future transactions from periodic transaction rules, for- the next 6 months or till report end date. In hledger-ui, also- make ordinary future transactions visible.-'--color=WHEN (or --colour=WHEN)'-- Should color-supporting commands use ANSI color codes in text- output. 'auto' (default): whenever stdout seems to be a- color-supporting terminal. 'always' or 'yes': always, useful eg- when piping output into 'less -R'. 'never' or 'no': never. A- NO_COLOR environment variable overrides this.-- When a reporting option appears more than once in the command line,-the last one takes precedence.-- Some reporting options can also be written as query arguments.---File: hledger.info, Node: Command options, Next: Command arguments, Prev: General options, Up: OPTIONS--2.2 Command options-===================--To see options for a particular command, including command-specific-options, run: 'hledger COMMAND -h'.-- Command-specific options must be written after the command name, eg:-'hledger print -x'.-- Additionally, if the command is an addon, you may need to put its-options after a double-hyphen, eg: 'hledger ui -- --watch'. Or, you can-run the addon executable directly: 'hledger-ui --watch'.---File: hledger.info, Node: Command arguments, Next: Queries, Prev: Command options, Up: OPTIONS--2.3 Command arguments-=====================--Most hledger commands accept arguments after the command name, which are-often a query, filtering the data in some way.-- You can save a set of command line options/arguments in a file, and-then reuse them by writing '@FILENAME' as a command line argument. Eg:-'hledger bal @foo.args'. (To prevent this, eg if you have an argument-that begins with a literal '@', precede it with '--', eg: 'hledger bal--- @ARG').-- Inside the argument file, each line should contain just one option or-argument. Avoid the use of spaces, except inside quotes (or you'll see-a confusing error). Between a flag and its argument, use = (or-nothing). Bad:--assets depth:2--X USD-- Good:--assets-depth:2--X=USD-- For special characters (see below), use one less level of quoting-than you would at the command prompt. Bad:---X"$"-- Good:---X$-- See also: Save frequently used options.---File: hledger.info, Node: Queries, Next: Special characters in arguments and queries, Prev: Command arguments, Up: OPTIONS--2.4 Queries-===========--One of hledger's strengths is being able to quickly report on precise-subsets of your data. Most commands accept an optional query-expression, written as arguments after the command name, to filter the-data by date, account name or other criteria. The syntax is similar to-a web search: one or more space-separated search terms, quotes to-enclose whitespace, prefixes to match specific fields, a not: prefix to-negate the match.-- We do not yet support arbitrary boolean combinations of search terms;-instead most commands show transactions/postings/accounts which match-(or negatively match):-- * any of the description terms AND- * any of the account terms AND- * any of the status terms AND- * all the other terms.-- The print command instead shows transactions which:-- * match any of the description terms AND- * have any postings matching any of the positive account terms AND- * have no postings matching any of the negative account terms AND- * match all the other terms.-- The following kinds of search terms can be used. Remember these can-also be prefixed with *'not:'*, eg to exclude a particular subaccount.--*'REGEX', 'acct:REGEX'*-- match account names by this regular expression. (With no prefix,- 'acct:' is assumed.) same as above--*'amt:N, amt:<N, amt:<=N, amt:>N, amt:>=N'*-- match postings with a single-commodity amount that is equal to,- less than, or greater than N. (Multi-commodity amounts are not- tested, and will always match.) 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.-*'code:REGEX'*-- match by transaction code (eg check number)-*'cur:REGEX'*-- match postings or transactions including any amounts whose- currency/commodity symbol is fully matched by REGEX. (For a partial- match, use '.*REGEX.*'). Note, to match characters which are- regex-significant, like the dollar sign ('$'), you need to prepend- '\'. And when using the command line you need to add one more- level of quoting to hide it from the shell, so eg do: 'hledger- print cur:'\$'' or 'hledger print cur:\\$'.-*'desc:REGEX'*-- match transaction descriptions.-*'date:PERIODEXPR'*-- match dates within the specified period. PERIODEXPR is a period- expression (with no report interval). Examples: 'date:2016',- 'date:thismonth', 'date:2000/2/1-2/15', 'date:lastweek-'. If the- '--date2' command line flag is present, this matches secondary- dates instead.-*'date2:PERIODEXPR'*-- match secondary dates within the specified period.-*'depth:N'*-- match (or display, depending on command) accounts at or above this- depth-*'note:REGEX'*-- match transaction notes (part of description right of '|', or whole- description when there's no '|')-*'payee:REGEX'*-- match transaction payee/payer names (part of description left of- '|', or whole description when there's no '|')-*'real:, real:0'*-- match real or virtual postings respectively-*'status:, status:!, status:*'*-- match unmarked, pending, or cleared transactions respectively-*'tag:REGEX[=REGEX]'*-- match by tag name, and optionally also by tag value. Note a tag:- query is considered to match a transaction if it matches any of the- postings. Also remember that postings inherit the tags of their- parent transaction.-- The following special search term is used automatically in-hledger-web, only:--*'inacct:ACCTNAME'*-- tells hledger-web to show the transaction register for this- account. Can be filtered further with 'acct' etc.-- Some of these can also be expressed as command-line options (eg-'depth:2' is equivalent to '--depth 2'). Generally you can mix options-and query arguments, and the resulting query will be their intersection-(perhaps excluding the '-p/--period' option).---File: hledger.info, Node: Special characters in arguments and queries, Next: Unicode characters, Prev: Queries, Up: OPTIONS--2.5 Special characters in arguments and queries-===============================================--In shell command lines, option and argument values which contain-"problematic" characters, ie spaces, and also characters significant to-your shell such as '<', '>', '(', ')', '|' and '$', should be escaped by-enclosing them in quotes or by writing backslashes before the-characters. Eg:-- 'hledger register -p 'last year' "accounts receivable-(receivable|payable)" amt:\>100'.--* Menu:--* More escaping::-* Even more escaping::-* Less escaping::---File: hledger.info, Node: More escaping, Next: Even more escaping, Up: Special characters in arguments and queries--2.5.1 More escaping----------------------Characters significant both to the shell and in regular expressions may-need one extra level of escaping. These include parentheses, the pipe-symbol and the dollar sign. Eg, to match the dollar symbol, bash users-should do:-- 'hledger balance cur:'\$''-- or:-- 'hledger balance cur:\\$'---File: hledger.info, Node: Even more escaping, Next: Less escaping, Prev: More escaping, Up: Special characters in arguments and queries--2.5.2 Even more escaping---------------------------When hledger runs an addon executable (eg you type 'hledger ui', hledger-runs 'hledger-ui'), it de-escapes command-line options and arguments-once, so you might need to _triple_-escape. Eg in bash, running the ui-command and matching the dollar sign, it's:-- 'hledger ui cur:'\\$''-- or:-- 'hledger ui cur:\\\\$'-- If you asked why _four_ slashes above, this may help:--unescaped: '$'-escaped: '\$'-double-escaped: '\\$'-triple-escaped: '\\\\$'-- (The number of backslashes in fish shell is left as an exercise for-the reader.)-- You can always avoid the extra escaping for addons by running the-addon directly:-- 'hledger-ui cur:\\$'---File: hledger.info, Node: Less escaping, Prev: Even more escaping, Up: Special characters in arguments and queries--2.5.3 Less escaping----------------------Inside an argument file, or in the search field of hledger-ui or-hledger-web, or at a GHCI prompt, you need one less level of escaping-than at the command line. And backslashes may work better than quotes.-Eg:-- 'ghci> :main balance cur:\$'---File: hledger.info, Node: Unicode characters, Next: Input files, Prev: Special characters in arguments and queries, Up: OPTIONS--2.6 Unicode characters-======================--hledger is expected to handle non-ascii characters correctly:-- * they should be parsed correctly in input files and on the command- line, by all hledger tools (add, iadd, hledger-web's- search/add/edit forms, etc.)-- * they should be displayed correctly by all hledger tools, and- on-screen alignment should be preserved.-- This requires a well-configured environment. Here are some tips:-- * A system locale must be configured, and it must be one that can- decode the characters being used. In bash, you can set a locale- like this: 'export LANG=en_US.UTF-8'. There are some more details- in Troubleshooting. This step is essential - without it, hledger- will quit on encountering a non-ascii character (as with all- GHC-compiled programs).-- * your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)- must support unicode-- * the terminal must be using a font which includes the required- unicode glyphs-- * the terminal should be configured to display wide characters as- double width (for report alignment)-- * 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).---File: hledger.info, Node: Input files, Next: Output destination, Prev: Unicode characters, Up: OPTIONS--2.7 Input files-===============--hledger reads transactions from a data file (and the add command writes-to it). By default this file is '$HOME/.hledger.journal' (or on-Windows, something like 'C:/Users/USER/.hledger.journal'). You can-override this with the '$LEDGER_FILE' environment variable:--$ setenv LEDGER_FILE ~/finance/2016.journal-$ hledger stats-- or with the '-f/--file' option:--$ hledger -f /some/file stats-- The file name '-' (hyphen) means standard input:--$ cat some.journal | hledger -f--- Usually the data file is in hledger's journal format, but it can be-in any of the supported file formats, which currently are:--Reader: Reads: Used for file- extensions:----------------------------------------------------------------------------'journal'hledger journal files and some Ledger '.journal' '.j'- journals, for transactions '.hledger' '.ledger'-'timeclock'timeclock files, for precise time '.timeclock'- logging-'timedot'timedot files, for approximate time '.timedot'- logging-'csv' comma/semicolon/tab/other-separated '.csv' '.ssv' '.tsv'- values, for data import-- hledger detects the format automatically based on the file extensions-shown above. If it can't recognise the file extension, it assumes-'journal' format. So for non-journal files, it's important to use a-recognised file extension, so as to either read successfully or to show-relevant error messages.-- When you can't ensure the right file extension, not to worry: you can-force a specific reader/format by prefixing the file path with the-format and a colon. Eg to read a .dat file as csv:--$ hledger -f csv:/some/csv-file.dat stats-$ echo 'i 2009/13/1 08:00:00' | hledger print -ftimeclock:--- You can specify multiple '-f' options, to read multiple files as one-big journal. There are some limitations with this:-- * directives in one file will not affect the other files- * balance assertions will not see any account balances from previous- files-- If you need either of those things, you can-- * use a single parent file which includes the others- * or concatenate the files into one before reading, eg: 'cat- a.journal b.journal | hledger -f- CMD'.---File: hledger.info, Node: Output destination, Next: Output format, Prev: Input files, Up: OPTIONS--2.8 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:--$ hledger print > foo.txt-- Some commands (print, register, stats, the balance commands) also-provide the '-o/--output-file' option, which does the same thing without-needing the shell. Eg:--$ hledger print -o foo.txt-$ hledger print -o - # write to stdout (the default)---File: hledger.info, Node: Output format, Next: Regular expressions, Prev: Output destination, Up: OPTIONS--2.9 Output format-=================--Some commands (print, register, the balance commands) offer a choice of-output format. In addition to the usual plain text format ('txt'),-there are CSV ('csv'), HTML ('html'), JSON ('json') and SQL ('sql').-This is controlled by the '-O/--output-format' option:--$ hledger print -O csv-- or, by a file extension specified with '-o/--output-file':--$ hledger balancesheet -o foo.html # write HTML to foo.html-- The '-O' option can be used to override the file extension if needed:--$ hledger balancesheet -o foo.txt -O html # write HTML to foo.txt-- Some notes about JSON output:-- * This feature is marked experimental, and not yet much used; you- should expect our JSON to evolve. Real-world feedback is welcome.-- * Our JSON is rather large and verbose, as it is quite a faithful- representation of hledger's internal data types. To understand the- JSON, read the Haskell type definitions, which are mostly in- https://github.com/simonmichael/hledger/blob/master/hledger-lib/Hledger/Data/Types.hs.-- * hledger represents quantities as Decimal values storing up to 255- significant digits, eg for repeating decimals. Such numbers can- arise in practice (from automatically-calculated transaction- prices), and would break most JSON consumers. So in JSON, we show- quantities as simple Numbers with at most 10 decimal places. We- don't limit the number of integer digits, but that part is under- your control. We hope this approach will not cause problems in- practice; if you find otherwise, please let us know. (Cf #1195)-- Notes about SQL output:-- * SQL output is also marked experimental, and much like JSON could- use real-world feedback.-- * SQL output is expected to work with sqlite, MySQL and PostgreSQL-- * SQL output is structured with the expectations that statements will- be executed in the empty database. If you already have tables- created via SQL output of hledger, you would probably want to- either clear tables of existing data (via 'delete' or 'truncate'- SQL statements) or drop tables completely as otherwise your- postings will be duped.---File: hledger.info, Node: Regular expressions, Next: Smart dates, Prev: Output format, Up: OPTIONS--2.10 Regular expressions-========================--hledger uses regular expressions in a number of places:-- * query terms, on the command line and in the hledger-web search- form: 'REGEX', 'desc:REGEX', 'cur:REGEX', 'tag:...=REGEX'- * CSV rules conditional blocks: 'if REGEX ...'- * account alias directives and options: 'alias /REGEX/ =- REPLACEMENT', '--alias /REGEX/=REPLACEMENT'-- hledger's regular expressions come from the regex-tdfa library. If-they're not doing what you expect, it's important to know exactly what-they support:-- 1. they are case insensitive- 2. they are infix matching (they do not need to match the entire thing- being matched)- 3. they are POSIX ERE (extended regular expressions)- 4. they also support GNU word boundaries ('\b', '\B', '\<', '\>')- 5. they do not support backreferences; if you write '\1', it will- match the digit '1'. Except when doing text replacement, eg in- account aliases, where backreferences can be used in the- replacement string to reference capturing groups in the search- regexp.- 6. they do not support mode modifiers ('(?s)'), character classes- ('\w', '\d'), or anything else not mentioned above.-- Some things to note:-- * In the 'alias' directive and '--alias' option, regular expressions- must be enclosed in forward slashes ('/REGEX/'). Elsewhere in- hledger, these are not required.-- * In queries, to match a regular expression metacharacter like '$' as- a literal character, prepend a backslash. Eg to search for amounts- with the dollar sign in hledger-web, write 'cur:\$'.-- * On the command line, some metacharacters like '$' have a special- meaning to the shell and so must be escaped at least once more.- See Special characters.---File: hledger.info, Node: Smart dates, Next: Report start & end date, Prev: Regular expressions, Up: OPTIONS--2.11 Smart dates-================--hledger's user interfaces accept a flexible "smart date" syntax (unlike-dates in the journal file). Smart dates allow some english words, can-be relative to today's date, and can have less-significant date parts-omitted (defaulting to 1).-- Examples:--'2004/10/1', exact date, several separators allowed. Year-'2004-01-01', is 4+ digits, month is 1-12, day is 1-31-'2004.9.1'-'2004' start of year-'2004/10' start of month-'10/1' month and day in current year-'21' day in current month-'october, oct' start of month in current year-'yesterday, today, -1, 0, 1 days from today-tomorrow'-'last/this/next -1, 0, 1 periods from the current period-day/week/month/quarter/year'-'20181201' 8 digit YYYYMMDD with valid year month and- day-'201812' 6 digit YYYYMM with valid year and month-- Counterexamples - malformed digit sequences might give surprising-results:--'201813' 6 digits with an invalid month is parsed as start of- 6-digit year-'20181301' 8 digits with an invalid month is parsed as start of- 8-digit year-'20181232' 8 digits with an invalid day gives an error-'201801012' 9+ digits beginning with a valid YYYYMMDD gives an error---File: hledger.info, Node: Report start & end date, Next: Report intervals, Prev: Smart dates, Up: OPTIONS--2.12 Report start & end date-============================--Most hledger reports show the full span of time represented by the-journal data, by default. So, the effective report start and end dates-will be the earliest and latest transaction or posting dates found in-the journal.-- Often you will want to see a shorter time span, such as the current-month. You can specify a start and/or end date using '-b/--begin',-'-e/--end', '-p/--period' or a 'date:' query (described below). All of-these accept the smart date syntax.-- Some notes:-- * As in Ledger, end dates are exclusive, so you need to write the- date _after_ the last day you want to include.- * As noted in reporting options: among start/end dates specified with- _options_, the last (i.e. right-most) option takes precedence.- * The effective report start and end dates are the intersection of- the start/end dates from options and that from 'date:' queries.- That is, 'date:2019-01 date:2019 -p'2000 to 2030'' yields January- 2019, the smallest common time span.-- Examples:--'-b begin on St. Patrick's day 2016-2016/3/17'-'-e 12/1' end at the start of december 1st of the current year- (11/30 will be the last date included)-'-b all transactions on or after the 1st of the current month-thismonth'-'-p all transactions in the current month-thismonth'-'date:2016/3/17..'the above written as queries instead ('..' can also be- replaced with '-')-'date:..12/1'-'date:thismonth..'-'date:thismonth'---File: hledger.info, Node: Report intervals, Next: Period expressions, Prev: Report start & end date, Up: OPTIONS--2.13 Report intervals-=====================--A report interval can be specified so that commands like register,-balance and activity will divide their reports into multiple subperiods.-The basic intervals can be selected with one of '-D/--daily',-'-W/--weekly', '-M/--monthly', '-Q/--quarterly', or '-Y/--yearly'. More-complex intervals may be specified with a period expression. Report-intervals can not be specified with a query.---File: hledger.info, Node: Period expressions, Next: Depth limiting, Prev: Report intervals, Up: OPTIONS--2.14 Period expressions-=======================--The '-p/--period' option accepts period expressions, a shorthand way of-expressing a start date, end date, and/or report interval all at once.-- Here's a basic period expression specifying the first quarter of-2009. Note, hledger always treats start dates as inclusive and end-dates as exclusive:-- '-p "from 2009/1/1 to 2009/4/1"'-- Keywords like "from" and "to" are optional, and so are the spaces, as-long as you don't run two dates together. "to" can also be written as-".." or "-". These are equivalent to the above:--'-p "2009/1/1 2009/4/1"'-'-p2009/1/1to2009/4/1'-'-p2009/1/1..2009/4/1'-- Dates are smart dates, so if the current year is 2009, the above can-also be written as:--'-p "1/1 4/1"'-'-p "january-apr"'-'-p "this year to 4/1"'-- If you specify only one date, the missing start or end date will be-the earliest or latest transaction in your journal:--'-p "from 2009/1/1"' everything after january 1, 2009-'-p "from 2009/1"' the same-'-p "from 2009"' the same-'-p "to 2009"' everything before january 1, 2009-- A single date with no "from" or "to" defines both the start and end-date like so:--'-p "2009"' the year 2009; equivalent to “2009/1/1 to 2010/1/1”-'-p "2009/1"' the month of jan; equivalent to “2009/1/1 to 2009/2/1”-'-p "2009/1/1"' just that day; equivalent to “2009/1/1 to 2009/1/2”-- Or you can specify a single quarter like so:--'-p "2009Q1"' first quarter of 2009, equivalent to “2009/1/1 to 2009/4/1”-'-p "q4"' fourth quarter of the current year-- The argument of '-p' can also begin with, or be, a report interval-expression. The basic report intervals are 'daily', 'weekly',-'monthly', 'quarterly', or 'yearly', which have the same effect as the-'-D','-W','-M','-Q', or '-Y' flags. Between report interval and-start/end dates (if any), the word 'in' is optional. Examples:--'-p "weekly from 2009/1/1 to 2009/4/1"'-'-p "monthly in 2008"'-'-p "quarterly"'-- Note that 'weekly', 'monthly', 'quarterly' and 'yearly' intervals-will always start on the first day on week, month, quarter or year-accordingly, and will end on the last day of same period, even if-associated period expression specifies different explicit start and end-date.-- For example:--'-p "weekly from starts on 2008/12/29, closest preceding-2009/1/1 to 2009/4/1"' Monday-'-p "monthly in starts on 2018/11/01-2008/11/25"'-'-p "quarterly from starts on 2009/04/01, ends on 2009/06/30,-2009-05-05 to which are first and last days of Q2 2009-2009-06-01"'-'-p "yearly from starts on 2009/01/01, first day of 2009-2009-12-29"'-- The following more complex report intervals are also supported:-'biweekly', 'fortnightly', 'bimonthly', 'every-day|week|month|quarter|year', 'every N-days|weeks|months|quarters|years'.-- All of these will start on the first day of the requested period and-end on the last one, as described above.-- Examples:--'-p "bimonthly from periods will have boundaries on 2008/01/01,-2008"' 2008/03/01, ...-'-p "every 2 weeks"' starts on closest preceding Monday-'-p "every 5 month from periods will have boundaries on 2009/03/01,-2009/03"' 2009/08/01, ...-- If you want intervals that start on arbitrary day of your choosing-and span a week, month or year, you need to use any of the following:-- 'every Nth day of week', 'every <weekday>', 'every Nth day [of-month]', 'every Nth weekday [of month]', 'every MM/DD [of year]', 'every-Nth MMM [of year]', 'every MMM Nth [of year]'.-- Examples:--'-p "every 2nd day of periods will go from Tue to Tue-week"'-'-p "every Tue"' same-'-p "every 15th day"' period boundaries will be on 15th of each- month-'-p "every 2nd period boundaries will be on second Monday of-Monday"' each month-'-p "every 11/05"' yearly periods with boundaries on 5th of Nov-'-p "every 5th Nov"' same-'-p "every Nov 5th"' same-- Show historical balances at end of 15th each month (N is exclusive-end date):-- 'hledger balance -H -p "every 16th day"'-- Group postings from start of wednesday to end of next tuesday (N is-start date and exclusive end date):-- 'hledger register checking -p "every 3rd day of week"'---File: hledger.info, Node: Depth limiting, Next: Pivoting, Prev: Period expressions, Up: OPTIONS--2.15 Depth limiting-===================--With the '--depth N' option (short form: '-N'), commands like account,-balance and register will show only the uppermost accounts in the-account tree, down to level N. Use this when you want a summary with-less detail. This flag has the same effect as a 'depth:' query argument-(so '-2', '--depth=2' or 'depth:2' are equivalent).---File: hledger.info, Node: Pivoting, Next: Valuation, Prev: Depth limiting, Up: OPTIONS--2.16 Pivoting-=============--Normally hledger sums amounts, and organizes them in a hierarchy, based-on account name. The '--pivot FIELD' option causes it to sum and-organize hierarchy based on the value of some other field instead.-FIELD can be: 'code', 'description', 'payee', 'note', or the full name-(case insensitive) of any tag. As with account names, values containing-'colon:separated:parts' will be displayed hierarchically in reports.-- '--pivot' is a general option affecting all reports; you can think of-hledger transforming the journal before any other processing, replacing-every posting's account name with the value of the specified field on-that posting, inheriting it from the transaction or using a blank value-if it's not present.-- An example:--2016/02/16 Member Fee Payment- assets:bank account 2 EUR- income:member fees -2 EUR ; member: John Doe-- Normal balance report showing account names:--$ hledger balance- 2 EUR assets:bank account- -2 EUR income:member fees---------------------- 0-- Pivoted balance report, using member: tag values instead:--$ hledger balance --pivot member- 2 EUR- -2 EUR John Doe---------------------- 0-- One way to show only amounts with a member: value (using a query,-described below):--$ hledger balance --pivot member tag:member=.- -2 EUR John Doe---------------------- -2 EUR-- Another way (the acct: query matches against the pivoted "account-name"):--$ hledger balance --pivot member acct:.- -2 EUR John Doe---------------------- -2 EUR---File: hledger.info, Node: Valuation, Prev: Pivoting, Up: OPTIONS--2.17 Valuation-==============--Instead of reporting amounts in their original commodity, hledger can-convert them to cost/sale amount (using the conversion rate recorded in-the transaction), or to market value (using some market price on a-certain date). This is controlled by the '--value=TYPE[,COMMODITY]'-option, but we also provide the simpler '-B'/'-V'/'-X' flags, and-usually one of those is all you need.--* Menu:--* -B Cost::-* -V Value::-* -X Value in specified commodity::-* Valuation date::-* Market prices::-* --infer-value market prices from transactions::-* Valuation commodity::-* Simple valuation examples::-* --value Flexible valuation::-* More valuation examples::-* Effect of valuation on reports::---File: hledger.info, Node: -B Cost, Next: -V Value, Up: Valuation--2.17.1 -B: Cost------------------The '-B/--cost' flag converts amounts to their cost or sale amount at-transaction time, if they have a transaction price specified.---File: hledger.info, Node: -V Value, Next: -X Value in specified commodity, Prev: -B Cost, Up: Valuation--2.17.2 -V: Value-------------------The '-V/--market' flag converts amounts to market value in their default-_valuation commodity_, using the market prices in effect on the-_valuation date(s)_, if any. More on these in a minute.---File: hledger.info, Node: -X Value in specified commodity, Next: Valuation date, Prev: -V Value, Up: Valuation--2.17.3 -X: Value in specified commodity------------------------------------------The '-X/--exchange=COMM' option is like '-V', except you tell it which-currency you want to convert to, and it tries to convert everything to-that.---File: hledger.info, Node: Valuation date, Next: Market prices, Prev: -X Value in specified commodity, Up: Valuation--2.17.4 Valuation date------------------------Since market prices can change from day to day, market value reports-have a valuation date (or more than one), which determines which market-prices will be used.-- For single period reports, if an explicit report end date is-specified, that will be used as the valuation date; otherwise the-valuation date is "today".-- For multiperiod reports, each column/period is valued on the last day-of the period.---File: hledger.info, Node: Market prices, Next: --infer-value market prices from transactions, Prev: Valuation date, Up: Valuation--2.17.5 Market prices-----------------------_(experimental)_-- 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 :-- 1. A _declared market price_ or _inferred market price_: A's latest- market price in B on or before the valuation date as declared by a- P directive, or (if the '--infer-value' flag is used) inferred from- transaction prices.-- 2. A _reverse market price_: the inverse of a declared or inferred- market price from B to A.-- 3. A _chained market price_: a synthetic price formed by combining the- shortest chain of market prices (any of the above types) leading- from A to B.-- Amounts for which no applicable market price can be found, are not-converted.---File: hledger.info, Node: --infer-value market prices from transactions, Next: Valuation commodity, Prev: Market prices, Up: Valuation--2.17.6 -infer-value: market prices from transactions-------------------------------------------------------_(experimental)_-- 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 transaction prices as additional-market prices (as Ledger does) ? We could produce value reports without-needing P directives at all.-- Adding the '--infer-value' flag to '-V', '-X' or '--value' enables-this. So for example, 'hledger bs -V --infer-value' will get market-prices both from P directives and from transactions.-- 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 Valuation section carefully, and try adding-'--debug' or '--debug=2' to troubleshoot.-- '--infer-value' can infer market prices from:-- * multicommodity transactions with explicit prices ('@'/'@@')-- * multicommodity transactions with implicit prices (no '@', two- commodities, unbalanced). (With these, the order of postings- matters. 'hledger print -x' can be useful for troubleshooting.)-- * but not, currently, from "more correct" multicommodity transactions- (no '@', multiple commodities, balanced).---File: hledger.info, Node: Valuation commodity, Next: Simple valuation examples, Prev: --infer-value market prices from transactions, Up: Valuation--2.17.7 Valuation commodity-----------------------------_(experimental)_-- *When you specify a valuation commodity ('-X COMM' or '--value-TYPE,COMM'):*-hledger will convert all amounts to COMM, wherever it can find a-suitable market price (including by reversing or chaining prices).-- *When you leave the valuation commodity unspecified ('-V' or '--value-TYPE'):*-For each commodity A, hledger picks a default valuation commodity as-follows, in this order of preference:-- 1. The price commodity from the latest P-declared market price for A- on or before valuation date.-- 2. 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.)-- 3. If there are no P directives at all (any commodity or date) and the- '--infer-value' flag is used: the price commodity from the latest- transaction-inferred price for A on or before valuation date.-- This means:-- * If you have P directives, they determine which commodities '-V'- will convert, and to what.-- * If you have no P directives, and use the '--infer-value' flag,- transaction prices determine it.-- Amounts for which no valuation commodity can be found are not-converted.---File: hledger.info, Node: Simple valuation examples, Next: --value Flexible valuation, Prev: Valuation commodity, Up: Valuation--2.17.8 Simple valuation examples-----------------------------------Here are some quick examples of '-V':--; 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-- How many euros do I have ?--$ hledger -f t.j bal -N euros- €100 assets:euros-- What are they worth at end of nov 3 ?--$ hledger -f t.j bal -N euros -V -e 2016/11/4- $110.00 assets:euros-- What are they worth after 2016/12/21 ? (no report end date-specified, defaults to today)--$ hledger -f t.j bal -N euros -V- $103.00 assets:euros---File: hledger.info, Node: --value Flexible valuation, Next: More valuation examples, Prev: Simple valuation examples, Up: Valuation--2.17.9 -value: Flexible valuation------------------------------------'-B', '-V' and '-X' are special cases of the more general '--value'-option:-- --value=TYPE[,COMM] TYPE is cost, then, end, now or YYYY-MM-DD.- COMM is an optional commodity symbol.- Shows amounts converted to:- - cost commodity using transaction prices (then optionally to COMM using market prices at period end(s))- - 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-- The TYPE part selects cost or value and valuation date:--'--value=cost'-- Convert amounts to cost, using the prices recorded in transactions.-'--value=then'-- Convert amounts to their value in the default valuation commodity,- using market prices on each posting's date. This is currently- supported only by the print and register commands.-'--value=end'-- 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's end date); or in multiperiod reports,- market prices on the last day of each subperiod.-'--value=now'-- Convert amounts to their value in the default valuation commodity- using current market prices (as of when report is generated).-'--value=YYYY-MM-DD'-- Convert amounts to their value in the default valuation commodity- using market prices on this date.-- To select a different valuation commodity, add the optional ',COMM'-part: a comma, then the target commodity's symbol. Eg:-*'--value=now,EUR'*. hledger will do its best to convert amounts to-this commodity, deducing market prices as described above.---File: hledger.info, Node: More valuation examples, Next: Effect of valuation on reports, Prev: --value Flexible valuation, Up: Valuation--2.17.10 More valuation examples----------------------------------Here are some examples showing the effect of '--value', as seen with-'print':--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 @ 5 B--2000-02-01- (a) 1 A @ 6 B--2000-03-01- (a) 1 A @ 7 B-- Show the cost of each posting:--$ hledger -f- print --value=cost-2000-01-01- (a) 5 B--2000-02-01- (a) 6 B--2000-03-01- (a) 7 B-- Show the value as of the last day of the report period (2000-02-29):--$ hledger -f- print --value=end date:2000/01-2000/03-2000-01-01- (a) 2 B--2000-02-01- (a) 2 B-- With no report period specified, that shows the value as of the last-day of the journal (2000-03-01):--$ hledger -f- print --value=end-2000-01-01- (a) 3 B--2000-02-01- (a) 3 B--2000-03-01- (a) 3 B-- Show the current value (the 2000-04-01 price is still in effect-today):--$ hledger -f- print --value=now-2000-01-01- (a) 4 B--2000-02-01- (a) 4 B--2000-03-01- (a) 4 B-- Show the value on 2000/01/15:--$ 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-- You may need to explicitly set a commodity's display style, when-reverse prices are used. Eg this output might be surprising:--P 2000-01-01 A 2B--2000-01-01- a 1B- b--$ hledger print -x -X A-2000-01-01- a 0- b 0-- Explanation: because there's no amount or commodity directive-specifying a display style for A, 0.5A gets the default style, which-shows no decimal digits. Because the displayed amount looks like zero,-the commodity symbol and minus sign are not displayed either. Adding a-commodity directive sets a more useful display style for A:--P 2000-01-01 A 2B-commodity 0.00A--2000-01-01- a 1B- b--$ hledger print -X A-2000-01-01- a 0.50A- b -0.50A---File: hledger.info, Node: Effect of valuation on reports, Prev: More valuation examples, Up: Valuation--2.17.11 Effect of valuation on reports-----------------------------------------Here is a reference for how valuation is supposed to affect each part of-hledger's reports (and a glossary). (It's wide, you'll have to scroll-sideways.) It may be useful when troubleshooting. If you find-problems, please report them, ideally with a reproducible example.-Related: #329, #1083.--Report '-B', '-V', '-X' '--value=then' '--value=end' '--value=DATE',-type '--value=cost' '--value=now'---------------------------------------------------------------------------------*print*-posting cost value at value at value at value at-amounts report end posting date report or DATE/today- or today journal end-balance unchanged unchanged unchanged unchanged unchanged-assertions-/-assignments-*register*-starting cost value at not value at value at-balance day before supported day before DATE/today-(with -H) report or report or- journal journal- start start-posting cost value at value at value at value at-amounts report end posting date report or DATE/today-(no report or today journal end-interval)-summary summarised value at sum of value at value at-posting cost period postings in period ends DATE/today-amounts ends interval,-(with valued at-report interval-interval) start-running sum/average sum/average sum/average sum/average sum/average-total/averageof of of displayed of of- displayed displayed values displayed displayed- values values values values-*balance-(bs, bse,-cf, is..)*-balances sums of value at not value at value at-(no report costs report end supported report or DATE/today-interval) or today journal end of sums- of sums of of sums of of- postings postings postings-balances sums of value at not value at value at-(with costs period supported period ends DATE/today-report ends of of sums of of sums-interval) sums of postings of- postings postings-starting sums of sums of not sums of sums of-balances costs of postings supported postings postings-(with postings before before before-report before report report report-interval report start start start-and -H) start-budget like like not like like-amounts balances balances supported balances balances-with--budget-grand sum of sum of not sum of sum of-total (no displayed displayed supported displayed displayed-report values values values values-interval)-row sums/averagessums/averagesnot sums/averages sums/averages-totals/averagesof of supported of of-(with displayed displayed displayed displayed-report values values values values-interval)-column sums of sums of not sums of sums of-totals displayed displayed supported displayed displayed- values values values values-grand sum/average sum/average not sum/average sum/average-total/averageof column of column supported of column of- totals totals totals column- totals-- *Glossary:*--_cost_-- calculated using price(s) recorded in the transaction(s).-_value_-- market value using available market price declarations, or the- unchanged amount if no conversion rate can be found.-_report start_-- the first day of the report period specified with -b or -p or- date:, otherwise today.-_report or journal start_-- the first day of the report period specified with -b or -p or- date:, otherwise the earliest transaction date in the journal,- otherwise today.-_report end_-- the last day of the report period specified with -e or -p or date:,- otherwise today.-_report or journal end_-- the last day of the report period specified with -e or -p or date:,- otherwise the latest transaction date in the journal, otherwise- today.-_report interval_-- a flag (-D/-W/-M/-Q/-Y) or period expression that activates the- report's multi-period mode (whether showing one or many- subperiods).---File: hledger.info, Node: COMMANDS, Next: ENVIRONMENT, Prev: OPTIONS, Up: Top--3 COMMANDS-**********--hledger provides a number of subcommands; 'hledger' with no arguments-shows a list.-- If you install additional 'hledger-*' packages, or if you put-programs or scripts named 'hledger-NAME' in your PATH, these will also-be listed as subcommands.-- Run a subcommand by writing its name as first argument (eg 'hledger-incomestatement'). You can also write one of the standard short aliases-displayed in parentheses in the command list ('hledger b'), or any any-unambiguous prefix of a command name ('hledger inc').-- Here are all the builtin commands in alphabetical order. See also-'hledger' for a more organised command list, and 'hledger CMD -h' for-detailed command help.--* Menu:--* accounts::-* activity::-* add::-* aregister::-* balance::-* balancesheet::-* balancesheetequity::-* cashflow::-* check-dates::-* check-dupes::-* close::-* codes::-* commodities::-* descriptions::-* diff::-* files::-* help::-* import::-* incomestatement::-* notes::-* payees::-* prices::-* print::-* print-unique::-* register::-* register-match::-* rewrite::-* roi::-* stats::-* tags::-* test::-* Add-on commands::---File: hledger.info, Node: accounts, Next: activity, Up: COMMANDS--3.1 accounts-============--accounts, a-Show account names.-- This command lists account names, either declared with account-directives (-declared), posted to (-used), or both (the default). With-query arguments, only matched account names and account names referenced-by matched postings are shown. It shows a flat list by default. With-'--tree', it uses indentation to show the account hierarchy. In flat-mode you can add '--drop N' to omit the first few account name-components. Account names can be depth-clipped with 'depth:N' or-'--depth N' or '-N'.-- Examples:--$ hledger accounts-assets:bank:checking-assets:bank:saving-assets:cash-expenses:food-expenses:supplies-income:gifts-income:salary-liabilities:debts---File: hledger.info, Node: activity, Next: add, Prev: accounts, Up: COMMANDS--3.2 activity-============--activity-Show an ascii barchart of posting counts per interval.-- The activity command displays an ascii histogram showing transaction-counts by day, week, month or other reporting interval (by day is the-default). With query arguments, it counts only matched transactions.-- Examples:--$ hledger activity --quarterly-2008-01-01 **-2008-04-01 *******-2008-07-01 -2008-10-01 **---File: hledger.info, Node: add, Next: aregister, Prev: activity, Up: COMMANDS--3.3 add-=======--add-Prompt for transactions and add them to the journal. Any arguments will-be used as default inputs for the first N prompts.-- Many hledger users edit their journals directly with a text editor,-or generate them from CSV. For more interactive data entry, there is the-'add' command, which prompts interactively on the console for new-transactions, and appends them to the journal file (if there are-multiple '-f FILE' options, the first file is used.) Existing-transactions are not changed. This is the only hledger command that-writes to the journal file.-- To use it, just run 'hledger add' and follow the prompts. You can-add as many transactions as you like; when you are finished, enter '.'-or press control-d or control-c to exit.-- Features:-- * add tries to provide useful defaults, using the most similar (by- description) recent transaction (filtered by the query, if any) as- a template.- * You can also set the initial defaults with command line arguments.- * Readline-style edit keys can be used during data entry.- * The tab key will auto-complete whenever possible - accounts,- descriptions, dates ('yesterday', 'today', 'tomorrow'). If the- input area is empty, it will insert the default value.- * If the journal defines a default commodity, it will be added to any- bare numbers entered.- * A parenthesised transaction code may be entered following a date.- * Comments and tags may be entered following a description or amount.- * If you make a mistake, enter '<' at any prompt to go one step- backward.- * Input prompts are displayed in a different colour when the terminal- supports it.-- Example (see the tutorial for a detailed explanation):--$ hledger add-Adding transactions to journal file /src/hledger/examples/sample.journal-Any command line arguments will be used as defaults.-Use tab key to complete, readline keys to edit, enter to accept defaults.-An optional (CODE) may follow transaction dates.-An optional ; COMMENT may follow descriptions or amounts.-If you make a mistake, enter < at any prompt to go one step backward.-To end a transaction, enter . when prompted.-To quit, enter . at a date prompt or press control-d or control-c.-Date [2015/05/22]: -Description: supermarket-Account 1: expenses:food-Amount 1: $10-Account 2: assets:checking-Amount 2 [$-10.0]: -Account 3 (or . or enter to finish this transaction): .-2015/05/22 supermarket- expenses:food $10- assets:checking $-10.0--Save this transaction to the journal ? [y]: -Saved.-Starting the next transaction (. or ctrl-D/ctrl-C to quit)-Date [2015/05/22]: <CTRL-D> $-- On Microsoft Windows, the add command makes sure that no part of the-file path ends with a period, as that would cause problems (#1056).---File: hledger.info, Node: aregister, Next: balance, Prev: add, Up: COMMANDS--3.4 aregister-=============--aregister, areg-Show transactions affecting a particular account, and the account's-running balance.-- 'aregister' shows the transactions affecting a particular account-(and its subaccounts), from the point of view of that account. Each-line shows:-- * the transaction's (or posting's, see below) date- * the names of the other account(s) involved- * the net change to this account's balance- * the account's historical running balance (including balance from- transactions before the report start date).-- With 'aregister', each line represents a whole transaction - as in-hledger-ui, hledger-web, and your bank statement. By contrast, the-'register' command shows individual postings, across all accounts. You-might prefer 'aregister' for reconciling with real-world asset/liability-accounts, and 'register' for reviewing detailed revenues/expenses.-- An account must be specified as the first argument, which should be-the full account name or an account pattern (regular expression).-aregister will show transactions in this account (the first one matched)-and any of its subaccounts.-- Any additional arguments form a query which will filter the-transactions shown.-- Transactions making a net change of zero are not shown by default;-add the '-E/--empty' flag to show them.--* Menu:--* aregister and custom posting dates::-* Output format::---File: hledger.info, Node: aregister and custom posting dates, Next: , Up: aregister--3.4.1 aregister and custom posting dates-------------------------------------------Transactions whose date is outside the report period can still be shown,-if they have a posting to this account dated inside the report period.-(And in this case it's the posting date that is shown.) This ensures-that 'aregister' can show an accurate historical running balance,-matching the one shown by 'register -H' with the same arguments.-- To filter strictly by transaction date instead, add the '--txn-dates'-flag. If you use this flag and some of your postings have custom dates,-it's probably best to assume the running balance is wrong.--3.4.2 Output format----------------------This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', and 'json'.-- Examples:-- Show all transactions and historical running balance in the first-account whose name contains "checking":--$ hledger areg checking-- Show transactions and historical running balance in all asset-accounts during july:--$ hledger areg assets date:jul---File: hledger.info, Node: balance, Next: balancesheet, Prev: aregister, Up: COMMANDS--3.5 balance-===========--balance, bal, b-Show accounts and their balances.-- The balance command is hledger's most versatile command. Note,-despite the name, it is not always used for showing real-world account-balances; the more accounting-aware balancesheet and incomestatement may-be more convenient for that.-- By default, it displays all accounts, and each account's change in-balance during the entire period of the journal. Balance changes are-calculated by adding up the postings in each account. You can limit the-postings matched, by a query, to see fewer accounts, changes over a-different time period, changes from only cleared transactions, etc.-- If you include an account's complete history of postings in the-report, the balance change is equivalent to the account's current ending-balance. For a real-world account, typically you won't have all-transactions in the journal; instead you'll have all transactions after-a certain date, and an "opening balances" transaction setting the-correct starting balance on that date. Then the balance command will-show real-world account balances. In some cases the -H/-historical flag-is used to ensure this (more below).-- The balance command can produce several styles of report:--* Menu:--* Classic balance report::-* Customising the classic balance report::-* Colour support::-* Flat mode::-* Depth limited balance reports::-* Percentages::-* Multicolumn balance report::-* Budget report::-* Output format::---File: hledger.info, Node: Classic balance report, Next: Customising the classic balance report, Up: balance--3.5.1 Classic balance report-------------------------------This is the original balance report, as found in Ledger. It usually-looks like this:--$ hledger balance- $-1 assets- $1 bank:saving- $-2 cash- $2 expenses- $1 food- $1 supplies- $-2 income- $-1 gifts- $-1 salary- $1 liabilities:debts---------------------- 0-- By default, accounts are displayed hierarchically, with subaccounts-indented below their parent. At each level of the tree, accounts are-sorted by account code if any, then by account name. Or with-'-S/--sort-amount', by their balance amount, largest first.-- "Boring" accounts, which contain a single interesting subaccount and-no balance of their own, are elided into the following line for more-compact output. (Eg above, the "liabilities" account.) Use-'--no-elide' to prevent this.-- Account balances are "inclusive" - they include the balances of any-subaccounts.-- Accounts which have zero balance (and no non-zero subaccounts) are-omitted. Use '-E/--empty' to show them.-- A final total is displayed by default; use '-N/--no-total' to-suppress it, eg:--$ hledger balance -p 2008/6 expenses --no-total- $2 expenses- $1 food- $1 supplies---File: hledger.info, Node: Customising the classic balance report, Next: Colour support, Prev: Classic balance report, Up: balance--3.5.2 Customising the classic balance report-----------------------------------------------You can customise the layout of classic balance reports with '--format-FMT':--$ hledger balance --format "%20(account) %12(total)"- assets $-1- bank:saving $1- cash $-2- expenses $2- food $1- supplies $1- income $-2- gifts $-1- salary $-1- liabilities:debts $1----------------------------------- 0-- The FMT format string (plus a newline) specifies the formatting-applied to each account/balance pair. It may contain any suitable text,-with data fields interpolated like so:-- '%[MIN][.MAX](FIELDNAME)'-- * MIN pads with spaces to at least this width (optional)-- * MAX truncates at this width (optional)-- * FIELDNAME must be enclosed in parentheses, and can be one of:-- * 'depth_spacer' - a number of spaces equal to the account's- depth, or if MIN is specified, MIN * depth spaces.- * 'account' - the account's name- * 'total' - the account's balance/posted total, right justified-- Also, FMT can begin with an optional prefix to control how-multi-commodity amounts are rendered:-- * '%_' - render on multiple lines, bottom-aligned (the default)- * '%^' - render on multiple lines, top-aligned- * '%,' - render on one line, comma-separated-- There are some quirks. Eg in one-line mode, '%(depth_spacer)' has no-effect, instead '%(account)' has indentation built in. Experimentation-may be needed to get pleasing results.-- Some example formats:-- * '%(total)' - the account's total- * '%-20.20(account)' - the account's name, left justified, padded to- 20 characters and clipped at 20 characters- * '%,%-50(account) %25(total)' - account name padded to 50- characters, total padded to 20 characters, with multiple- commodities rendered on one line- * '%20(total) %2(depth_spacer)%-(account)' - the default format for- the single-column balance report---File: hledger.info, Node: Colour support, Next: Flat mode, Prev: Customising the classic balance report, Up: balance--3.5.3 Colour support-----------------------In terminal output, when colour is enabled, the balance command shows-negative amounts in red.---File: hledger.info, Node: Flat mode, Next: Depth limited balance reports, Prev: Colour support, Up: balance--3.5.4 Flat mode------------------To see a flat list instead of the default hierarchical display, use-'--flat'. In this mode, accounts (unless depth-clipped) show their full-names and "exclusive" balance, excluding any subaccount balances. In-this mode, you can also use '--drop N' to omit the first few account-name components.--$ hledger balance -p 2008/6 expenses -N --flat --drop 1- $1 food- $1 supplies---File: hledger.info, Node: Depth limited balance reports, Next: Percentages, Prev: Flat mode, Up: balance--3.5.5 Depth limited balance reports--------------------------------------With '--depth N' or 'depth:N' or just '-N', balance reports show-accounts only to the specified numeric depth. This is very useful to-summarise a complex set of accounts and get an overview.--$ hledger balance -N -1- $-1 assets- $2 expenses- $-2 income- $1 liabilities-- Flat-mode balance reports, which normally show exclusive balances,-show inclusive balances at the depth limit.---File: hledger.info, Node: Percentages, Next: Multicolumn balance report, Prev: Depth limited balance reports, Up: balance--3.5.6 Percentages--------------------With '-%' or '--percent', balance reports show each account's value-expressed as a percentage of the column's total. This is useful to get-an overview of the relative sizes of account balances. For example to-obtain an overview of expenses:--$ hledger balance expenses -%- 100.0 % expenses- 50.0 % food- 50.0 % supplies---------------------- 100.0 %-- Note that '--tree' does not have an effect on '-%'. The percentages-are always relative to the total sum of each column, they are never-relative to the parent account.-- Since the percentages are relative to the columns sum, it is usually-not useful to calculate percentages if the signs of the amounts are-mixed. Although the results are technically correct, they are most-likely useless. Especially in a balance report that sums up to zero (eg-'hledger balance -B') all percentage values will be zero.-- This flag does not work if the report contains any mixed commodity-accounts. If there are mixed commodity accounts in the report be sure-to use '-V' or '-B' to coerce the report into using a single commodity.---File: hledger.info, Node: Multicolumn balance report, Next: Budget report, Prev: Percentages, Up: balance--3.5.7 Multicolumn balance report-----------------------------------Multicolumn or tabular balance reports are a very useful hledger-feature, and usually the preferred style. They share many of the above-features, but they show the report as a table, with columns representing-time periods. This mode is activated by providing a reporting interval.-- There are three types of multicolumn balance report, showing-different information:-- 1. By default: each column shows the sum of postings in that period,- ie the account's change of balance in that period. This is useful- eg for a monthly income statement:-- $ hledger balance --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 -- 2. With '--cumulative': each column shows the ending balance for that- period, accumulating the changes across periods, starting from 0 at- the report start date:-- $ hledger balance --quarterly income expenses -E --cumulative- Ending balances (cumulative) in 2008:- - || 2008/03/31 2008/06/30 2008/09/30 2008/12/31 - ===================++=================================================- expenses:food || 0 $1 $1 $1 - expenses:supplies || 0 $1 $1 $1 - income:gifts || 0 $-1 $-1 $-1 - income:salary || $-1 $-1 $-1 $-1 - -------------------++-------------------------------------------------- || $-1 0 0 0 -- 3. With '--historical/-H': each column shows the actual historical- ending balance for that period, accumulating the changes across- periods, starting from the actual balance at the report start date.- This is useful eg for a multi-period balance sheet, and when you- are showing only the data after a certain start date:-- $ hledger balance ^assets ^liabilities --quarterly --historical --begin 2008/4/1- Ending balances (historical) in 2008/04/01-2008/12/31:- - || 2008/06/30 2008/09/30 2008/12/31 - ======================++=====================================- assets:bank:checking || $1 $1 0 - assets:bank:saving || $1 $1 $1 - assets:cash || $-2 $-2 $-2 - liabilities:debts || 0 0 $1 - ----------------------++-------------------------------------- || 0 0 0 -- Note that '--cumulative' or '--historical/-H' disable-'--row-total/-T', since summing end balances generally does not make-sense.-- Multicolumn balance reports display accounts in flat mode by default;-to see the hierarchy, use '--tree'.-- With a reporting interval (like '--quarterly' above), the report-start/end dates will be adjusted if necessary so that they encompass the-displayed report periods. This is so that the first and last periods-will be "full" and comparable to the others.-- The '-E/--empty' flag does two things in multicolumn balance reports:-first, the report will show all columns within the specified report-period (without -E, leading and trailing columns with all zeroes are not-shown). Second, all accounts which existed at the report start date-will be considered, not just the ones with activity during the report-period (use -E to include low-activity accounts which would otherwise-would be omitted).-- The '-T/--row-total' flag adds an additional column showing the total-for each row.-- The '-A/--average' flag adds a column showing the average value in-each row.-- Here's an example of all three:--$ hledger balance -Q income expenses --tree -ETA-Balance changes in 2008:-- || 2008q1 2008q2 2008q3 2008q4 Total Average -============++===================================================- expenses || 0 $2 0 0 $2 $1 - food || 0 $1 0 0 $1 0 - supplies || 0 $1 0 0 $1 0 - income || $-1 $-1 0 0 $-2 $-1 - gifts || 0 $-1 0 0 $-1 0 - salary || $-1 0 0 0 $-1 0 -------------++---------------------------------------------------- || $-1 $1 0 0 0 0 --(Average is rounded to the dollar here since all journal amounts are)-- The '--transpose' flag can be used to exchange the rows and columns-of a multicolumn report.-- When showing multicommodity amounts, multicolumn balance reports will-elide any amounts which have more than two commodities, since otherwise-columns could get very wide. The '--no-elide' flag disables this.-Hiding totals with the '-N/--no-total' flag can also help reduce the-width of multicommodity reports.-- When the report is still too wide, a good workaround is to pipe it-into 'less -RS' (-R for colour, -S to chop long lines). Eg: 'hledger-bal -D --color=yes | less -RS'.---File: hledger.info, Node: Budget report, Next: , Prev: Multicolumn balance report, Up: balance--3.5.8 Budget report----------------------With '--budget', extra columns are displayed showing budget goals for-each account and period, if any. Budget goals are defined by periodic-transactions. This is very useful for comparing planned and actual-income, expenses, time usage, etc. -budget is most often combined with-a report interval.-- For example, you can take average monthly expenses in the common-expense categories to construct a minimal monthly budget:--;; Budget-~ monthly- income $2000- expenses:food $400- expenses:bus $50- expenses:movies $30- assets:bank:checking--;; Two months worth of expenses-2017-11-01- income $1950- expenses:food $396- expenses:bus $49- expenses:movies $30- expenses:supplies $20- assets:bank:checking--2017-12-01- income $2100- expenses:food $412- expenses:bus $53- expenses:gifts $100- assets:bank:checking-- You can now see a monthly budget report:--$ hledger balance -M --budget-Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec -======================++====================================================- assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - expenses || $495 [ 103% of $480] $565 [ 118% of $480] - expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50] - expenses:food || $396 [ 99% of $400] $412 [ 103% of $400] - expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30] - income || $1950 [ 98% of $2000] $2100 [ 105% of $2000] -----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0] -- This is different from a normal balance report in several ways:-- * Only accounts with budget goals during the report period are shown,- by default.-- * In each column, in square brackets after the actual amount, budget- goal amounts are shown, and the actual/goal percentage. (Note:- budget goals should be in the same commodity as the actual amount.)-- * All parent accounts are always shown, even in flat mode. Eg- assets, assets:bank, and expenses above.-- * Amounts always include all subaccounts, budgeted or unbudgeted,- even in flat mode.-- This means that the numbers displayed will not always add up! Eg-above, the 'expenses' actual amount includes the gifts and supplies-transactions, but the 'expenses:gifts' and 'expenses:supplies' accounts-are not shown, as they have no budget amounts declared.-- This can be confusing. When you need to make things clearer, use the-'-E/--empty' flag, which will reveal all accounts including unbudgeted-ones, giving the full picture. Eg:--$ hledger balance -M --budget --empty-Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec -======================++====================================================- assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] - expenses || $495 [ 103% of $480] $565 [ 118% of $480] - expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50] - expenses:food || $396 [ 99% of $400] $412 [ 103% of $400] - expenses:gifts || 0 $100 - expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30] - expenses:supplies || $20 0 - income || $1950 [ 98% of $2000] $2100 [ 105% of $2000] -----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0] -- You can roll over unspent budgets to next period with '--cumulative':--$ hledger balance -M --budget --cumulative-Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec -======================++====================================================- assets || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] - assets:bank || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] - assets:bank:checking || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] - expenses || $495 [ 103% of $480] $1060 [ 110% of $960] - expenses:bus || $49 [ 98% of $50] $102 [ 102% of $100] - expenses:food || $396 [ 99% of $400] $808 [ 101% of $800] - expenses:movies || $30 [ 100% of $30] $30 [ 50% of $60] - income || $1950 [ 98% of $2000] $4050 [ 101% of $4000] -----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0] -- For more examples, see Budgeting and Forecasting.--* Menu:--* Nested budgets::---File: hledger.info, Node: Nested budgets, Up: Budget report--3.5.8.1 Nested budgets-......................--You can add budgets to any account in your account hierarchy. If you-have budgets on both parent account and some of its children, then-budget(s) of the child account(s) would be added to the budget of their-parent, much like account balances behave.-- In the most simple case this means that once you add a budget to any-account, all its parents would have budget as well.-- To illustrate this, consider the following budget:--~ monthly from 2019/01- expenses:personal $1,000.00- expenses:personal:electronics $100.00- liabilities-- With this, monthly budget for electronics is defined to be $100 and-budget for personal expenses is an additional $1000, which implicitly-means that budget for both 'expenses:personal' and 'expenses' is $1100.-- Transactions in 'expenses:personal:electronics' will be counted both-towards its $100 budget and $1100 of 'expenses:personal' , and-transactions in any other subaccount of 'expenses:personal' would be-counted towards only towards the budget of 'expenses:personal'.-- For example, let's consider these transactions:--~ monthly from 2019/01- expenses:personal $1,000.00- expenses:personal:electronics $100.00- liabilities--2019/01/01 Google home hub- expenses:personal:electronics $90.00- liabilities $-90.00--2019/01/02 Phone screen protector- expenses:personal:electronics:upgrades $10.00- liabilities--2019/01/02 Weekly train ticket- expenses:personal:train tickets $153.00- liabilities--2019/01/03 Flowers- expenses:personal $30.00- liabilities-- As you can see, we have transactions in-'expenses:personal:electronics:upgrades' and 'expenses:personal:train-tickets', and since both of these accounts are without explicitly-defined budget, these transactions would be counted towards budgets of-'expenses:personal:electronics' and 'expenses:personal' accordingly:--$ hledger balance --budget -M-Budget performance in 2019/01:-- || Jan -===============================++===============================- expenses || $283.00 [ 26% of $1100.00] - expenses:personal || $283.00 [ 26% of $1100.00] - expenses:personal:electronics || $100.00 [ 100% of $100.00] - liabilities || $-283.00 [ 26% of $-1100.00] --------------------------------++-------------------------------- || 0 [ 0] -- And with '--empty', we can get a better picture of budget allocation-and consumption:--$ hledger balance --budget -M --empty-Budget performance in 2019/01:-- || Jan -========================================++===============================- expenses || $283.00 [ 26% of $1100.00] - expenses:personal || $283.00 [ 26% of $1100.00] - expenses:personal:electronics || $100.00 [ 100% of $100.00] - expenses:personal:electronics:upgrades || $10.00 - expenses:personal:train tickets || $153.00 - liabilities || $-283.00 [ 26% of $-1100.00] -----------------------------------------++-------------------------------- || 0 [ 0] --3.5.9 Output format----------------------This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', (multicolumn-non-budget reports only) 'html', and (experimental) 'json'.---File: hledger.info, Node: balancesheet, Next: balancesheetequity, Prev: balance, Up: COMMANDS--3.6 balancesheet-================--balancesheet, bs-This command displays a balance sheet, showing historical ending-balances of asset and liability accounts. (To see equity as well, use-the balancesheetequity command.) Amounts are shown with normal positive-sign, as in conventional financial statements.-- The asset and liability accounts shown are those accounts declared-with the 'Asset' or 'Cash' or 'Liability' type, or otherwise all-accounts under a top-level 'asset' or 'liability' account (case-insensitive, plurals allowed).-- Example:--$ hledger balancesheet-Balance Sheet--Assets:- $-1 assets- $1 bank:saving- $-2 cash---------------------- $-1--Liabilities:- $1 liabilities:debts---------------------- $1--Total:---------------------- 0-- With a reporting interval, multiple columns will be shown, one for-each report period. As with multicolumn balance reports, you can alter-the report mode with '--change'/'--cumulative'/'--historical'. Normally-balancesheet shows historical ending balances, which is what you need-for a balance sheet; note this means it ignores report begin dates (and-'-T/--row-total', since summing end balances generally does not make-sense). Instead of absolute values percentages can be displayed with-'-%'.-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', 'html', and-(experimental) 'json'.---File: hledger.info, Node: balancesheetequity, Next: cashflow, Prev: balancesheet, Up: COMMANDS--3.7 balancesheetequity-======================--balancesheetequity, bse-This command displays a balance sheet, showing historical ending-balances of asset, liability and equity accounts. Amounts are shown-with normal positive sign, as in conventional financial statements.-- The asset, liability and equity accounts shown are those accounts-declared with the 'Asset', 'Cash', 'Liability' or 'Equity' type, or-otherwise all accounts under a top-level 'asset', 'liability' or-'equity' account (case insensitive, plurals allowed).-- Example:--$ hledger balancesheetequity-Balance Sheet With Equity--Assets:- $-2 assets- $1 bank:saving- $-3 cash---------------------- $-2--Liabilities:- $1 liabilities:debts---------------------- $1--Equity:- $1 equity:owner---------------------- $1--Total:---------------------- 0-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', 'html', and-(experimental) 'json'.---File: hledger.info, Node: cashflow, Next: check-dates, Prev: balancesheetequity, Up: COMMANDS--3.8 cashflow-============--cashflow, cf-This command displays a cashflow statement, showing the inflows and-outflows affecting "cash" (ie, liquid) assets. Amounts are shown with-normal positive sign, as in conventional financial statements.-- The "cash" accounts shown are those accounts declared with the 'Cash'-type, or otherwise all accounts under a top-level 'asset' account (case-insensitive, plural allowed) which do not have 'fixed', 'investment',-'receivable' or 'A/R' in their name.-- Example:--$ hledger cashflow-Cashflow Statement--Cash flows:- $-1 assets- $1 bank:saving- $-2 cash---------------------- $-1--Total:---------------------- $-1-- With a reporting interval, multiple columns will be shown, one for-each report period. Normally cashflow shows changes in assets per-period, though as with multicolumn balance reports you can alter the-report mode with '--change'/'--cumulative'/'--historical'. Instead of-absolute values percentages can be displayed with '-%'.-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', 'html', and-(experimental) 'json'.---File: hledger.info, Node: check-dates, Next: check-dupes, Prev: cashflow, Up: COMMANDS--3.9 check-dates-===============--check-dates-Check that transactions are sorted by increasing date. With -date2,-checks secondary dates instead. With -strict, dates must also be-unique. With a query, only matched transactions' dates are checked.-Reads the default journal file, or another specified with -f.---File: hledger.info, Node: check-dupes, Next: close, Prev: check-dates, Up: COMMANDS--3.10 check-dupes-================--check-dupes-Reports account names having the same leaf but different prefixes. In-other words, two or more leaves that are categorized differently. Reads-the default journal file, or another specified as an argument.-- An example: http://stefanorodighiero.net/software/hledger-dupes.html---File: hledger.info, Node: close, Next: codes, Prev: check-dupes, Up: COMMANDS--3.11 close-==========--close, equity-Prints a "closing balances" transaction and an "opening balances"-transaction that bring account balances to and from zero, respectively.-These can be added to your journal file(s), eg to bring asset/liability-balances forward into a new journal file, or to close out-revenues/expenses to retained earnings at the end of a period.-- You can print just one of these transactions by using the '--close'-or '--open' flag. You can customise their descriptions with the-'--close-desc' and '--open-desc' options.-- One amountless posting to "equity:opening/closing balances" is added-to balance the transactions, by default. You can customise this account-name with '--close-acct' and '--open-acct'; if you specify only one of-these, it will be used for both.-- With '--x/--explicit', the equity posting's amount will be shown.-And if it involves multiple commodities, a posting for each commodity-will be shown, as with the print command.-- With '--interleaved', the equity postings are shown next to the-postings they balance, which makes troubleshooting easier.-- By default, transaction prices in the journal are ignored when-generating the closing/opening transactions. With '--show-costs', this-cost information is preserved ('balance -B' reports will be unchanged-after the transition). Separate postings are generated for each cost in-each commodity. Note this can generate very large journal entries, if-you have many foreign currency or investment transactions.--* Menu:--* close usage::---File: hledger.info, Node: close usage, Up: close--3.11.1 close usage---------------------If you split your journal files by time (eg yearly), you will typically-run this command at the end of the year, and save the closing-transaction as last entry of the old file, and the opening transaction-as the first entry of the new file. This makes the files self-contained, so that correct balances are reported no matter which of them-are loaded. Ie, if you load just one file, the balances are initialised-correctly; or if you load several files, the redundant closing/opening-transactions cancel each other out. (They will show up in print or-register reports; you can exclude them with a query like-'not:desc:'(opening|closing) balances''.)-- If you're running a business, you might also use this command to-"close the books" at the end of an accounting period, transferring-income statement account balances to retained earnings. (You may want-to change the equity account name to something like "equity:retained-earnings".)-- By default, the closing transaction is dated yesterday, the balances-are calculated as of end of yesterday, and the opening transaction is-dated today. To close on some other date, use: 'hledger close -e-OPENINGDATE'. Eg, to close/open on the 2018/2019 boundary, use '-e-2019'. You can also use -p or 'date:PERIOD' (any starting date is-ignored).-- Both transactions will include balance assertions for the-closed/reopened accounts. You probably shouldn't use status or realness-filters (like -C or -R or 'status:') with this command, or the generated-balance assertions will depend on these flags. Likewise, if you run-this command with -auto, the balance assertions will probably always-require -auto.-- Examples:-- Carrying asset/liability balances into a new file for 2019:--$ hledger close -f 2018.journal -e 2019 assets liabilities --open- # (copy/paste the output to the start of your 2019 journal file)-$ hledger close -f 2018.journal -e 2019 assets liabilities --close- # (copy/paste the output to the end of your 2018 journal file)-- Now:--$ hledger bs -f 2019.journal # one file - balances are correct-$ hledger bs -f 2018.journal -f 2019.journal # two files - balances still correct-$ hledger bs -f 2018.journal not:desc:closing # to see year-end balances, must exclude closing txn-- Transactions spanning the closing date can complicate matters,-breaking balance assertions:--2018/12/30 a purchase made in 2018, clearing the following year- expenses:food 5- assets:bank:checking -5 ; [2019/1/2]-- Here's one way to resolve that:--; in 2018.journal:-2018/12/30 a purchase made in 2018, clearing the following year- expenses:food 5- liabilities:pending--; in 2019.journal:-2019/1/2 clearance of last year's pending transactions- liabilities:pending 5 = 0- assets:checking---File: hledger.info, Node: codes, Next: commodities, Prev: close, Up: COMMANDS--3.12 codes-==========--codes-List the codes seen in transactions, in the order parsed.-- This command prints the value of each transaction's 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.-- Transactions aren't required to have a code, and missing or empty-codes will not be shown by default. With the '-E'/'--empty' flag, they-will be printed as blank lines.-- You can add a query to select a subset of transactions.-- Examples:--1/1 (123)- (a) 1--1/1 ()- (a) 1--1/1- (a) 1--1/1 (126)- (a) 1--$ hledger codes-123-124-126--$ hledger codes -E-123-124---126---File: hledger.info, Node: commodities, Next: descriptions, Prev: codes, Up: COMMANDS--3.13 commodities-================--commodities-List all commodity/currency symbols used or declared in the journal.---File: hledger.info, Node: descriptions, Next: diff, Prev: commodities, Up: COMMANDS--3.14 descriptions-=================--descriptions-List the unique descriptions that appear in transactions.-- This command lists the unique descriptions that appear in-transactions, in alphabetic order. You can add a query to select a-subset of transactions.-- Example:--$ hledger descriptions-Store Name-Gas Station | Petrol-Person A---File: hledger.info, Node: diff, Next: files, Prev: descriptions, Up: COMMANDS--3.15 diff-=========--diff-Compares a particular account's transactions in two input files. It-shows any transactions to this account which are in one file but not in-the other.-- More precisely, for each posting affecting this account in either-file, it looks for a corresponding posting in the other file which posts-the same amount to the same account (ignoring date, description, etc.)-Since postings not transactions are compared, this also works when-multiple bank transactions have been combined into a single journal-entry.-- This is useful eg if you have downloaded an account's 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.-- Examples:--$ 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:---File: hledger.info, Node: files, Next: help, Prev: diff, Up: COMMANDS--3.16 files-==========--files-List all files included in the journal. With a REGEX argument, only-file names matching the regular expression (case sensitive) are shown.---File: hledger.info, Node: help, Next: import, Prev: files, Up: COMMANDS--3.17 help-=========--help-Show any of the hledger manuals.-- The 'help' command displays any of the main hledger manuals, in one-of several ways. Run it with no argument to list the manuals, or-provide a full or partial manual name to select one.-- hledger manuals are available in several formats. hledger help will-use the first of these display methods that it finds: info, man, $PAGER,-less, stdout (or when non-interactive, just stdout). You can force a-particular viewer with the '--info', '--man', '--pager', '--cat' flags.-- Examples:--$ hledger help-Please choose a manual by typing "hledger help MANUAL" (a substring is ok).-Manuals: hledger hledger-ui hledger-web journal csv timeclock timedot--$ hledger help h --man--hledger(1) hledger User Manuals hledger(1)--NAME- hledger - a command-line accounting tool--SYNOPSIS- hledger [-f FILE] COMMAND [OPTIONS] [ARGS]- hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]- hledger--DESCRIPTION- hledger is a cross-platform program for tracking money, time, or any-...---File: hledger.info, Node: import, Next: incomestatement, Prev: help, Up: COMMANDS--3.18 import-===========--import-Read new transactions added to each FILE since last run, and add them to-the main journal file. Or with -dry-run, just print the transactions-that would be added. Or with -catchup, just mark all of the FILEs'-transactions as imported, without actually importing any.-- The input files are specified as arguments - no need to write -f-before each one. So eg to add new transactions from all CSV files to-the main journal, it's just: 'hledger import *.csv'-- New transactions are detected in the same way as print -new: by-assuming transactions are always added to the input files in increasing-date order, and by saving '.latest.FILE' state files.-- The -dry-run output is in journal format, so you can filter it, eg to-see only uncategorised transactions:--$ hledger import --dry ... | hledger -f- print unknown --ignore-assertions--* Menu:--* Importing balance assignments::---File: hledger.info, Node: Importing balance assignments, Up: import--3.18.1 Importing balance assignments---------------------------------------Entries added by import will have their posting amounts made explicit-(like 'hledger print -x'). This means that any balance assignments in-imported files must be evaluated; but, imported files don't get to see-the main file's account balances. As a result, importing entries with-balance assignments (eg from an institution that provides only balances-and not posting amounts) will probably generate incorrect posting-amounts. To avoid this problem, use print instead of import:--$ hledger print IMPORTFILE [--new] >> $LEDGER_FILE-- (If you think import should leave amounts implicit like print does,-please test it and send a pull request.)---File: hledger.info, Node: incomestatement, Next: notes, Prev: import, Up: COMMANDS--3.19 incomestatement-====================--incomestatement, is-- This command displays an income statement, showing revenues and-expenses during one or more periods. Amounts are shown with normal-positive sign, as in conventional financial statements.-- The revenue and expense accounts shown are those accounts declared-with the 'Revenue' or 'Expense' type, or otherwise all accounts under a-top-level 'revenue' or 'income' or 'expense' account (case insensitive,-plurals allowed).-- Example:--$ hledger incomestatement-Income Statement--Revenues:- $-2 income- $-1 gifts- $-1 salary---------------------- $-2--Expenses:- $2 expenses- $1 food- $1 supplies---------------------- $2--Total:---------------------- 0-- With a reporting interval, multiple columns will be shown, one for-each report period. Normally incomestatement shows revenues/expenses-per period, though as with multicolumn balance reports you can alter the-report mode with '--change'/'--cumulative'/'--historical'. Instead of-absolute values percentages can be displayed with '-%'.-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', 'html', and-(experimental) 'json'.---File: hledger.info, Node: notes, Next: payees, Prev: incomestatement, Up: COMMANDS--3.20 notes-==========--notes-List the unique notes that appear in transactions.-- 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).-- Example:--$ hledger notes-Petrol-Snacks---File: hledger.info, Node: payees, Next: prices, Prev: notes, Up: COMMANDS--3.21 payees-===========--payees-List the unique payee/payer names that appear in transactions.-- This command lists the unique payee/payer names that appear in-transactions, in alphabetic order. You can add a query to select a-subset of transactions. The payee/payer is the part of the transaction-description before a | character (or if there is no |, the whole-description).-- Example:--$ hledger payees-Store Name-Gas Station-Person A---File: hledger.info, Node: prices, Next: print, Prev: payees, Up: COMMANDS--3.22 prices-===========--prices-Print market price directives from the journal. With -costs, also print-synthetic market prices based on transaction prices. With--inverted-costs, also print inverse prices based on transaction prices.-Prices (and postings providing prices) can be filtered by a query.-Price amounts are always displayed with their full precision.---File: hledger.info, Node: print, Next: print-unique, Prev: prices, Up: COMMANDS--3.23 print-==========--print, txns, p-Show transaction journal entries, sorted by date.-- The print command displays full journal entries (transactions) from-the journal file in date order, tidily formatted. With -date2,-transactions are sorted by secondary date instead.-- print's output is always a valid hledger journal.-It preserves all transaction information, but it does not preserve-directives or inter-transaction comments--$ hledger print-2008/01/01 income- assets:bank:checking $1- income:salary $-1--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--2008/12/31 * pay off- liabilities:debts $1- assets:bank:checking $-1-- Normally, the journal entry's explicit or implicit amount style is-preserved. For example, when an amount is omitted in the journal, it-will not appear in the output. Similarly, when a transaction price is-implied but not written, it will not appear in the output. You can use-the '-x'/'--explicit' flag to make all amounts and transaction prices-explicit, which can be useful for troubleshooting or for making your-journal more readable and robust against data entry errors. '-x' is-also implied by using any of '-B','-V','-X','--value'.-- Note, '-x'/'--explicit' will cause postings with a multi-commodity-amount (these can arise when a multi-commodity transaction has an-implicit amount) to be split into multiple single-commodity postings,-keeping the output parseable.-- With '-B'/'--cost', amounts with transaction prices are converted to-cost using that price. This can be used for troubleshooting.-- With '-m'/'--match' and a STR argument, print will show at most one-transaction: the one one whose description is most similar to STR, and-is most recent. STR should contain at least two characters. If there-is no similar-enough match, no transaction will be shown.-- With '--new', for each FILE being read, hledger reads (and writes) a-special state file ('.latest.FILE' in the same directory), containing-the latest transaction date(s) that were seen last time FILE was read.-When this file is found, only transactions with newer dates (and new-transactions on the latest date) are printed. This is useful for-ignoring already-seen entries in import data, such as downloaded CSV-files. Eg:--$ hledger -f bank1.csv print --new-(shows transactions added since last print --new on this file)-- This assumes that transactions added to FILE always have same or-increasing dates, and that transactions on the same day do not get-reordered. See also the import command.-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', and-(experimental) 'json' and 'sql'.-- Here's an example of print's CSV output:--$ hledger print -Ocsv-"txnidx","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","posting-status","posting-comment"-"1","2008/01/01","","","","income","","assets:bank:checking","1","$","","1","",""-"1","2008/01/01","","","","income","","income:salary","-1","$","1","","",""-"2","2008/06/01","","","","gift","","assets:bank:checking","1","$","","1","",""-"2","2008/06/01","","","","gift","","income:gifts","-1","$","1","","",""-"3","2008/06/02","","","","save","","assets:bank:saving","1","$","","1","",""-"3","2008/06/02","","","","save","","assets:bank:checking","-1","$","1","","",""-"4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","","1","",""-"4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","","1","",""-"4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","2","","",""-"5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","","1","",""-"5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","1","","",""-- * There is one CSV record per posting, with the parent transaction's- fields repeated.- * The "txnidx" (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.)- * The amount is separated into "commodity" (the symbol) and "amount"- (numeric quantity) fields.- * The numeric amount is repeated in either the "credit" or "debit"- column, for convenience. (Those names are not accurate in the- accounting sense; it just puts negative amounts under credit and- zero or greater amounts under debit.)---File: hledger.info, Node: print-unique, Next: register, Prev: print, Up: COMMANDS--3.24 print-unique-=================--print-unique-Print transactions which do not reuse an already-seen description.-- Example:--$ cat unique.journal-1/1 test- (acct:one) 1-2/2 test- (acct:two) 2-$ LEDGER_FILE=unique.journal hledger print-unique-(-f option not supported)-2015/01/01 test- (acct:one) 1---File: hledger.info, Node: register, Next: register-match, Prev: print-unique, Up: COMMANDS--3.25 register-=============--register, reg, r-Show postings and their running total.-- The register command displays matched postings, across all accounts,-in date order, with their running total or running historical balance.-(See also the 'aregister' command, which shows matched transactions in a-specific account.)-- register normally shows line per posting, but note that-multi-commodity amounts will occupy multiple lines (one line per-commodity).-- It is typically used with a query selecting a particular account, to-see that account's activity:--$ 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-- With -date2, it shows and sorts by secondary date instead.-- The '--historical'/'-H' 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:--$ 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-- The '--depth' option limits the amount of sub-account detail-displayed.-- The '--average'/'-A' 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 '--empty' (see-below). It is affected by '--historical'. It works best when showing-just one account and one commodity.-- The '--related'/'-r' flag shows the _other_ postings in the-transactions of the postings which would normally be shown.-- The '--invert' flag negates all amounts. For example, it can be used-on an income account where amounts are normally displayed as negative-numbers. It's also useful to show postings on the checking account-together with the related account:--$ hledger register --related --invert assets:checking-- With a reporting interval, register shows summary postings, one per-interval, aggregating the postings to each account:--$ hledger register --monthly income-2008/01 income:salary $-1 $-1-2008/06 income:gifts $-1 $-2-- Periods with no activity, and summary postings with a zero amount,-are not shown by default; use the '--empty'/'-E' flag to see them:--$ 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-- Often, you'll want to see just one line per interval. The '--depth'-option helps with this, causing subaccounts to be aggregated:--$ hledger register --monthly assets --depth 1h-2008/01 assets $1 $1-2008/06 assets $-1 0-2008/12 assets $-1 $-1-- 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.--* Menu:--* Custom register output::---File: hledger.info, Node: Custom register output, Up: register--3.25.1 Custom register output--------------------------------register uses the full terminal width by default, except on windows.-You can override this by setting the 'COLUMNS' environment variable (not-a bash shell variable) or by using the '--width'/'-w' option.-- 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's argument, comma-separated:-'--width W,D' . Here's a diagram (won't display correctly in -help):--<--------------------------------- width (W) ---------------------------------->-date (10) description (D) account (W-41-D) amount (12) balance (12)-DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA-- and some examples:--$ hledger reg # use terminal width (or 80 on windows)-$ hledger reg -w 100 # use width 100-$ COLUMNS=100 hledger reg # set with one-time environment variable-$ export COLUMNS=100; hledger reg # set till session end (or window resize)-$ hledger reg -w 100,40 # set overall width 100, description width 40-$ hledger reg -w $COLUMNS,40 # use terminal width, & description width 40-- This command also supports the output destination and output format-options The output formats supported are 'txt', 'csv', and-(experimental) 'json'.---File: hledger.info, Node: register-match, Next: rewrite, Prev: register, Up: COMMANDS--3.26 register-match-===================--register-match-Print the one posting whose transaction description is closest to DESC,-in the style of the register command. If there are multiple equally-good matches, it shows the most recent. Query options (options, not-arguments) can be used to restrict the search space. Helps-ledger-autosync detect already-seen transactions when importing.---File: hledger.info, Node: rewrite, Next: roi, Prev: register-match, Up: COMMANDS--3.27 rewrite-============--rewrite-Print all transactions, rewriting the postings of matched transactions.-For now the only rewrite available is adding new postings, like print--auto.-- 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's first posting amount.-- Examples:--$ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'-$ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'-$ hledger-rewrite.hs -f rewrites.hledger-- rewrites.hledger may consist of entries like:--= ^income 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-- Note the single quotes to protect the dollar sign from bash, and the-two spaces between account and amount.-- More:--$ hledger rewrite -- [QUERY] --add-posting "ACCT AMTEXPR" ...-$ hledger rewrite -- ^income --add-posting '(liabilities:tax) *.33'-$ hledger rewrite -- expenses:gifts --add-posting '(budget:gifts) *-1"'-$ hledger rewrite -- ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'-- Argument for '--add-posting' option is a usual posting of transaction-with an exception for amount specification. More precisely, you can use-''*'' (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's-commodity.--* Menu:--* Re-write rules in a file::---File: hledger.info, Node: Re-write rules in a file, Up: rewrite--3.27.1 Re-write rules in a file----------------------------------During the run this tool will execute so called "Automated Transactions"-found in any journal it process. I.e instead of specifying this-operations in command line you can put them in a journal file.--$ rewrite-rules.journal-- Make contents look like this:--= ^income- (liabilities:tax) *.33--= expenses:gifts- budget:gifts *-1- assets:budget *1-- Note that ''='' (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.--$ hledger rewrite -- -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal-- This is something similar to the commands pipeline:--$ hledger rewrite -- -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \- | hledger rewrite -- -f - expenses:gifts --add-posting 'budget:gifts *-1' \- --add-posting 'assets:budget *1' \- > rewritten-tidy-output.journal-- It is important to understand that relative order of such entries in-journal is important. You can re-use result of previously added-postings.--* Menu:--* Diff output format::-* rewrite vs print --auto::---File: hledger.info, Node: Diff output format, Next: rewrite vs print --auto, Up: Re-write rules in a file--3.27.1.1 Diff output format-...........................--To use this tool for batch modification of your journal files you may-find useful output in form of unified diff.--$ hledger rewrite -- --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'-- Output might look like:----- /tmp/examples/sample.journal-+++ /tmp/examples/sample.journal-@@ -18,3 +18,4 @@- 2008/01/01 income-- assets:bank:checking $1-+ assets:bank:checking $1- income:salary-+ (liabilities:tax) 0-@@ -22,3 +23,4 @@- 2008/06/01 gift-- assets:bank:checking $1-+ assets:bank:checking $1- income:gifts-+ (liabilities:tax) 0-- If you'll pass this through 'patch' tool you'll 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 '--file' options and 'include' directives inside of these-files.-- Be careful. Whole transaction being re-formatted in a style of-output from 'hledger print'.-- See also:-- https://github.com/simonmichael/hledger/issues/99---File: hledger.info, Node: rewrite vs print --auto, Prev: Diff output format, Up: Re-write rules in a file--3.27.1.2 rewrite vs. print -auto-................................--This command predates print -auto, and currently does much the same-thing, but with these differences:-- * with multiple files, rewrite lets rules in any file affect all- other files. print -auto uses standard directive scoping; rules- affect only child files.-- * rewrite's query limits which transactions can be rewritten; all are- printed. print -auto's query limits which transactions are- printed.-- * rewrite applies rules specified on command line or in the journal.- print -auto applies rules specified in the journal.---File: hledger.info, Node: roi, Next: stats, Prev: rewrite, Up: COMMANDS--3.28 roi-========--roi-Shows the time-weighted (TWR) and money-weighted (IRR) rate of return on-your investments.-- This command assumes that you have account(s) that hold nothing but-your investments and whenever you record current appraisal/valuation of-these investments you offset unrealized profit and loss into account(s)-that, again, hold nothing but unrealized profit and loss.-- Any transactions affecting balance of investment account(s) and not-originating from unrealized profit and loss account(s) are assumed to be-your investments or withdrawals.-- At a minimum, you need to supply a query (which could be just an-account name) to select your investments with '--inv', and another query-to identify your profit and loss transactions with '--pnl'.-- It will compute and display the internalized rate of return (IRR) and-time-weighted rate of return (TWR) for your investments for the time-period requested. Both rates of return are annualized before display,-regardless of the length of reporting interval.---File: hledger.info, Node: stats, Next: tags, Prev: roi, Up: COMMANDS--3.29 stats-==========--stats-Show some journal statistics.-- The stats command displays summary information for the whole journal,-or a matched part of it. With a reporting interval, it shows a report-for each report period.-- Example:--$ hledger stats-Main journal file : /src/hledger/examples/sample.journal-Included journal files : -Transactions span : 2008-01-01 to 2009-01-01 (366 days)-Last transaction : 2008-12-31 (2333 days ago)-Transactions : 5 (0.0 per day)-Transactions last 30 days: 0 (0.0 per day)-Transactions last 7 days : 0 (0.0 per day)-Payees/descriptions : 5-Accounts : 8 (depth 3)-Commodities : 1 ($)-Market prices : 12 ($)-- This command also supports output destination and output format-selection.---File: hledger.info, Node: tags, Next: test, Prev: stats, Up: COMMANDS--3.30 tags-=========--tags-List the unique tag names used in the journal. With a TAGREGEX-argument, only tag names matching the regular expression (case-insensitive) are shown. With QUERY arguments, only transactions-matching the query are considered.-- With the -values flag, the tags' unique values are listed instead.-- With -parsed flag, all tags or values are shown in the order they are-parsed from the input data, including duplicates.-- With -E/-empty, any blank/empty values will also be shown, otherwise-they are omitted.---File: hledger.info, Node: test, Next: Add-on commands, Prev: tags, Up: COMMANDS--3.31 test-=========--test-Run built-in unit tests.-- This command runs the unit tests built in to hledger and hledger-lib,-printing the results on stdout. If any test fails, the exit code will-be non-zero.-- This is mainly used by hledger developers, but you can also use it to-sanity-check the installed hledger executable on your platform. All-tests are expected to pass - if you ever see a failure, please report as-a bug!-- This command also accepts tasty test runner options, written after a-- (double hyphen). Eg to run only the tests in Hledger.Data.Amount,-with ANSI colour codes disabled:--$ hledger test -- -pData.Amount --color=never-- For help on these, see https://github.com/feuerbach/tasty#options-('-- --help' currently doesn't show them).---File: hledger.info, Node: Add-on commands, Prev: test, Up: COMMANDS--3.32 Add-on commands-====================--hledger also searches for external add-on commands, and will include-these in the commands list. These are programs or scripts in your PATH-whose name starts with 'hledger-' and ends with a recognised file-extension (currently: no extension, 'bat','com','exe',-'hs','lhs','pl','py','rb','rkt','sh').-- Add-ons can be invoked like any hledger command, but there are a few-things to be aware of. Eg if the 'hledger-web' add-on is installed,-- * 'hledger -h web' shows hledger's help, while 'hledger web -h' shows- hledger-web's help.-- * Flags specific to the add-on must have a preceding '--' to hide- them from hledger. So 'hledger web --serve --port 9000' will be- rejected; you must use 'hledger web -- --serve --port 9000'.-- * You can always run add-ons directly if preferred: 'hledger-web- --serve --port 9000'.-- Add-ons are a relatively easy way to add local features or experiment-with new ideas. They can be written in any language, but haskell-scripts have a big advantage: they can use the same hledger (and-haskell) library functions that built-in commands do, for command-line-options, journal parsing, reporting, etc.-- Two important add-ons are the hledger-ui and hledger-web user-interfaces. These are maintained and released along with hledger:--* Menu:--* ui::-* web::-* iadd::-* interest::---File: hledger.info, Node: ui, Next: web, Up: Add-on commands--3.32.1 ui------------hledger-ui provides an efficient terminal interface.---File: hledger.info, Node: web, Next: iadd, Prev: ui, Up: Add-on commands--3.32.2 web-------------hledger-web provides a simple web interface.-- Third party add-ons, maintained separately from hledger, include:---File: hledger.info, Node: iadd, Next: interest, Prev: web, Up: Add-on commands--3.32.3 iadd--------------hledger-iadd is a more interactive, terminal UI replacement for the add-command.---File: hledger.info, Node: interest, Prev: iadd, Up: Add-on commands--3.32.4 interest------------------hledger-interest generates interest transactions for an account-according to various schemes.-- A few more experimental or old add-ons can be found in hledger's bin/-directory. These are typically prototypes and not guaranteed to work.---File: hledger.info, Node: ENVIRONMENT, Next: FILES, Prev: COMMANDS, Up: Top--4 ENVIRONMENT-*************--*LEDGER_FILE* The journal file path when not specified with '-f'.-Default: '~/.hledger.journal' (on windows, perhaps-'C:/Users/USER/.hledger.journal').-- A typical value is '~/DIR/YYYY.journal', where DIR is a-version-controlled finance directory and YYYY is the current year. Or-'~/DIR/current.journal', where current.journal is a symbolic link to-YYYY.journal.-- On Mac computers, you can set this and other environment variables in-a more thorough way that also affects applications started from the GUI-(say, an Emacs dock icon). Eg on MacOS Catalina I have a-'~/.MacOSX/environment.plist' file containing--{- "LEDGER_FILE" : "~/finance/current.journal"-}-- To see the effect you may need to 'killall Dock', or reboot.-- *COLUMNS* The screen width used by the register command. Default:-the full terminal width.-- *NO_COLOR* If this variable exists with any value, hledger will not-use ANSI color codes in terminal output. This overrides the--color/-colour option.---File: hledger.info, Node: FILES, Next: LIMITATIONS, Prev: ENVIRONMENT, Up: Top--5 FILES-*******--Reads data from one or more files in hledger journal, timeclock,-timedot, or CSV format specified with '-f', or '$LEDGER_FILE', or-'$HOME/.hledger.journal' (on windows, perhaps-'C:/Users/USER/.hledger.journal').---File: hledger.info, Node: LIMITATIONS, Next: TROUBLESHOOTING, Prev: FILES, Up: Top--6 LIMITATIONS-*************--The need to precede addon command options with '--' when invoked from-hledger is awkward.-- When input data contains non-ascii characters, a suitable system-locale must be configured (or there will be an unhelpful error). Eg on-POSIX, set LANG to something other than C.-- In a Microsoft Windows CMD window, non-ascii characters and colours-are not supported.-- On Windows, non-ascii characters may not display correctly when-running a hledger built in CMD in MSYS/CYGWIN, or vice-versa.-- In a Cygwin/MSYS/Mintty window, the tab key is not supported in-hledger add.-- Not all of Ledger's journal file syntax is supported. See file-format differences.-- On large data files, hledger is slower and uses more memory than-Ledger.---File: hledger.info, Node: TROUBLESHOOTING, Prev: LIMITATIONS, Up: Top--7 TROUBLESHOOTING-*****************--Here are some issues you might encounter when you run hledger (and-remember you can also seek help from the IRC channel, mail list or bug-tracker):-- *Successfully installed, but "No command 'hledger' found"*-stack and cabal install binaries into a special directory, which should-be added to your PATH environment variable. Eg on unix-like systems,-that is ~/.local/bin and ~/.cabal/bin respectively.-- *I set a custom LEDGER_FILE, but hledger is still using the default-file*-'LEDGER_FILE' should be a real environment variable, not just a shell-variable. The command 'env | grep LEDGER_FILE' should show it. You may-need to use 'export'. Here's an explanation.-- *Getting errors like "Illegal byte sequence" or "Invalid or-incomplete multibyte or wide character" or "commitAndReleaseBuffer:-invalid argument (invalid character)"*-Programs compiled with GHC (hledger, haskell build tools, etc.) need to-have a UTF-8-aware locale configured in the environment, otherwise they-will fail with these kinds of errors when they encounter non-ascii-characters.-- To fix it, set the LANG environment variable to some locale which-supports UTF-8. The locale you choose must be installed on your system.-- Here's an example of setting LANG temporarily, on Ubuntu GNU/Linux:--$ file my.journal-my.journal: UTF-8 Unicode text # the file is UTF8-encoded-$ echo $LANG-C # LANG is set to the default locale, which does not support UTF8-$ locale -a # which locales are installed ?-C-en_US.utf8 # here's a UTF8-aware one we can use-POSIX-$ LANG=en_US.utf8 hledger -f my.journal print # ensure it is used for this command-- If available, 'C.UTF-8' will also work. If your preferred locale-isn't listed by 'locale -a', you might need to install it. Eg on-Ubuntu/Debian:--$ apt-get install language-pack-fr-$ locale -a-C-en_US.utf8-fr_BE.utf8-fr_CA.utf8-fr_CH.utf8-fr_FR.utf8-fr_LU.utf8-POSIX-$ LANG=fr_FR.utf8 hledger -f my.journal print-- Here's how you could set it permanently, if you use a bash shell:--$ echo "export LANG=en_US.utf8" >>~/.bash_profile-$ bash --login-- Exact spelling and capitalisation may be important. Note the-difference on MacOS ('UTF-8', not 'utf8'). Some platforms (eg ubuntu)-allow variant spellings, but others (eg macos) require it to be exact:--$ locale -a | grep -iE en_us.*utf-en_US.UTF-8-$ LANG=en_US.UTF-8 hledger -f my.journal print---Tag Table:-Node: Top68-Node: COMMON TASKS2321-Ref: #common-tasks2433-Node: Getting help2840-Ref: #getting-help2972-Node: Constructing command lines3525-Ref: #constructing-command-lines3717-Node: Starting a journal file4414-Ref: #starting-a-journal-file4612-Node: Setting opening balances5800-Ref: #setting-opening-balances5996-Node: Recording transactions9137-Ref: #recording-transactions9317-Node: Reconciling9873-Ref: #reconciling10016-Node: Reporting12273-Ref: #reporting12413-Node: Migrating to a new file16412-Ref: #migrating-to-a-new-file16560-Node: OPTIONS16859-Ref: #options16966-Node: General options17336-Ref: #general-options17461-Node: Command options20767-Ref: #command-options20918-Node: Command arguments21316-Ref: #command-arguments21463-Node: Queries22343-Ref: #queries22498-Node: Special characters in arguments and queries26460-Ref: #special-characters-in-arguments-and-queries26688-Node: More escaping27139-Ref: #more-escaping27301-Node: Even more escaping27597-Ref: #even-more-escaping27791-Node: Less escaping28462-Ref: #less-escaping28624-Node: Unicode characters28869-Ref: #unicode-characters29051-Node: Input files30463-Ref: #input-files30606-Node: Output destination32905-Ref: #output-destination33057-Node: Output format33482-Ref: #output-format33632-Node: Regular expressions35799-Ref: #regular-expressions35956-Node: Smart dates37692-Ref: #smart-dates37843-Node: Report start & end date39204-Ref: #report-start-end-date39376-Node: Report intervals40873-Ref: #report-intervals41038-Node: Period expressions41428-Ref: #period-expressions41588-Node: Depth limiting45920-Ref: #depth-limiting46064-Node: Pivoting46396-Ref: #pivoting46519-Node: Valuation48195-Ref: #valuation48297-Node: -B Cost48986-Ref: #b-cost49090-Node: -V Value49223-Ref: #v-value49369-Node: -X Value in specified commodity49564-Ref: #x-value-in-specified-commodity49763-Node: Valuation date49912-Ref: #valuation-date50080-Node: Market prices50490-Ref: #market-prices50670-Node: --infer-value market prices from transactions51447-Ref: #infer-value-market-prices-from-transactions51696-Node: Valuation commodity52978-Ref: #valuation-commodity53187-Node: Simple valuation examples54413-Ref: #simple-valuation-examples54615-Node: --value Flexible valuation55274-Ref: #value-flexible-valuation55482-Node: More valuation examples57429-Ref: #more-valuation-examples57638-Node: Effect of valuation on reports59643-Ref: #effect-of-valuation-on-reports59831-Node: COMMANDS65352-Ref: #commands65460-Node: accounts66568-Ref: #accounts66666-Node: activity67365-Ref: #activity67475-Node: add67858-Ref: #add67959-Node: aregister70752-Ref: #aregister70864-Node: aregister and custom posting dates72237-Ref: #aregister-and-custom-posting-dates72410-Ref: #output-format-173003-Node: balance73408-Ref: #balance73525-Node: Classic balance report74983-Ref: #classic-balance-report75156-Node: Customising the classic balance report76540-Ref: #customising-the-classic-balance-report76768-Node: Colour support78844-Ref: #colour-support79011-Node: Flat mode79107-Ref: #flat-mode79255-Node: Depth limited balance reports79668-Ref: #depth-limited-balance-reports79853-Node: Percentages80309-Ref: #percentages80475-Node: Multicolumn balance report81612-Ref: #multicolumn-balance-report81792-Node: Budget report87389-Ref: #budget-report87532-Node: Nested budgets92798-Ref: #nested-budgets92910-Ref: #output-format-296391-Node: balancesheet96588-Ref: #balancesheet96724-Node: balancesheetequity98236-Ref: #balancesheetequity98385-Node: cashflow99461-Ref: #cashflow99589-Node: check-dates100805-Ref: #check-dates100932-Node: check-dupes101211-Ref: #check-dupes101337-Node: close101630-Ref: #close101738-Node: close usage103260-Ref: #close-usage103353-Node: codes106166-Ref: #codes106274-Node: commodities106986-Ref: #commodities107113-Node: descriptions107195-Ref: #descriptions107323-Node: diff107627-Ref: #diff107733-Node: files108780-Ref: #files108880-Node: help109027-Ref: #help109127-Node: import110208-Ref: #import110322-Node: Importing balance assignments111215-Ref: #importing-balance-assignments111363-Node: incomestatement112012-Ref: #incomestatement112145-Node: notes113490-Ref: #notes113603-Node: payees113971-Ref: #payees114077-Node: prices114497-Ref: #prices114603-Node: print114944-Ref: #print115054-Node: print-unique119850-Ref: #print-unique119976-Node: register120261-Ref: #register120388-Node: Custom register output124837-Ref: #custom-register-output124966-Node: register-match126303-Ref: #register-match126437-Node: rewrite126788-Ref: #rewrite126903-Node: Re-write rules in a file128758-Ref: #re-write-rules-in-a-file128892-Node: Diff output format130102-Ref: #diff-output-format130271-Node: rewrite vs print --auto131363-Ref: #rewrite-vs.-print---auto131542-Node: roi132098-Ref: #roi132196-Node: stats133208-Ref: #stats133307-Node: tags134095-Ref: #tags134193-Node: test134712-Ref: #test134820-Node: Add-on commands135567-Ref: #add-on-commands135684-Node: ui137027-Ref: #ui137115-Node: web137169-Ref: #web137272-Node: iadd137388-Ref: #iadd137499-Node: interest137581-Ref: #interest137688-Node: ENVIRONMENT137928-Ref: #environment138040-Node: FILES139025-Ref: #files-1139128-Node: LIMITATIONS139341-Ref: #limitations139460-Node: TROUBLESHOOTING140202-Ref: #troubleshooting140315+hledger(1) hledger 1.20+***********************++hledger - a command-line accounting tool++ 'hledger [-f FILE] COMMAND [OPTIONS] [ARGS]'+'hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]'+'hledger'++ hledger is a reliable, 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).++ This is hledger's command-line interface (there are also terminal and+web interfaces). Its basic function is to read a plain text file+describing financial transactions (in accounting terms, a general+journal) and print useful reports on standard output, or export them as+CSV. hledger can also read some other file formats such as CSV files,+translating them to journal format. Additionally, hledger lists other+hledger-* executables found in the user's $PATH and can invoke them as+subcommands.++ hledger reads data from one or more files in hledger journal,+timeclock, timedot, or CSV format specified with '-f', or+'$LEDGER_FILE', or '$HOME/.hledger.journal' (on windows, perhaps+'C:/Users/USER/.hledger.journal'). If using '$LEDGER_FILE', note this+must be a real environment variable, not a shell variable. You can+specify standard input with '-f-'.++ Transactions are dated movements of money between two (or more) named+accounts, and are recorded with journal entries like this:++2015/10/16 bought food+ expenses:food $10+ assets:cash++ For more about this format, see hledger_journal(5).++ Most users use a text editor to edit the journal, usually with an+editor mode such as ledger-mode for added convenience. hledger's+interactive add command is another way to record new transactions.+hledger never changes existing transactions.++ To get started, you can either save some entries like the above in+'~/.hledger.journal', or run 'hledger add' and follow the prompts. Then+try some commands like 'hledger print' or 'hledger balance'. Run+'hledger' with no arguments for a list of commands.++* Menu:++* COMMON TASKS::+* OPTIONS::+* COMMANDS::+* ENVIRONMENT::+* FILES::+* LIMITATIONS::+* TROUBLESHOOTING::+++File: hledger.info, Node: COMMON TASKS, Next: OPTIONS, Prev: Top, Up: Top++1 COMMON TASKS+**************++Here are some quick examples of how to do some basic tasks with hledger.+For more details, see the reference section below, the+hledger_journal(5) manual, or the more extensive docs at+https://hledger.org.++* Menu:++* Getting help::+* Constructing command lines::+* Starting a journal file::+* Setting opening balances::+* Recording transactions::+* Reconciling::+* Reporting::+* Migrating to a new file::+++File: hledger.info, Node: Getting help, Next: Constructing command lines, Up: COMMON TASKS++1.1 Getting help+================++$ hledger # show available commands+$ hledger --help # show common options+$ hledger CMD --help # show common and command options, and command help+$ hledger help # show available manuals/topics+$ hledger help hledger # show hledger manual as info/man/text (auto-chosen)+$ hledger help journal --man # show the journal manual as a man page+$ hledger help --help # show more detailed help for the help command++ Find more docs, chat, mail list, reddit, issue tracker:+https://hledger.org#help-feedback+++File: hledger.info, Node: Constructing command lines, Next: Starting a journal file, Prev: Getting help, Up: COMMON TASKS++1.2 Constructing command lines+==============================++hledger has an extensive and powerful command line interface. We strive+to keep it simple and ergonomic, but you may run into one of the+confusing real world details described in OPTIONS, below. If that+happens, here are some tips that may help:++ * command-specific options must go after the command (it's fine to+ put all options there) ('hledger CMD OPTS ARGS')+ * running add-on executables directly simplifies command line parsing+ ('hledger-ui OPTS ARGS')+ * enclose "problematic" args in single quotes+ * if needed, also add a backslash to hide regular expression+ metacharacters from the shell+ * to see how a misbehaving command is being parsed, add '--debug=2'.+++File: hledger.info, Node: Starting a journal file, Next: Setting opening balances, Prev: Constructing command lines, Up: COMMON TASKS++1.3 Starting a journal file+===========================++hledger looks for your accounting data in a journal file,+'$HOME/.hledger.journal' by default:++$ hledger stats+The hledger journal file "/Users/simon/.hledger.journal" was not found.+Please create it first, eg with "hledger add" or a text editor.+Or, specify an existing journal file with -f or LEDGER_FILE.++ You can override this by setting the 'LEDGER_FILE' environment+variable. It's a good practice to keep this important file under+version control, and to start a new file each year. So you could do+something like this:++$ mkdir ~/finance+$ cd ~/finance+$ git init+Initialized empty Git repository in /Users/simon/finance/.git/+$ touch 2020.journal+$ echo "export LEDGER_FILE=$HOME/finance/2020.journal" >> ~/.bashrc+$ source ~/.bashrc+$ hledger stats+Main file : /Users/simon/finance/2020.journal+Included files : +Transactions span : to (0 days)+Last transaction : none+Transactions : 0 (0.0 per day)+Transactions last 30 days: 0 (0.0 per day)+Transactions last 7 days : 0 (0.0 per day)+Payees/descriptions : 0+Accounts : 0 (depth 0)+Commodities : 0 ()+Market prices : 0 ()+++File: hledger.info, Node: Setting opening balances, Next: Recording transactions, Prev: Starting a journal file, Up: COMMON TASKS++1.4 Setting opening balances+============================++Pick a starting date for which you can look up the balances of some+real-world assets (bank accounts, wallet..) and liabilities (credit+cards..).++ To avoid a lot of data entry, you may want to start with just one or+two accounts, like your checking account or cash wallet; and pick a+recent starting date, like today or the start of the week. You can+always come back later and add more accounts and older transactions, eg+going back to january 1st.++ Add an opening balances transaction to the journal, declaring the+balances on this date. Here are two ways to do it:++ * The first way: open the journal in any text editor and save an+ entry like this:++ 2020-01-01 * opening balances+ assets:bank:checking $1000 = $1000+ assets:bank:savings $2000 = $2000+ assets:cash $100 = $100+ liabilities:creditcard $-50 = $-50+ equity:opening/closing balances++ These are start-of-day balances, ie whatever was in the account at+ the end of the previous day.++ The * after the date is an optional status flag. Here it means+ "cleared & confirmed".++ The currency symbols are optional, but usually a good idea as+ you'll be dealing with multiple currencies sooner or later.++ The = amounts are optional balance assertions, providing extra+ error checking.++ * The second way: run 'hledger add' and follow the prompts to record+ a similar transaction:++ $ hledger add+ Adding transactions to journal file /Users/simon/finance/2020.journal+ Any command line arguments will be used as defaults.+ Use tab key to complete, readline keys to edit, enter to accept defaults.+ An optional (CODE) may follow transaction dates.+ An optional ; COMMENT may follow descriptions or amounts.+ If you make a mistake, enter < at any prompt to go one step backward.+ To end a transaction, enter . when prompted.+ To quit, enter . at a date prompt or press control-d or control-c.+ Date [2020-02-07]: 2020-01-01+ Description: * opening balances+ Account 1: assets:bank:checking+ Amount 1: $1000+ Account 2: assets:bank:savings+ Amount 2 [$-1000]: $2000+ Account 3: assets:cash+ Amount 3 [$-3000]: $100+ Account 4: liabilities:creditcard+ Amount 4 [$-3100]: $-50+ Account 5: equity:opening/closing balances+ Amount 5 [$-3050]: + Account 6 (or . or enter to finish this transaction): .+ 2020-01-01 * opening balances+ assets:bank:checking $1000+ assets:bank:savings $2000+ assets:cash $100+ liabilities:creditcard $-50+ equity:opening/closing balances $-3050+ + Save this transaction to the journal ? [y]: + Saved.+ Starting the next transaction (. or ctrl-D/ctrl-C to quit)+ Date [2020-01-01]: .++ If you're using version control, this could be a good time to commit+the journal. Eg:++$ git commit -m 'initial balances' 2020.journal+++File: hledger.info, Node: Recording transactions, Next: Reconciling, Prev: Setting opening balances, Up: COMMON TASKS++1.5 Recording transactions+==========================++As you spend or receive money, you can record these transactions using+one of the methods above (text editor, hledger add) or by using the+hledger-iadd or hledger-web add-ons, or by using the import command to+convert CSV data downloaded from your bank.++ Here are some simple transactions, see the hledger_journal(5) manual+and hledger.org for more ideas:++2020/1/10 * gift received+ assets:cash $20+ income:gifts++2020.1.12 * farmers market+ expenses:food $13+ assets:cash++2020-01-15 paycheck+ income:salary+ assets:bank:checking $1000+++File: hledger.info, Node: Reconciling, Next: Reporting, Prev: Recording transactions, Up: COMMON TASKS++1.6 Reconciling+===============++Periodically you should reconcile - compare your hledger-reported+balances against external sources of truth, like bank statements or your+bank's 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.++ A typical workflow:++ 1. Reconcile cash. Count what's in your wallet. Compare with what+ hledger reports ('hledger bal cash'). 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+ ('hledger reg cash'). If you can't find the error, add an+ adjustment transaction. Eg if you have $105 after the above, and+ can't explain the missing $2, it could be:++ 2020-01-16 * adjust cash+ assets:cash $-2 = $105+ expenses:misc++ 2. Reconcile checking. Log in to your bank's website. Compare+ today's (cleared) balance with hledger's cleared balance ('hledger+ bal checking -C'). 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 'hledger reg checking -C'. This will be+ easier if you generally record transaction dates quite similar to+ your bank's clearing dates.++ 3. Repeat for other asset/liability accounts.++ Tip: instead of the register command, use hledger-ui to see a+live-updating register while you edit the journal: 'hledger-ui --watch+--register checking -C'++ After reconciling, it could be a good time to mark the reconciled+transactions' status as "cleared and confirmed", if you want to track+that, by adding the '*' marker. Eg in the paycheck transaction above,+insert '*' between '2020-01-15' and 'paycheck'++ If you're using version control, this can be another good time to+commit:++$ git commit -m 'txns' 2020.journal+++File: hledger.info, Node: Reporting, Next: Migrating to a new file, Prev: Reconciling, Up: COMMON TASKS++1.7 Reporting+=============++Here are some basic reports.++ Show all transactions:++$ hledger print+2020-01-01 * opening balances+ assets:bank:checking $1000+ assets:bank:savings $2000+ assets:cash $100+ liabilities:creditcard $-50+ equity:opening/closing balances $-3050++2020-01-10 * gift received+ assets:cash $20+ income:gifts++2020-01-12 * farmers market+ expenses:food $13+ assets:cash++2020-01-15 * paycheck+ income:salary+ assets:bank:checking $1000++2020-01-16 * adjust cash+ assets:cash $-2 = $105+ expenses:misc++ Show account names, and their hierarchy:++$ hledger accounts --tree+assets+ bank+ checking+ savings+ cash+equity+ opening/closing balances+expenses+ food+ misc+income+ gifts+ salary+liabilities+ creditcard++ Show all account totals:++$ hledger balance+ $4105 assets+ $4000 bank+ $2000 checking+ $2000 savings+ $105 cash+ $-3050 equity:opening/closing balances+ $15 expenses+ $13 food+ $2 misc+ $-1020 income+ $-20 gifts+ $-1000 salary+ $-50 liabilities:creditcard+--------------------+ 0++ Show only asset and liability balances, as a flat list, limited to+depth 2:++$ hledger bal assets liabilities --flat -2+ $4000 assets:bank+ $105 assets:cash+ $-50 liabilities:creditcard+--------------------+ $4055++ Show the same thing without negative numbers, formatted as a simple+balance sheet:++$ hledger bs --flat -2+Balance Sheet 2020-01-16++ || 2020-01-16 +========================++============+ Assets || +------------------------++------------+ assets:bank || $4000 + assets:cash || $105 +------------------------++------------+ || $4105 +========================++============+ Liabilities || +------------------------++------------+ liabilities:creditcard || $50 +------------------------++------------+ || $50 +========================++============+ Net: || $4055 ++ The final total is your "net worth" on the end date. (Or use 'bse'+for a full balance sheet with equity.)++ Show income and expense totals, formatted as an income statement:++hledger is +Income Statement 2020-01-01-2020-01-16++ || 2020-01-01-2020-01-16 +===============++=======================+ Revenues || +---------------++-----------------------+ income:gifts || $20 + income:salary || $1000 +---------------++-----------------------+ || $1020 +===============++=======================+ Expenses || +---------------++-----------------------+ expenses:food || $13 + expenses:misc || $2 +---------------++-----------------------+ || $15 +===============++=======================+ Net: || $1005 ++ The final total is your net income during this period.++ Show transactions affecting your wallet, with running total:++$ hledger register cash+2020-01-01 opening balances assets:cash $100 $100+2020-01-10 gift received assets:cash $20 $120+2020-01-12 farmers market assets:cash $-13 $107+2020-01-16 adjust cash assets:cash $-2 $105++ Show weekly posting counts as a bar chart:++$ hledger activity -W+2019-12-30 *****+2020-01-06 ****+2020-01-13 ****+++File: hledger.info, Node: Migrating to a new file, Prev: Reporting, Up: COMMON TASKS++1.8 Migrating to a new file+===========================++At the end of the year, you may want to continue your journal in a new+file, so that old transactions don't slow down or clutter your reports,+and to help ensure the integrity of your accounting history. See the+close command.++ If using version control, don't forget to 'git add' the new file.+++File: hledger.info, Node: OPTIONS, Next: COMMANDS, Prev: COMMON TASKS, Up: Top++2 OPTIONS+*********++* Menu:++* General options::+* Command options::+* Command arguments::+* Queries::+* Special characters in arguments and queries::+* Unicode characters::+* Input files::+* Strict mode::+* Output destination::+* Output format::+* Regular expressions::+* Smart dates::+* Report start & end date::+* Report intervals::+* Period expressions::+* Depth limiting::+* Pivoting::+* Valuation::+++File: hledger.info, Node: General options, Next: Command options, Up: OPTIONS++2.1 General options+===================++To see general usage help, including general options which are supported+by most hledger commands, run 'hledger -h'.++ General help options:++'-h --help'++ show general usage (or after COMMAND, command usage)+'--version'++ show version+'--debug[=N]'++ show debug output (levels 1-9, default: 1)++ General input options:++'-f FILE --file=FILE'++ use a different input file. For stdin, use - (default:+ '$LEDGER_FILE' or '$HOME/.hledger.journal')+'--rules-file=RULESFILE'++ Conversion rules file to use when reading CSV (default: FILE.rules)+'--separator=CHAR'++ Field separator to expect when reading CSV (default: ',')+'--alias=OLD=NEW'++ rename accounts named OLD to NEW+'--anon'++ anonymize accounts and payees+'--pivot FIELDNAME'++ use some other field or tag for the account name+'-I --ignore-assertions'++ disable balance assertion checks (note: does not disable balance+ assignments)+'-s --strict'++ do extra error checking (check that all posted accounts are+ declared)++ General reporting options:++'-b --begin=DATE'++ include postings/txns on or after this date+'-e --end=DATE'++ include postings/txns before this date+'-D --daily'++ multiperiod/multicolumn report by day+'-W --weekly'++ multiperiod/multicolumn report by week+'-M --monthly'++ multiperiod/multicolumn report by month+'-Q --quarterly'++ multiperiod/multicolumn report by quarter+'-Y --yearly'++ multiperiod/multicolumn report by year+'-p --period=PERIODEXP'++ set start date, end date, and/or reporting interval all at once+ using period expressions syntax+'--date2'++ match the secondary date instead (see command help for other+ effects)+'-U --unmarked'++ include only unmarked postings/txns (can combine with -P or -C)+'-P --pending'++ include only pending postings/txns+'-C --cleared'++ include only cleared postings/txns+'-R --real'++ include only non-virtual postings+'-NUM --depth=NUM'++ hide/aggregate accounts or postings more than NUM levels deep+'-E --empty'++ show items with zero amount, normally hidden (and vice-versa in+ hledger-ui/hledger-web)+'-B --cost'++ convert amounts to their cost/selling amount at transaction time+'-V --market'++ convert amounts to their market value in default valuation+ commodities+'-X --exchange=COMM'++ convert amounts to their market value in commodity COMM+'--value'++ convert amounts to cost or market value, more flexibly than+ -B/-V/-X+'--infer-value'++ with -V/-X/-value, also infer market prices from transactions+'--auto'++ apply automated posting rules to modify transactions.+'--forecast'++ generate future transactions from periodic transaction rules, for+ the next 6 months or till report end date. In hledger-ui, also+ make ordinary future transactions visible.+'--color=WHEN (or --colour=WHEN)'++ Should color-supporting commands use ANSI color codes in text+ output. 'auto' (default): whenever stdout seems to be a+ color-supporting terminal. 'always' or 'yes': always, useful eg+ when piping output into 'less -R'. 'never' or 'no': never. A+ NO_COLOR environment variable overrides this.++ When a reporting option appears more than once in the command line,+the last one takes precedence.++ Some reporting options can also be written as query arguments.+++File: hledger.info, Node: Command options, Next: Command arguments, Prev: General options, Up: OPTIONS++2.2 Command options+===================++To see options for a particular command, including command-specific+options, run: 'hledger COMMAND -h'.++ Command-specific options must be written after the command name, eg:+'hledger print -x'.++ Additionally, if the command is an addon, you may need to put its+options after a double-hyphen, eg: 'hledger ui -- --watch'. Or, you can+run the addon executable directly: 'hledger-ui --watch'.+++File: hledger.info, Node: Command arguments, Next: Queries, Prev: Command options, Up: OPTIONS++2.3 Command arguments+=====================++Most hledger commands accept arguments after the command name, which are+often a query, filtering the data in some way.++ You can save a set of command line options/arguments in a file, and+then reuse them by writing '@FILENAME' as a command line argument. Eg:+'hledger bal @foo.args'. (To prevent this, eg if you have an argument+that begins with a literal '@', precede it with '--', eg: 'hledger bal+-- @ARG').++ Inside the argument file, each line should contain just one option or+argument. Avoid the use of spaces, except inside quotes (or you'll see+a confusing error). Between a flag and its argument, use = (or+nothing). Bad:++assets depth:2+-X USD++ Good:++assets+depth:2+-X=USD++ For special characters (see below), use one less level of quoting+than you would at the command prompt. Bad:++-X"$"++ Good:++-X$++ See also: Save frequently used options.+++File: hledger.info, Node: Queries, Next: Special characters in arguments and queries, Prev: Command arguments, Up: OPTIONS++2.4 Queries+===========++One of hledger's strengths is being able to quickly report on precise+subsets of your data. Most commands accept an optional query+expression, written as arguments after the command name, to filter the+data by date, account name or other criteria. The syntax is similar to+a web search: one or more space-separated search terms, quotes to+enclose whitespace, prefixes to match specific fields, a not: prefix to+negate the match.++ We do not yet support arbitrary boolean combinations of search terms;+instead most commands show transactions/postings/accounts which match+(or negatively match):++ * any of the description terms AND+ * any of the account terms AND+ * any of the status terms AND+ * all the other terms.++ The print command instead shows transactions which:++ * match any of the description terms AND+ * have any postings matching any of the positive account terms AND+ * have no postings matching any of the negative account terms AND+ * match all the other terms.++ The following kinds of search terms can be used. Remember these can+also be prefixed with *'not:'*, eg to exclude a particular subaccount.++*'REGEX', 'acct:REGEX'*++ match account names by this regular expression. (With no prefix,+ 'acct:' is assumed.) same as above++*'amt:N, amt:<N, amt:<=N, amt:>N, amt:>=N'*++ match postings with a single-commodity amount that is equal to,+ less than, or greater than N. (Multi-commodity amounts are not+ tested, and will always match.) 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.+*'code:REGEX'*++ match by transaction code (eg check number)+*'cur:REGEX'*++ match postings or transactions including any amounts whose+ currency/commodity symbol is fully matched by REGEX. (For a partial+ match, use '.*REGEX.*'). Note, to match characters which are+ regex-significant, like the dollar sign ('$'), you need to prepend+ '\'. And when using the command line you need to add one more+ level of quoting to hide it from the shell, so eg do: 'hledger+ print cur:'\$'' or 'hledger print cur:\\$'.+*'desc:REGEX'*++ match transaction descriptions.+*'date:PERIODEXPR'*++ match dates within the specified period. PERIODEXPR is a period+ expression (with no report interval). Examples: 'date:2016',+ 'date:thismonth', 'date:2000/2/1-2/15', 'date:lastweek-'. If the+ '--date2' command line flag is present, this matches secondary+ dates instead.+*'date2:PERIODEXPR'*++ match secondary dates within the specified period.+*'depth:N'*++ match (or display, depending on command) accounts at or above this+ depth+*'note:REGEX'*++ match transaction notes (part of description right of '|', or whole+ description when there's no '|')+*'payee:REGEX'*++ match transaction payee/payer names (part of description left of+ '|', or whole description when there's no '|')+*'real:, real:0'*++ match real or virtual postings respectively+*'status:, status:!, status:*'*++ match unmarked, pending, or cleared transactions respectively+*'tag:REGEX[=REGEX]'*++ match by tag name, and optionally also by tag value. Note a tag:+ query is considered to match a transaction if it matches any of the+ postings. Also remember that postings inherit the tags of their+ parent transaction.++ The following special search term is used automatically in+hledger-web, only:++*'inacct:ACCTNAME'*++ tells hledger-web to show the transaction register for this+ account. Can be filtered further with 'acct' etc.++ Some of these can also be expressed as command-line options (eg+'depth:2' is equivalent to '--depth 2'). Generally you can mix options+and query arguments, and the resulting query will be their intersection+(perhaps excluding the '-p/--period' option).+++File: hledger.info, Node: Special characters in arguments and queries, Next: Unicode characters, Prev: Queries, Up: OPTIONS++2.5 Special characters in arguments and queries+===============================================++In shell command lines, option and argument values which contain+"problematic" characters, ie spaces, and also characters significant to+your shell such as '<', '>', '(', ')', '|' and '$', should be escaped by+enclosing them in quotes or by writing backslashes before the+characters. Eg:++ 'hledger register -p 'last year' "accounts receivable+(receivable|payable)" amt:\>100'.++* Menu:++* More escaping::+* Even more escaping::+* Less escaping::+++File: hledger.info, Node: More escaping, Next: Even more escaping, Up: Special characters in arguments and queries++2.5.1 More escaping+-------------------++Characters significant both to the shell and in regular expressions may+need one extra level of escaping. These include parentheses, the pipe+symbol and the dollar sign. Eg, to match the dollar symbol, bash users+should do:++ 'hledger balance cur:'\$''++ or:++ 'hledger balance cur:\\$'+++File: hledger.info, Node: Even more escaping, Next: Less escaping, Prev: More escaping, Up: Special characters in arguments and queries++2.5.2 Even more escaping+------------------------++When hledger runs an addon executable (eg you type 'hledger ui', hledger+runs 'hledger-ui'), it de-escapes command-line options and arguments+once, so you might need to _triple_-escape. Eg in bash, running the ui+command and matching the dollar sign, it's:++ 'hledger ui cur:'\\$''++ or:++ 'hledger ui cur:\\\\$'++ If you asked why _four_ slashes above, this may help:++unescaped: '$'+escaped: '\$'+double-escaped: '\\$'+triple-escaped: '\\\\$'++ (The number of backslashes in fish shell is left as an exercise for+the reader.)++ You can always avoid the extra escaping for addons by running the+addon directly:++ 'hledger-ui cur:\\$'+++File: hledger.info, Node: Less escaping, Prev: Even more escaping, Up: Special characters in arguments and queries++2.5.3 Less escaping+-------------------++Inside an argument file, or in the search field of hledger-ui or+hledger-web, or at a GHCI prompt, you need one less level of escaping+than at the command line. And backslashes may work better than quotes.+Eg:++ 'ghci> :main balance cur:\$'+++File: hledger.info, Node: Unicode characters, Next: Input files, Prev: Special characters in arguments and queries, Up: OPTIONS++2.6 Unicode characters+======================++hledger is expected to handle non-ascii characters correctly:++ * they should be parsed correctly in input files and on the command+ line, by all hledger tools (add, iadd, hledger-web's+ search/add/edit forms, etc.)++ * they should be displayed correctly by all hledger tools, and+ on-screen alignment should be preserved.++ This requires a well-configured environment. Here are some tips:++ * A system locale must be configured, and it must be one that can+ decode the characters being used. In bash, you can set a locale+ like this: 'export LANG=en_US.UTF-8'. There are some more details+ in Troubleshooting. This step is essential - without it, hledger+ will quit on encountering a non-ascii character (as with all+ GHC-compiled programs).++ * your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)+ must support unicode++ * the terminal must be using a font which includes the required+ unicode glyphs++ * the terminal should be configured to display wide characters as+ double width (for report alignment)++ * 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).+++File: hledger.info, Node: Input files, Next: Strict mode, Prev: Unicode characters, Up: OPTIONS++2.7 Input files+===============++hledger reads transactions from a data file (and the add command writes+to it). By default this file is '$HOME/.hledger.journal' (or on+Windows, something like 'C:/Users/USER/.hledger.journal'). You can+override this with the '$LEDGER_FILE' environment variable:++$ setenv LEDGER_FILE ~/finance/2016.journal+$ hledger stats++ or with the '-f/--file' option:++$ hledger -f /some/file stats++ The file name '-' (hyphen) means standard input:++$ cat some.journal | hledger -f-++ Usually the data file is in hledger's journal format, but it can be+in any of the supported file formats, which currently are:++Reader: Reads: Used for file+ extensions:+--------------------------------------------------------------------------+'journal'hledger journal files and some Ledger '.journal' '.j'+ journals, for transactions '.hledger' '.ledger'+'timeclock'timeclock files, for precise time '.timeclock'+ logging+'timedot'timedot files, for approximate time '.timedot'+ logging+'csv' comma/semicolon/tab/other-separated '.csv' '.ssv' '.tsv'+ values, for data import++ hledger detects the format automatically based on the file extensions+shown above. If it can't recognise the file extension, it assumes+'journal' format. So for non-journal files, it's important to use a+recognised file extension, so as to either read successfully or to show+relevant error messages.++ When you can't ensure the right file extension, not to worry: you can+force a specific reader/format by prefixing the file path with the+format and a colon. Eg to read a .dat file as csv:++$ hledger -f csv:/some/csv-file.dat stats+$ echo 'i 2009/13/1 08:00:00' | hledger print -ftimeclock:-++ You can specify multiple '-f' options, to read multiple files as one+big journal. There are some limitations with this:++ * directives in one file will not affect the other files+ * balance assertions will not see any account balances from previous+ files++ If you need either of those things, you can++ * use a single parent file which includes the others+ * or concatenate the files into one before reading, eg: 'cat+ a.journal b.journal | hledger -f- CMD'.+++File: hledger.info, Node: Strict mode, Next: Output destination, Prev: Input files, Up: OPTIONS++2.8 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:++ * Are the input files parseable, with valid syntax ?+ * Are all transactions balanced ?+ * Do all balance assertions pass ?++ With the '-s'/'--strict' flag, additional checks are performed:++ * Are all accounts posted to, declared with an 'account' directive ?+ (Account error checking)+ * Are all commodities declared with a 'commodity' directive ?+ (Commodity error checking)++ See also: https://hledger.org/checking-for-errors.html++ _experimental._+++File: hledger.info, Node: Output destination, Next: Output format, Prev: Strict mode, Up: OPTIONS++2.9 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:++$ hledger print > foo.txt++ Some commands (print, register, stats, the balance commands) also+provide the '-o/--output-file' option, which does the same thing without+needing the shell. Eg:++$ hledger print -o foo.txt+$ hledger print -o - # write to stdout (the default)+++File: hledger.info, Node: Output format, Next: Regular expressions, Prev: Output destination, Up: OPTIONS++2.10 Output format+==================++Some commands (print, register, the balance commands) offer a choice of+output format. In addition to the usual plain text format ('txt'),+there are CSV ('csv'), HTML ('html'), JSON ('json') and SQL ('sql').+This is controlled by the '-O/--output-format' option:++$ hledger print -O csv++ or, by a file extension specified with '-o/--output-file':++$ hledger balancesheet -o foo.html # write HTML to foo.html++ The '-O' option can be used to override the file extension if needed:++$ hledger balancesheet -o foo.txt -O html # write HTML to foo.txt++ Some notes about JSON output:++ * This feature is marked experimental, and not yet much used; you+ should expect our JSON to evolve. Real-world feedback is welcome.++ * Our JSON is rather large and verbose, as it is quite a faithful+ representation of hledger's internal data types. To understand the+ JSON, read the Haskell type definitions, which are mostly in+ https://github.com/simonmichael/hledger/blob/master/hledger-lib/Hledger/Data/Types.hs.++ * hledger represents quantities as Decimal values storing up to 255+ significant digits, eg for repeating decimals. Such numbers can+ arise in practice (from automatically-calculated transaction+ prices), and would break most JSON consumers. So in JSON, we show+ quantities as simple Numbers with at most 10 decimal places. We+ don't limit the number of integer digits, but that part is under+ your control. We hope this approach will not cause problems in+ practice; if you find otherwise, please let us know. (Cf #1195)++ Notes about SQL output:++ * SQL output is also marked experimental, and much like JSON could+ use real-world feedback.++ * SQL output is expected to work with sqlite, MySQL and PostgreSQL++ * SQL output is structured with the expectations that statements will+ be executed in the empty database. If you already have tables+ created via SQL output of hledger, you would probably want to+ either clear tables of existing data (via 'delete' or 'truncate'+ SQL statements) or drop tables completely as otherwise your+ postings will be duped.+++File: hledger.info, Node: Regular expressions, Next: Smart dates, Prev: Output format, Up: OPTIONS++2.11 Regular expressions+========================++hledger uses regular expressions in a number of places:++ * query terms, on the command line and in the hledger-web search+ form: 'REGEX', 'desc:REGEX', 'cur:REGEX', 'tag:...=REGEX'+ * CSV rules conditional blocks: 'if REGEX ...'+ * account alias directives and options: 'alias /REGEX/ =+ REPLACEMENT', '--alias /REGEX/=REPLACEMENT'++ hledger's regular expressions come from the regex-tdfa library. If+they're not doing what you expect, it's important to know exactly what+they support:++ 1. they are case insensitive+ 2. they are infix matching (they do not need to match the entire thing+ being matched)+ 3. they are POSIX ERE (extended regular expressions)+ 4. they also support GNU word boundaries ('\b', '\B', '\<', '\>')+ 5. they do not support backreferences; if you write '\1', it will+ match the digit '1'. Except when doing text replacement, eg in+ account aliases, where backreferences can be used in the+ replacement string to reference capturing groups in the search+ regexp.+ 6. they do not support mode modifiers ('(?s)'), character classes+ ('\w', '\d'), or anything else not mentioned above.++ Some things to note:++ * In the 'alias' directive and '--alias' option, regular expressions+ must be enclosed in forward slashes ('/REGEX/'). Elsewhere in+ hledger, these are not required.++ * In queries, to match a regular expression metacharacter like '$' as+ a literal character, prepend a backslash. Eg to search for amounts+ with the dollar sign in hledger-web, write 'cur:\$'.++ * On the command line, some metacharacters like '$' have a special+ meaning to the shell and so must be escaped at least once more.+ See Special characters.+++File: hledger.info, Node: Smart dates, Next: Report start & end date, Prev: Regular expressions, Up: OPTIONS++2.12 Smart dates+================++hledger's user interfaces accept a flexible "smart date" syntax (unlike+dates in the journal file). Smart dates allow some english words, can+be relative to today's date, and can have less-significant date parts+omitted (defaulting to 1).++ Examples:++'2004/10/1', exact date, several separators allowed. Year+'2004-01-01', is 4+ digits, month is 1-12, day is 1-31+'2004.9.1'+'2004' start of year+'2004/10' start of month+'10/1' month and day in current year+'21' day in current month+'october, oct' start of month in current year+'yesterday, today, -1, 0, 1 days from today+tomorrow'+'last/this/next -1, 0, 1 periods from the current period+day/week/month/quarter/year'+'20181201' 8 digit YYYYMMDD with valid year month and+ day+'201812' 6 digit YYYYMM with valid year and month++ Counterexamples - malformed digit sequences might give surprising+results:++'201813' 6 digits with an invalid month is parsed as start of+ 6-digit year+'20181301' 8 digits with an invalid month is parsed as start of+ 8-digit year+'20181232' 8 digits with an invalid day gives an error+'201801012' 9+ digits beginning with a valid YYYYMMDD gives an error+++File: hledger.info, Node: Report start & end date, Next: Report intervals, Prev: Smart dates, Up: OPTIONS++2.13 Report start & end date+============================++Most hledger reports show the full span of time represented by the+journal data, by default. So, the effective report start and end dates+will be the earliest and latest transaction or posting dates found in+the journal.++ Often you will want to see a shorter time span, such as the current+month. You can specify a start and/or end date using '-b/--begin',+'-e/--end', '-p/--period' or a 'date:' query (described below). All of+these accept the smart date syntax.++ Some notes:++ * As in Ledger, end dates are exclusive, so you need to write the+ date _after_ the last day you want to include.+ * As noted in reporting options: among start/end dates specified with+ _options_, the last (i.e. right-most) option takes precedence.+ * The effective report start and end dates are the intersection of+ the start/end dates from options and that from 'date:' queries.+ That is, 'date:2019-01 date:2019 -p'2000 to 2030'' yields January+ 2019, the smallest common time span.++ Examples:++'-b begin on St. Patrick's day 2016+2016/3/17'+'-e 12/1' end at the start of december 1st of the current year+ (11/30 will be the last date included)+'-b all transactions on or after the 1st of the current month+thismonth'+'-p all transactions in the current month+thismonth'+'date:2016/3/17..'the above written as queries instead ('..' can also be+ replaced with '-')+'date:..12/1'+'date:thismonth..'+'date:thismonth'+++File: hledger.info, Node: Report intervals, Next: Period expressions, Prev: Report start & end date, Up: OPTIONS++2.14 Report intervals+=====================++A report interval can be specified so that commands like register,+balance and activity will divide their reports into multiple subperiods.+The basic intervals can be selected with one of '-D/--daily',+'-W/--weekly', '-M/--monthly', '-Q/--quarterly', or '-Y/--yearly'. More+complex intervals may be specified with a period expression. Report+intervals can not be specified with a query.+++File: hledger.info, Node: Period expressions, Next: Depth limiting, Prev: Report intervals, Up: OPTIONS++2.15 Period expressions+=======================++The '-p/--period' option accepts period expressions, a shorthand way of+expressing a start date, end date, and/or report interval all at once.++ Here's a basic period expression specifying the first quarter of+2009. Note, hledger always treats start dates as inclusive and end+dates as exclusive:++ '-p "from 2009/1/1 to 2009/4/1"'++ Keywords like "from" and "to" are optional, and so are the spaces, as+long as you don't run two dates together. "to" can also be written as+".." or "-". These are equivalent to the above:++'-p "2009/1/1 2009/4/1"'+'-p2009/1/1to2009/4/1'+'-p2009/1/1..2009/4/1'++ Dates are smart dates, so if the current year is 2009, the above can+also be written as:++'-p "1/1 4/1"'+'-p "january-apr"'+'-p "this year to 4/1"'++ If you specify only one date, the missing start or end date will be+the earliest or latest transaction in your journal:++'-p "from 2009/1/1"' everything after january 1, 2009+'-p "from 2009/1"' the same+'-p "from 2009"' the same+'-p "to 2009"' everything before january 1, 2009++ A single date with no "from" or "to" defines both the start and end+date like so:++'-p "2009"' the year 2009; equivalent to “2009/1/1 to 2010/1/1”+'-p "2009/1"' the month of jan; equivalent to “2009/1/1 to 2009/2/1”+'-p "2009/1/1"' just that day; equivalent to “2009/1/1 to 2009/1/2”++ Or you can specify a single quarter like so:++'-p "2009Q1"' first quarter of 2009, equivalent to “2009/1/1 to 2009/4/1”+'-p "q4"' fourth quarter of the current year++ The argument of '-p' can also begin with, or be, a report interval+expression. The basic report intervals are 'daily', 'weekly',+'monthly', 'quarterly', or 'yearly', which have the same effect as the+'-D','-W','-M','-Q', or '-Y' flags. Between report interval and+start/end dates (if any), the word 'in' is optional. Examples:++'-p "weekly from 2009/1/1 to 2009/4/1"'+'-p "monthly in 2008"'+'-p "quarterly"'++ Note that 'weekly', 'monthly', 'quarterly' and 'yearly' intervals+will always start on the first day on week, month, quarter or year+accordingly, and will end on the last day of same period, even if+associated period expression specifies different explicit start and end+date.++ For example:++'-p "weekly from starts on 2008/12/29, closest preceding+2009/1/1 to 2009/4/1"' Monday+'-p "monthly in starts on 2018/11/01+2008/11/25"'+'-p "quarterly from starts on 2009/04/01, ends on 2009/06/30,+2009-05-05 to which are first and last days of Q2 2009+2009-06-01"'+'-p "yearly from starts on 2009/01/01, first day of 2009+2009-12-29"'++ The following more complex report intervals are also supported:+'biweekly', 'fortnightly', 'bimonthly', 'every+day|week|month|quarter|year', 'every N+days|weeks|months|quarters|years'.++ All of these will start on the first day of the requested period and+end on the last one, as described above.++ Examples:++'-p "bimonthly from periods will have boundaries on 2008/01/01,+2008"' 2008/03/01, ...+'-p "every 2 weeks"' starts on closest preceding Monday+'-p "every 5 month from periods will have boundaries on 2009/03/01,+2009/03"' 2009/08/01, ...++ If you want intervals that start on arbitrary day of your choosing+and span a week, month or year, you need to use any of the following:++ 'every Nth day of week', 'every WEEKDAYNAME' (eg+'mon|tue|wed|thu|fri|sat|sun'), 'every Nth day [of month]', 'every Nth+WEEKDAYNAME [of month]', 'every MM/DD [of year]', 'every Nth MMM [of+year]', 'every MMM Nth [of year]'.++ Examples:++'-p "every 2nd day of periods will go from Tue to Tue+week"'+'-p "every Tue"' same+'-p "every 15th day"' period boundaries will be on 15th of each+ month+'-p "every 2nd period boundaries will be on second Monday of+Monday"' each month+'-p "every 11/05"' yearly periods with boundaries on 5th of Nov+'-p "every 5th Nov"' same+'-p "every Nov 5th"' same++ Show historical balances at end of 15th each month (N is exclusive+end date):++ 'hledger balance -H -p "every 16th day"'++ Group postings from start of wednesday to end of next tuesday (N is+start date and exclusive end date):++ 'hledger register checking -p "every 3rd day of week"'+++File: hledger.info, Node: Depth limiting, Next: Pivoting, Prev: Period expressions, Up: OPTIONS++2.16 Depth limiting+===================++With the '--depth N' option (short form: '-N'), commands like account,+balance and register will show only the uppermost accounts in the+account tree, down to level N. Use this when you want a summary with+less detail. This flag has the same effect as a 'depth:' query argument+(so '-2', '--depth=2' or 'depth:2' are equivalent).+++File: hledger.info, Node: Pivoting, Next: Valuation, Prev: Depth limiting, Up: OPTIONS++2.17 Pivoting+=============++Normally hledger sums amounts, and organizes them in a hierarchy, based+on account name. The '--pivot FIELD' option causes it to sum and+organize hierarchy based on the value of some other field instead.+FIELD can be: 'code', 'description', 'payee', 'note', or the full name+(case insensitive) of any tag. As with account names, values containing+'colon:separated:parts' will be displayed hierarchically in reports.++ '--pivot' is a general option affecting all reports; you can think of+hledger transforming the journal before any other processing, replacing+every posting's account name with the value of the specified field on+that posting, inheriting it from the transaction or using a blank value+if it's not present.++ An example:++2016/02/16 Member Fee Payment+ assets:bank account 2 EUR+ income:member fees -2 EUR ; member: John Doe++ Normal balance report showing account names:++$ hledger balance+ 2 EUR assets:bank account+ -2 EUR income:member fees+--------------------+ 0++ Pivoted balance report, using member: tag values instead:++$ hledger balance --pivot member+ 2 EUR+ -2 EUR John Doe+--------------------+ 0++ One way to show only amounts with a member: value (using a query,+described below):++$ hledger balance --pivot member tag:member=.+ -2 EUR John Doe+--------------------+ -2 EUR++ Another way (the acct: query matches against the pivoted "account+name"):++$ hledger balance --pivot member acct:.+ -2 EUR John Doe+--------------------+ -2 EUR+++File: hledger.info, Node: Valuation, Prev: Pivoting, Up: OPTIONS++2.18 Valuation+==============++Instead of reporting amounts in their original commodity, hledger can+convert them to cost/sale amount (using the conversion rate recorded in+the transaction), or to market value (using some market price on a+certain date). This is controlled by the '--value=TYPE[,COMMODITY]'+option, but we also provide the simpler '-B'/'-V'/'-X' flags, and+usually one of those is all you need.++* Menu:++* -B Cost::+* -V Value::+* -X Value in specified commodity::+* Valuation date::+* Market prices::+* --infer-value market prices from transactions::+* Valuation commodity::+* Simple valuation examples::+* --value Flexible valuation::+* More valuation examples::+* Effect of valuation on reports::+++File: hledger.info, Node: -B Cost, Next: -V Value, Up: Valuation++2.18.1 -B: Cost+---------------++The '-B/--cost' flag converts amounts to their cost or sale amount at+transaction time, if they have a transaction price specified.+++File: hledger.info, Node: -V Value, Next: -X Value in specified commodity, Prev: -B Cost, Up: Valuation++2.18.2 -V: Value+----------------++The '-V/--market' flag converts amounts to market value in their default+_valuation commodity_, using the market prices in effect on the+_valuation date(s)_, if any. More on these in a minute.+++File: hledger.info, Node: -X Value in specified commodity, Next: Valuation date, Prev: -V Value, Up: Valuation++2.18.3 -X: Value in specified commodity+---------------------------------------++The '-X/--exchange=COMM' option is like '-V', except you tell it which+currency you want to convert to, and it tries to convert everything to+that.+++File: hledger.info, Node: Valuation date, Next: Market prices, Prev: -X Value in specified commodity, Up: Valuation++2.18.4 Valuation date+---------------------++Since market prices can change from day to day, market value reports+have a valuation date (or more than one), which determines which market+prices will be used.++ For single period reports, if an explicit report end date is+specified, that will be used as the valuation date; otherwise the+valuation date is "today".++ For multiperiod reports, each column/period is valued on the last day+of the period, by default.+++File: hledger.info, Node: Market prices, Next: --infer-value market prices from transactions, Prev: Valuation date, Up: Valuation++2.18.5 Market prices+--------------------++_(experimental)_++ 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 :++ 1. A _declared market price_ or _inferred market price_: A's latest+ market price in B on or before the valuation date as declared by a+ P directive, or (with the '--infer-value' flag) inferred from+ transaction prices.++ 2. A _reverse market price_: the inverse of a declared or inferred+ market price from B to A.++ 3. A _a forward chain of market prices_: a synthetic price formed by+ combining the shortest chain of "forward" (only 1 above) market+ prices, leading from A to B.++ 4. A _any chain of market prices_: a chain of any market prices,+ including both forward and reverse prices (1 and 2 above), leading+ from A to B.++ Amounts for which no applicable market price can be found, are not+converted.+++File: hledger.info, Node: --infer-value market prices from transactions, Next: Valuation commodity, Prev: Market prices, Up: Valuation++2.18.6 -infer-value: market prices from transactions+----------------------------------------------------++_(experimental)_++ 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 transaction prices as additional+market prices (as Ledger does) ? We could produce value reports without+needing P directives at all.++ Adding the '--infer-value' flag to '-V', '-X' or '--value' enables+this. So for example, 'hledger bs -V --infer-value' will get market+prices both from P directives and from transactions.++ 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 Valuation section carefully, and try adding+'--debug' or '--debug=2' to troubleshoot.++ '--infer-value' can infer market prices from:++ * multicommodity transactions with explicit prices ('@'/'@@')++ * multicommodity transactions with implicit prices (no '@', two+ commodities, unbalanced). (With these, the order of postings+ matters. 'hledger print -x' can be useful for troubleshooting.)++ * but not, currently, from "more correct" multicommodity transactions+ (no '@', multiple commodities, balanced).+++File: hledger.info, Node: Valuation commodity, Next: Simple valuation examples, Prev: --infer-value market prices from transactions, Up: Valuation++2.18.7 Valuation commodity+--------------------------++_(experimental)_++ *When you specify a valuation commodity ('-X COMM' or '--value+TYPE,COMM'):*+hledger will convert all amounts to COMM, wherever it can find a+suitable market price (including by reversing or chaining prices).++ *When you leave the valuation commodity unspecified ('-V' or '--value+TYPE'):*+For each commodity A, hledger picks a default valuation commodity as+follows, in this order of preference:++ 1. The price commodity from the latest P-declared market price for A+ on or before valuation date.++ 2. 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.)++ 3. If there are no P directives at all (any commodity or date) and the+ '--infer-value' flag is used: the price commodity from the latest+ transaction-inferred price for A on or before valuation date.++ This means:++ * If you have P directives, they determine which commodities '-V'+ will convert, and to what.++ * If you have no P directives, and use the '--infer-value' flag,+ transaction prices determine it.++ Amounts for which no valuation commodity can be found are not+converted.+++File: hledger.info, Node: Simple valuation examples, Next: --value Flexible valuation, Prev: Valuation commodity, Up: Valuation++2.18.8 Simple valuation examples+--------------------------------++Here are some quick examples of '-V':++; 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++ How many euros do I have ?++$ hledger -f t.j bal -N euros+ €100 assets:euros++ What are they worth at end of nov 3 ?++$ hledger -f t.j bal -N euros -V -e 2016/11/4+ $110.00 assets:euros++ What are they worth after 2016/12/21 ? (no report end date+specified, defaults to today)++$ hledger -f t.j bal -N euros -V+ $103.00 assets:euros+++File: hledger.info, Node: --value Flexible valuation, Next: More valuation examples, Prev: Simple valuation examples, Up: Valuation++2.18.9 -value: Flexible valuation+---------------------------------++'-B', '-V' and '-X' are special cases of the more general '--value'+option:++ --value=TYPE[,COMM] TYPE is cost, then, end, now or YYYY-MM-DD.+ COMM is an optional commodity symbol.+ Shows amounts converted to:+ - cost commodity using transaction prices (then optionally to COMM using market prices at period end(s))+ - 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++ The TYPE part selects cost or value and valuation date:++'--value=cost'++ Convert amounts to cost, using the prices recorded in transactions.+'--value=then'++ Convert amounts to their value in the default valuation commodity,+ using market prices on each posting's date. This is currently+ supported only by the print and register commands.+'--value=end'++ 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's end date); or in multiperiod reports,+ market prices on the last day of each subperiod.+'--value=now'++ Convert amounts to their value in the default valuation commodity+ using current market prices (as of when report is generated).+'--value=YYYY-MM-DD'++ Convert amounts to their value in the default valuation commodity+ using market prices on this date.++ To select a different valuation commodity, add the optional ',COMM'+part: a comma, then the target commodity's symbol. Eg:+*'--value=now,EUR'*. hledger will do its best to convert amounts to+this commodity, deducing market prices as described above.+++File: hledger.info, Node: More valuation examples, Next: Effect of valuation on reports, Prev: --value Flexible valuation, Up: Valuation++2.18.10 More valuation examples+-------------------------------++Here are some examples showing the effect of '--value', as seen with+'print':++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 @ 5 B++2000-02-01+ (a) 1 A @ 6 B++2000-03-01+ (a) 1 A @ 7 B++ Show the cost of each posting:++$ hledger -f- print --value=cost+2000-01-01+ (a) 5 B++2000-02-01+ (a) 6 B++2000-03-01+ (a) 7 B++ Show the value as of the last day of the report period (2000-02-29):++$ hledger -f- print --value=end date:2000/01-2000/03+2000-01-01+ (a) 2 B++2000-02-01+ (a) 2 B++ With no report period specified, that shows the value as of the last+day of the journal (2000-03-01):++$ hledger -f- print --value=end+2000-01-01+ (a) 3 B++2000-02-01+ (a) 3 B++2000-03-01+ (a) 3 B++ Show the current value (the 2000-04-01 price is still in effect+today):++$ hledger -f- print --value=now+2000-01-01+ (a) 4 B++2000-02-01+ (a) 4 B++2000-03-01+ (a) 4 B++ Show the value on 2000/01/15:++$ 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++ You may need to explicitly set a commodity's display style, when+reverse prices are used. Eg this output might be surprising:++P 2000-01-01 A 2B++2000-01-01+ a 1B+ b++$ hledger print -x -X A+2000-01-01+ a 0+ b 0++ Explanation: because there's no amount or commodity directive+specifying a display style for A, 0.5A gets the default style, which+shows no decimal digits. Because the displayed amount looks like zero,+the commodity symbol and minus sign are not displayed either. Adding a+commodity directive sets a more useful display style for A:++P 2000-01-01 A 2B+commodity 0.00A++2000-01-01+ a 1B+ b++$ hledger print -X A+2000-01-01+ a 0.50A+ b -0.50A+++File: hledger.info, Node: Effect of valuation on reports, Prev: More valuation examples, Up: Valuation++2.18.11 Effect of valuation on reports+--------------------------------------++Here is a reference for how valuation is supposed to affect each part of+hledger's reports (and a glossary). (It's wide, you'll have to scroll+sideways.) It may be useful when troubleshooting. If you find+problems, please report them, ideally with a reproducible example.+Related: #329, #1083.++Report '-B', '-V', '-X' '--value=then''--value=end' '--value=DATE',+type '--value=cost' '--value=now'+--------------------------------------------------------------------------------+*print*+posting cost value at value at value at value+amounts report end posting report or at+ or today date journal end DATE/today+balance unchanged unchanged unchanged unchanged unchanged+assertions/assignments+*register*+starting cost value at day not value at day value+balance before supported before at+(-H) report or report or DATE/today+ journal journal+ start start+posting cost value at value at value at value+amounts report end posting report or at+ or today date journal end DATE/today+summary summarised value at sum of value at value+posting cost period ends postings period ends at+amounts in DATE/today+with interval,+report valued at+interval interval+ start+running sum/average sum/average sum/average sum/average sum/average+total/averageof displayed of displayed of of displayed of+ values values displayed values displayed+ values values+*balance+(bs, bse,+cf, is)*+balance sums of value at not value at value+changes costs report end supported report or at+ or today of journal end DATE/today+ sums of of sums of of sums+ postings postings of+ postings+budget like balance like balance not like like+amounts changes changes supported balances balance+(-budget) changes+grand sum of sum of not sum of sum of+total displayed displayed supported displayed displayed+ values values values values+*balance+(bs, bse,+cf, is)+with+report+interval*+starting sums of value at not value at sums of+balances costs of report start supported report start postings+(-H) postings of sums of of sums of before+ before all postings all postings report+ report start before before start+ report start report start+balance sums of same as not balance value+changes costs of -value=end supported change in at+(bal, is, postings in each period, DATE/today+bs period valued at of sums+-change, period ends of+cf postings+-change)+end sums of same as not period end value+balances costs of -value=end supported balances, at+(bal -H, postings valued at DATE/today+is -H, from before period ends of sums+bs, cf) report start of+ to period postings+ end+budget like balance like balance not like like+amounts changes/end changes/end supported balances balance+(-budget) balances balances changes/end+ balances+row sums, sums, not sums, sums,+totals, averages of averages of supported averages of averages+row displayed displayed displayed of+averages values values values displayed+(-T, -A) values+column sums of sums of not sums of sums of+totals displayed displayed supported displayed displayed+ values values values values+grand sum, average sum, average not sum, average sum,+total, of column of column supported of column average+grand totals totals totals of+average column+ totals++ '--cumulative' is omitted to save space, it works like '-H' but with+a zero starting balance.++ *Glossary:*++_cost_++ calculated using price(s) recorded in the transaction(s).+_value_++ market value using available market price declarations, or the+ unchanged amount if no conversion rate can be found.+_report start_++ the first day of the report period specified with -b or -p or+ date:, otherwise today.+_report or journal start_++ the first day of the report period specified with -b or -p or+ date:, otherwise the earliest transaction date in the journal,+ otherwise today.+_report end_++ the last day of the report period specified with -e or -p or date:,+ otherwise today.+_report or journal end_++ the last day of the report period specified with -e or -p or date:,+ otherwise the latest transaction date in the journal, otherwise+ today.+_report interval_++ a flag (-D/-W/-M/-Q/-Y) or period expression that activates the+ report's multi-period mode (whether showing one or many+ subperiods).+++File: hledger.info, Node: COMMANDS, Next: ENVIRONMENT, Prev: OPTIONS, Up: Top++3 COMMANDS+**********++hledger provides a number of subcommands; 'hledger' with no arguments+shows a list.++ If you install additional 'hledger-*' packages, or if you put+programs or scripts named 'hledger-NAME' in your PATH, these will also+be listed as subcommands.++ Run a subcommand by writing its name as first argument (eg 'hledger+incomestatement'). You can also write one of the standard short aliases+displayed in parentheses in the command list ('hledger b'), or any any+unambiguous prefix of a command name ('hledger inc').++ Here are all the builtin commands in alphabetical order. See also+'hledger' for a more organised command list, and 'hledger CMD -h' for+detailed command help.++* Menu:++* accounts::+* activity::+* add::+* aregister::+* balance::+* balancesheet::+* balancesheetequity::+* cashflow::+* check::+* close::+* codes::+* commodities::+* descriptions::+* diff::+* files::+* help::+* import::+* incomestatement::+* notes::+* payees::+* prices::+* print::+* print-unique::+* register::+* register-match::+* rewrite::+* roi::+* stats::+* tags::+* test::+* Add-on commands::+++File: hledger.info, Node: accounts, Next: activity, Up: COMMANDS++3.1 accounts+============++accounts, a+Show account names.++ This command lists account names, either declared with account+directives (-declared), posted to (-used), or both (the default). With+query arguments, only matched account names and account names referenced+by matched postings are shown. It shows a flat list by default. With+'--tree', it uses indentation to show the account hierarchy. In flat+mode you can add '--drop N' to omit the first few account name+components. Account names can be depth-clipped with 'depth:N' or+'--depth N' or '-N'.++ Examples:++$ hledger accounts+assets:bank:checking+assets:bank:saving+assets:cash+expenses:food+expenses:supplies+income:gifts+income:salary+liabilities:debts+++File: hledger.info, Node: activity, Next: add, Prev: accounts, Up: COMMANDS++3.2 activity+============++activity+Show an ascii barchart of posting counts per interval.++ The activity command displays an ascii histogram showing transaction+counts by day, week, month or other reporting interval (by day is the+default). With query arguments, it counts only matched transactions.++ Examples:++$ hledger activity --quarterly+2008-01-01 **+2008-04-01 *******+2008-07-01 +2008-10-01 **+++File: hledger.info, Node: add, Next: aregister, Prev: activity, Up: COMMANDS++3.3 add+=======++add+Prompt for transactions and add them to the journal. Any arguments will+be used as default inputs for the first N prompts.++ Many hledger users edit their journals directly with a text editor,+or generate them from CSV. For more interactive data entry, there is the+'add' command, which prompts interactively on the console for new+transactions, and appends them to the journal file (if there are+multiple '-f FILE' options, the first file is used.) Existing+transactions are not changed. This is the only hledger command that+writes to the journal file.++ To use it, just run 'hledger add' and follow the prompts. You can+add as many transactions as you like; when you are finished, enter '.'+or press control-d or control-c to exit.++ Features:++ * add tries to provide useful defaults, using the most similar (by+ description) recent transaction (filtered by the query, if any) as+ a template.+ * You can also set the initial defaults with command line arguments.+ * Readline-style edit keys can be used during data entry.+ * The tab key will auto-complete whenever possible - accounts,+ descriptions, dates ('yesterday', 'today', 'tomorrow'). If the+ input area is empty, it will insert the default value.+ * If the journal defines a default commodity, it will be added to any+ bare numbers entered.+ * A parenthesised transaction code may be entered following a date.+ * Comments and tags may be entered following a description or amount.+ * If you make a mistake, enter '<' at any prompt to go one step+ backward.+ * Input prompts are displayed in a different colour when the terminal+ supports it.++ Example (see the tutorial for a detailed explanation):++$ hledger add+Adding transactions to journal file /src/hledger/examples/sample.journal+Any command line arguments will be used as defaults.+Use tab key to complete, readline keys to edit, enter to accept defaults.+An optional (CODE) may follow transaction dates.+An optional ; COMMENT may follow descriptions or amounts.+If you make a mistake, enter < at any prompt to go one step backward.+To end a transaction, enter . when prompted.+To quit, enter . at a date prompt or press control-d or control-c.+Date [2015/05/22]: +Description: supermarket+Account 1: expenses:food+Amount 1: $10+Account 2: assets:checking+Amount 2 [$-10.0]: +Account 3 (or . or enter to finish this transaction): .+2015/05/22 supermarket+ expenses:food $10+ assets:checking $-10.0++Save this transaction to the journal ? [y]: +Saved.+Starting the next transaction (. or ctrl-D/ctrl-C to quit)+Date [2015/05/22]: <CTRL-D> $++ On Microsoft Windows, the add command makes sure that no part of the+file path ends with a period, as that would cause problems (#1056).+++File: hledger.info, Node: aregister, Next: balance, Prev: add, Up: COMMANDS++3.4 aregister+=============++aregister, areg+Show transactions affecting a particular account, and the account's+running balance.++ 'aregister' shows the transactions affecting a particular account+(and its subaccounts), from the point of view of that account. Each+line shows:++ * the transaction's (or posting's, see below) date+ * the names of the other account(s) involved+ * the net change to this account's balance+ * the account's historical running balance (including balance from+ transactions before the report start date).++ With 'aregister', each line represents a whole transaction - as in+hledger-ui, hledger-web, and your bank statement. By contrast, the+'register' command shows individual postings, across all accounts. You+might prefer 'aregister' for reconciling with real-world asset/liability+accounts, and 'register' for reviewing detailed revenues/expenses.++ An account must be specified as the first argument, which should be+the full account name or an account pattern (regular expression).+aregister will show transactions in this account (the first one matched)+and any of its subaccounts.++ Any additional arguments form a query which will filter the+transactions shown.++ Transactions making a net change of zero are not shown by default;+add the '-E/--empty' flag to show them.++* Menu:++* aregister and custom posting dates::+* Output format::+++File: hledger.info, Node: aregister and custom posting dates, Next: , Up: aregister++3.4.1 aregister and custom posting dates+----------------------------------------++Transactions whose date is outside the report period can still be shown,+if they have a posting to this account dated inside the report period.+(And in this case it's the posting date that is shown.) This ensures+that 'aregister' can show an accurate historical running balance,+matching the one shown by 'register -H' with the same arguments.++ To filter strictly by transaction date instead, add the '--txn-dates'+flag. If you use this flag and some of your postings have custom dates,+it's probably best to assume the running balance is wrong.++3.4.2 Output format+-------------------++This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', and 'json'.++ Examples:++ Show all transactions and historical running balance in the first+account whose name contains "checking":++$ hledger areg checking++ Show transactions and historical running balance in all asset+accounts during july:++$ hledger areg assets date:jul+++File: hledger.info, Node: balance, Next: balancesheet, Prev: aregister, Up: COMMANDS++3.5 balance+===========++balance, bal, b+Show accounts and their balances.++ The balance command is hledger's most versatile command. Note,+despite the name, it is not always used for showing real-world account+balances; the more accounting-aware balancesheet and incomestatement may+be more convenient for that.++ By default, it displays all accounts, and each account's change in+balance during the entire period of the journal. Balance changes are+calculated by adding up the postings in each account. You can limit the+postings matched, by a query, to see fewer accounts, changes over a+different time period, changes from only cleared transactions, etc.++ If you include an account's complete history of postings in the+report, the balance change is equivalent to the account's current ending+balance. For a real-world account, typically you won't have all+transactions in the journal; instead you'll have all transactions after+a certain date, and an "opening balances" transaction setting the+correct starting balance on that date. Then the balance command will+show real-world account balances. In some cases the -H/-historical flag+is used to ensure this (more below).++ The balance command can produce several styles of report:++* Menu:++* Classic balance report::+* Customising the classic balance report::+* Colour support::+* Flat mode::+* Depth limited balance reports::+* Percentages::+* Sorting by amount::+* Multicolumn balance report::+* Budget report::+* Output format::+++File: hledger.info, Node: Classic balance report, Next: Customising the classic balance report, Up: balance++3.5.1 Classic balance report+----------------------------++This is the original balance report, as found in Ledger. It usually+looks like this:++$ hledger balance+ $-1 assets+ $1 bank:saving+ $-2 cash+ $2 expenses+ $1 food+ $1 supplies+ $-2 income+ $-1 gifts+ $-1 salary+ $1 liabilities:debts+--------------------+ 0++ By default, accounts are displayed hierarchically, with subaccounts+indented below their parent, with accounts at each level of the tree+sorted by declaration order if declared, then by account name.++ "Boring" accounts, which contain a single interesting subaccount and+no balance of their own, are elided into the following line for more+compact output. (Eg above, the "liabilities" account.) Use+'--no-elide' to prevent this.++ Account balances are "inclusive" - they include the balances of any+subaccounts.++ Accounts which have zero balance (and no non-zero subaccounts) are+omitted. Use '-E/--empty' to show them.++ A final total is displayed by default; use '-N/--no-total' to+suppress it, eg:++$ hledger balance -p 2008/6 expenses --no-total+ $2 expenses+ $1 food+ $1 supplies+++File: hledger.info, Node: Customising the classic balance report, Next: Colour support, Prev: Classic balance report, Up: balance++3.5.2 Customising the classic balance report+--------------------------------------------++You can customise the layout of classic balance reports with '--format+FMT':++$ hledger balance --format "%20(account) %12(total)"+ assets $-1+ bank:saving $1+ cash $-2+ expenses $2+ food $1+ supplies $1+ income $-2+ gifts $-1+ salary $-1+ liabilities:debts $1+---------------------------------+ 0++ The FMT format string (plus a newline) specifies the formatting+applied to each account/balance pair. It may contain any suitable text,+with data fields interpolated like so:++ '%[MIN][.MAX](FIELDNAME)'++ * MIN pads with spaces to at least this width (optional)++ * MAX truncates at this width (optional)++ * FIELDNAME must be enclosed in parentheses, and can be one of:++ * 'depth_spacer' - a number of spaces equal to the account's+ depth, or if MIN is specified, MIN * depth spaces.+ * 'account' - the account's name+ * 'total' - the account's balance/posted total, right justified++ Also, FMT can begin with an optional prefix to control how+multi-commodity amounts are rendered:++ * '%_' - render on multiple lines, bottom-aligned (the default)+ * '%^' - render on multiple lines, top-aligned+ * '%,' - render on one line, comma-separated++ There are some quirks. Eg in one-line mode, '%(depth_spacer)' has no+effect, instead '%(account)' has indentation built in. Experimentation+may be needed to get pleasing results.++ Some example formats:++ * '%(total)' - the account's total+ * '%-20.20(account)' - the account's name, left justified, padded to+ 20 characters and clipped at 20 characters+ * '%,%-50(account) %25(total)' - account name padded to 50+ characters, total padded to 20 characters, with multiple+ commodities rendered on one line+ * '%20(total) %2(depth_spacer)%-(account)' - the default format for+ the single-column balance report+++File: hledger.info, Node: Colour support, Next: Flat mode, Prev: Customising the classic balance report, Up: balance++3.5.3 Colour support+--------------------++In terminal output, when colour is enabled, the balance command shows+negative amounts in red.+++File: hledger.info, Node: Flat mode, Next: Depth limited balance reports, Prev: Colour support, Up: balance++3.5.4 Flat mode+---------------++To see a flat list instead of the default hierarchical display, use+'--flat'. In this mode, accounts (unless depth-clipped) show their full+names and "exclusive" balance, excluding any subaccount balances. In+this mode, you can also use '--drop N' to omit the first few account+name components.++$ hledger balance -p 2008/6 expenses -N --flat --drop 1+ $1 food+ $1 supplies+++File: hledger.info, Node: Depth limited balance reports, Next: Percentages, Prev: Flat mode, Up: balance++3.5.5 Depth limited balance reports+-----------------------------------++With '--depth N' or 'depth:N' or just '-N', balance reports show+accounts only to the specified numeric depth. This is very useful to+summarise a complex set of accounts and get an overview.++$ hledger balance -N -1+ $-1 assets+ $2 expenses+ $-2 income+ $1 liabilities++ Flat-mode balance reports, which normally show exclusive balances,+show inclusive balances at the depth limit.+++File: hledger.info, Node: Percentages, Next: Sorting by amount, Prev: Depth limited balance reports, Up: balance++3.5.6 Percentages+-----------------++With '-%' or '--percent', balance reports show each account's value+expressed as a percentage of the column's total. This is useful to get+an overview of the relative sizes of account balances. For example to+obtain an overview of expenses:++$ hledger balance expenses -%+ 100.0 % expenses+ 50.0 % food+ 50.0 % supplies+--------------------+ 100.0 %++ Note that '--tree' does not have an effect on '-%'. The percentages+are always relative to the total sum of each column, they are never+relative to the parent account.++ Since the percentages are relative to the columns sum, it is usually+not useful to calculate percentages if the signs of the amounts are+mixed. Although the results are technically correct, they are most+likely useless. Especially in a balance report that sums up to zero (eg+'hledger balance -B') all percentage values will be zero.++ This flag does not work if the report contains any mixed commodity+accounts. If there are mixed commodity accounts in the report be sure+to use '-V' or '-B' to coerce the report into using a single commodity.+++File: hledger.info, Node: Sorting by amount, Next: Multicolumn balance report, Prev: Percentages, Up: balance++3.5.7 Sorting by amount+-----------------------++With '-S'/'--sort-amount', accounts with the largest (most positive)+balances are shown first. For example, 'hledger bal expenses -MAS'+shows your biggest averaged monthly expenses first.++ Revenues and liability balances are typically negative, however, so+'-S' shows these in reverse order. To work around this, you can add+'--invert' to flip the signs. Or, use one of the sign-flipping reports+like 'balancesheet' or 'incomestatement', which also support '-S'. Eg:+'hledger is -MAS'.+++File: hledger.info, Node: Multicolumn balance report, Next: Budget report, Prev: Sorting by amount, Up: balance++3.5.8 Multicolumn balance report+--------------------------------++Multicolumn or tabular balance reports are a very useful hledger+feature, and usually the preferred style. They share many of the above+features, but they show the report as a table, with columns representing+time periods. This mode is activated by providing a reporting interval.++ There are three types of multicolumn balance report, showing+different information:++ 1. By default: each column shows the sum of postings in that period,+ ie the account's change of balance in that period. This is useful+ eg for a monthly income statement:++ $ hledger balance --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 ++ 2. With '--cumulative': each column shows the ending balance for that+ period, accumulating the changes across periods, starting from 0 at+ the report start date:++ $ hledger balance --quarterly income expenses -E --cumulative+ Ending balances (cumulative) in 2008:+ + || 2008/03/31 2008/06/30 2008/09/30 2008/12/31 + ===================++=================================================+ expenses:food || 0 $1 $1 $1 + expenses:supplies || 0 $1 $1 $1 + income:gifts || 0 $-1 $-1 $-1 + income:salary || $-1 $-1 $-1 $-1 + -------------------++-------------------------------------------------+ || $-1 0 0 0 ++ 3. With '--historical/-H': each column shows the actual historical+ ending balance for that period, accumulating the changes across+ periods, starting from the actual balance at the report start date.+ This is useful eg for a multi-period balance sheet, and when you+ are showing only the data after a certain start date:++ $ hledger balance ^assets ^liabilities --quarterly --historical --begin 2008/4/1+ Ending balances (historical) in 2008/04/01-2008/12/31:+ + || 2008/06/30 2008/09/30 2008/12/31 + ======================++=====================================+ assets:bank:checking || $1 $1 0 + assets:bank:saving || $1 $1 $1 + assets:cash || $-2 $-2 $-2 + liabilities:debts || 0 0 $1 + ----------------------++-------------------------------------+ || 0 0 0 ++ Note that '--cumulative' or '--historical/-H' disable+'--row-total/-T', since summing end balances generally does not make+sense.++ Multicolumn balance reports display accounts in flat mode by default;+to see the hierarchy, use '--tree'.++ With a reporting interval (like '--quarterly' above), the report+start/end dates will be adjusted if necessary so that they encompass the+displayed report periods. This is so that the first and last periods+will be "full" and comparable to the others.++ The '-E/--empty' flag does two things in multicolumn balance reports:+first, the report will show all columns within the specified report+period (without -E, leading and trailing columns with all zeroes are not+shown). Second, all accounts which existed at the report start date+will be considered, not just the ones with activity during the report+period (use -E to include low-activity accounts which would otherwise+would be omitted).++ The '-T/--row-total' flag adds an additional column showing the total+for each row.++ The '-A/--average' flag adds a column showing the average value in+each row.++ Here's an example of all three:++$ hledger balance -Q income expenses --tree -ETA+Balance changes in 2008:++ || 2008q1 2008q2 2008q3 2008q4 Total Average +============++===================================================+ expenses || 0 $2 0 0 $2 $1 + food || 0 $1 0 0 $1 0 + supplies || 0 $1 0 0 $1 0 + income || $-1 $-1 0 0 $-2 $-1 + gifts || 0 $-1 0 0 $-1 0 + salary || $-1 0 0 0 $-1 0 +------------++---------------------------------------------------+ || $-1 $1 0 0 0 0 ++(Average is rounded to the dollar here since all journal amounts are)++ The '--transpose' flag can be used to exchange the rows and columns+of a multicolumn report.++ When showing multicommodity amounts, multicolumn balance reports will+elide any amounts which have more than two commodities, since otherwise+columns could get very wide. The '--no-elide' flag disables this.+Hiding totals with the '-N/--no-total' flag can also help reduce the+width of multicommodity reports.++ When the report is still too wide, a good workaround is to pipe it+into 'less -RS' (-R for colour, -S to chop long lines). Eg: 'hledger+bal -D --color=yes | less -RS'.+++File: hledger.info, Node: Budget report, Next: , Prev: Multicolumn balance report, Up: balance++3.5.9 Budget report+-------------------++With '--budget', extra columns are displayed showing budget goals for+each account and period, if any. Budget goals are defined by periodic+transactions. This is very useful for comparing planned and actual+income, expenses, time usage, etc. -budget is most often combined with+a report interval.++ For example, you can take average monthly expenses in the common+expense categories to construct a minimal monthly budget:++;; Budget+~ monthly+ income $2000+ expenses:food $400+ expenses:bus $50+ expenses:movies $30+ assets:bank:checking++;; Two months worth of expenses+2017-11-01+ income $1950+ expenses:food $396+ expenses:bus $49+ expenses:movies $30+ expenses:supplies $20+ assets:bank:checking++2017-12-01+ income $2100+ expenses:food $412+ expenses:bus $53+ expenses:gifts $100+ assets:bank:checking++ You can now see a monthly budget report:++$ hledger balance -M --budget+Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec +======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + expenses || $495 [ 103% of $480] $565 [ 118% of $480] + expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50] + expenses:food || $396 [ 99% of $400] $412 [ 103% of $400] + expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30] + income || $1950 [ 98% of $2000] $2100 [ 105% of $2000] +----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0] ++ This is different from a normal balance report in several ways:++ * Only accounts with budget goals during the report period are shown,+ by default.++ * In each column, in square brackets after the actual amount, budget+ goal amounts are shown, and the actual/goal percentage. (Note:+ budget goals should be in the same commodity as the actual amount.)++ * All parent accounts are always shown, even in flat mode. Eg+ assets, assets:bank, and expenses above.++ * Amounts always include all subaccounts, budgeted or unbudgeted,+ even in flat mode.++ This means that the numbers displayed will not always add up! Eg+above, the 'expenses' actual amount includes the gifts and supplies+transactions, but the 'expenses:gifts' and 'expenses:supplies' accounts+are not shown, as they have no budget amounts declared.++ This can be confusing. When you need to make things clearer, use the+'-E/--empty' flag, which will reveal all accounts including unbudgeted+ones, giving the full picture. Eg:++$ hledger balance -M --budget --empty+Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec +======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480] + expenses || $495 [ 103% of $480] $565 [ 118% of $480] + expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50] + expenses:food || $396 [ 99% of $400] $412 [ 103% of $400] + expenses:gifts || 0 $100 + expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30] + expenses:supplies || $20 0 + income || $1950 [ 98% of $2000] $2100 [ 105% of $2000] +----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0] ++ You can roll over unspent budgets to next period with '--cumulative':++$ hledger balance -M --budget --cumulative+Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec +======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] + assets:bank || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] + assets:bank:checking || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960] + expenses || $495 [ 103% of $480] $1060 [ 110% of $960] + expenses:bus || $49 [ 98% of $50] $102 [ 102% of $100] + expenses:food || $396 [ 99% of $400] $808 [ 101% of $800] + expenses:movies || $30 [ 100% of $30] $30 [ 50% of $60] + income || $1950 [ 98% of $2000] $4050 [ 101% of $4000] +----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0] ++ For more examples and notes, see Budgeting.++* Menu:++* Budget report start date::+* Nested budgets::+++File: hledger.info, Node: Budget report start date, Next: Nested budgets, Up: Budget report++3.5.9.1 Budget report start date+................................++This might be a bug, but for now: when making budget reports, it's a+good idea to explicitly set the report's start date to the first day of+a reporting period, because a periodic rule like '~ monthly' generates+its transactions on the 1st of each month, and if your journal has no+regular transactions on the 1st, the default report start date could+exclude that budget goal, which can be a little surprising. Eg here the+default report period is just the day of 2020-01-15:++~ monthly in 2020+ (expenses:food) $500++2020-01-15+ expenses:food $400+ assets:checking++$ hledger bal expenses --budget+Budget performance in 2020-01-15:++ || 2020-01-15 +==============++============+ <unbudgeted> || $400 +--------------++------------+ || $400 ++ To avoid this, specify the budget report's period, or at least the+start date, with '-b'/'-e'/'-p'/'date:', to ensure it includes the+budget goal transactions (periodic transactions) that you want. Eg,+adding '-b 2020/1/1' to the above:++$ hledger bal expenses --budget -b 2020/1/1+Budget performance in 2020-01-01..2020-01-15:++ || 2020-01-01..2020-01-15 +===============++========================+ expenses:food || $400 [80% of $500] +---------------++------------------------+ || $400 [80% of $500] +++File: hledger.info, Node: Nested budgets, Prev: Budget report start date, Up: Budget report++3.5.9.2 Nested budgets+......................++You can add budgets to any account in your account hierarchy. If you+have budgets on both parent account and some of its children, then+budget(s) of the child account(s) would be added to the budget of their+parent, much like account balances behave.++ In the most simple case this means that once you add a budget to any+account, all its parents would have budget as well.++ To illustrate this, consider the following budget:++~ monthly from 2019/01+ expenses:personal $1,000.00+ expenses:personal:electronics $100.00+ liabilities++ With this, monthly budget for electronics is defined to be $100 and+budget for personal expenses is an additional $1000, which implicitly+means that budget for both 'expenses:personal' and 'expenses' is $1100.++ Transactions in 'expenses:personal:electronics' will be counted both+towards its $100 budget and $1100 of 'expenses:personal' , and+transactions in any other subaccount of 'expenses:personal' would be+counted towards only towards the budget of 'expenses:personal'.++ For example, let's consider these transactions:++~ monthly from 2019/01+ expenses:personal $1,000.00+ expenses:personal:electronics $100.00+ liabilities++2019/01/01 Google home hub+ expenses:personal:electronics $90.00+ liabilities $-90.00++2019/01/02 Phone screen protector+ expenses:personal:electronics:upgrades $10.00+ liabilities++2019/01/02 Weekly train ticket+ expenses:personal:train tickets $153.00+ liabilities++2019/01/03 Flowers+ expenses:personal $30.00+ liabilities++ As you can see, we have transactions in+'expenses:personal:electronics:upgrades' and 'expenses:personal:train+tickets', and since both of these accounts are without explicitly+defined budget, these transactions would be counted towards budgets of+'expenses:personal:electronics' and 'expenses:personal' accordingly:++$ hledger balance --budget -M+Budget performance in 2019/01:++ || Jan +===============================++===============================+ expenses || $283.00 [ 26% of $1100.00] + expenses:personal || $283.00 [ 26% of $1100.00] + expenses:personal:electronics || $100.00 [ 100% of $100.00] + liabilities || $-283.00 [ 26% of $-1100.00] +-------------------------------++-------------------------------+ || 0 [ 0] ++ And with '--empty', we can get a better picture of budget allocation+and consumption:++$ hledger balance --budget -M --empty+Budget performance in 2019/01:++ || Jan +========================================++===============================+ expenses || $283.00 [ 26% of $1100.00] + expenses:personal || $283.00 [ 26% of $1100.00] + expenses:personal:electronics || $100.00 [ 100% of $100.00] + expenses:personal:electronics:upgrades || $10.00 + expenses:personal:train tickets || $153.00 + liabilities || $-283.00 [ 26% of $-1100.00] +----------------------------------------++-------------------------------+ || 0 [ 0] ++3.5.10 Output format+--------------------++This command also supports the output destination and output format+options The output formats supported are (in most modes): 'txt', 'csv',+'html', and 'json'.+++File: hledger.info, Node: balancesheet, Next: balancesheetequity, Prev: balance, Up: COMMANDS++3.6 balancesheet+================++balancesheet, bs+This command displays a balance sheet, showing historical ending+balances of asset and liability accounts. (To see equity as well, use+the balancesheetequity command.) Amounts are shown with normal positive+sign, as in conventional financial statements.++ The asset and liability accounts shown are those accounts declared+with the 'Asset' or 'Cash' or 'Liability' type, or otherwise all+accounts under a top-level 'asset' or 'liability' account (case+insensitive, plurals allowed).++ Example:++$ hledger balancesheet+Balance Sheet++Assets:+ $-1 assets+ $1 bank:saving+ $-2 cash+--------------------+ $-1++Liabilities:+ $1 liabilities:debts+--------------------+ $1++Total:+--------------------+ 0++ With a reporting interval, multiple columns will be shown, one for+each report period. As with multicolumn balance reports, you can alter+the report mode with '--change'/'--cumulative'/'--historical'. Normally+balancesheet shows historical ending balances, which is what you need+for a balance sheet; note this means it ignores report begin dates (and+'-T/--row-total', since summing end balances generally does not make+sense). Instead of absolute values percentages can be displayed with+'-%'.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'html', and+(experimental) 'json'.+++File: hledger.info, Node: balancesheetequity, Next: cashflow, Prev: balancesheet, Up: COMMANDS++3.7 balancesheetequity+======================++balancesheetequity, bse+This command displays a balance sheet, showing historical ending+balances of asset, liability and equity accounts. Amounts are shown+with normal positive sign, as in conventional financial statements.++ The asset, liability and equity accounts shown are those accounts+declared with the 'Asset', 'Cash', 'Liability' or 'Equity' type, or+otherwise all accounts under a top-level 'asset', 'liability' or+'equity' account (case insensitive, plurals allowed).++ Example:++$ hledger balancesheetequity+Balance Sheet With Equity++Assets:+ $-2 assets+ $1 bank:saving+ $-3 cash+--------------------+ $-2++Liabilities:+ $1 liabilities:debts+--------------------+ $1++Equity:+ $1 equity:owner+--------------------+ $1++Total:+--------------------+ 0++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'html', and+(experimental) 'json'.+++File: hledger.info, Node: cashflow, Next: check, Prev: balancesheetequity, Up: COMMANDS++3.8 cashflow+============++cashflow, cf+This command displays a cashflow statement, showing the inflows and+outflows affecting "cash" (ie, liquid) assets. Amounts are shown with+normal positive sign, as in conventional financial statements.++ The "cash" accounts shown are those accounts declared with the 'Cash'+type, or otherwise all accounts under a top-level 'asset' account (case+insensitive, plural allowed) which do not have 'fixed', 'investment',+'receivable' or 'A/R' in their name.++ Example:++$ hledger cashflow+Cashflow Statement++Cash flows:+ $-1 assets+ $1 bank:saving+ $-2 cash+--------------------+ $-1++Total:+--------------------+ $-1++ With a reporting interval, multiple columns will be shown, one for+each report period. Normally cashflow shows changes in assets per+period, though as with multicolumn balance reports you can alter the+report mode with '--change'/'--cumulative'/'--historical'. Instead of+absolute values percentages can be displayed with '-%'.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'html', and+(experimental) 'json'.+++File: hledger.info, Node: check, Next: close, Prev: cashflow, Up: COMMANDS++3.9 check+=========++check+Check for various kinds of errors in your data. _experimental_++ hledger provides a number of built-in error checks to help prevent+problems in your data. Some of these are run automatically; or, you can+use this 'check' command to run them on demand, with no output and a+zero exit code if all is well. Some examples:++hledger check # basic checks+hledger check -s # basic + strict checks+hledger check ordereddates uniqueleafnames # basic + specified checks++ Here are the checks currently available:++* Menu:++* Basic checks::+* Strict checks::+* Other checks::+* Addon checks::+++File: hledger.info, Node: Basic checks, Next: Strict checks, Up: check++3.9.1 Basic checks+------------------++These are always run by this command and other commands:++ * *parseable* - data files are well-formed and can be successfully+ parsed++ * *autobalanced* - all transactions are balanced, inferring missing+ amounts where necessary, and possibly converting commodities using+ transaction prices or automatically-inferred transaction prices++ * *assertions* - all balance assertions in the journal are passing.+ (This check can be disabled with '-I'/'--ignore-assertions'.)+++File: hledger.info, Node: Strict checks, Next: Other checks, Prev: Basic checks, Up: check++3.9.2 Strict checks+-------------------++These are always run by this and other commands when '-s'/'--strict' is+used (strict mode):++ * *accounts* - all account names used by transactions have been+ declared++ * *commodities* - all commodity symbols used have been declared+++File: hledger.info, Node: Other checks, Next: Addon checks, Prev: Strict checks, Up: check++3.9.3 Other checks+------------------++These checks can be run by specifying their names as arguments to the+check command:++ * *ordereddates* - transactions are ordered by date (similar to the+ old 'check-dates' command)++ * *uniqueleafnames* - all account leaf names are unique (similar to+ the old 'check-dupes' command)+++File: hledger.info, Node: Addon checks, Prev: Other checks, Up: check++3.9.4 Addon checks+------------------++Some checks are not yet integrated with this command, but are available+as add-on commands in+https://github.com/simonmichael/hledger/tree/master/bin:++ * *hledger-check-tagfiles* - all tag values containing / (a forward+ slash) exist as file paths++ * *hledger-check-fancyassertions* - more complex balance assertions+ are passing++ You could make your own similar scripts to perform custom checks;+Cookbook -> Scripting may be helpful.+++File: hledger.info, Node: close, Next: codes, Prev: check, Up: COMMANDS++3.10 close+==========++close, equity+Prints a "closing balances" transaction and an "opening balances"+transaction that bring account balances to and from zero, respectively.+These can be added to your journal file(s), eg to bring asset/liability+balances forward into a new journal file, or to close out+revenues/expenses to retained earnings at the end of a period.++ You can print just one of these transactions by using the '--close'+or '--open' flag. You can customise their descriptions with the+'--close-desc' and '--open-desc' options.++ One amountless posting to "equity:opening/closing balances" is added+to balance the transactions, by default. You can customise this account+name with '--close-acct' and '--open-acct'; if you specify only one of+these, it will be used for both.++ With '--x/--explicit', the equity posting's amount will be shown.+And if it involves multiple commodities, a posting for each commodity+will be shown, as with the print command.++ With '--interleaved', the equity postings are shown next to the+postings they balance, which makes troubleshooting easier.++ By default, transaction prices in the journal are ignored when+generating the closing/opening transactions. With '--show-costs', this+cost information is preserved ('balance -B' reports will be unchanged+after the transition). Separate postings are generated for each cost in+each commodity. Note this can generate very large journal entries, if+you have many foreign currency or investment transactions.++* Menu:++* close usage::+++File: hledger.info, Node: close usage, Up: close++3.10.1 close usage+------------------++If you split your journal files by time (eg yearly), you will typically+run this command at the end of the year, and save the closing+transaction as last entry of the old file, and the opening transaction+as the first entry of the new file. This makes the files self+contained, so that correct balances are reported no matter which of them+are loaded. Ie, if you load just one file, the balances are initialised+correctly; or if you load several files, the redundant closing/opening+transactions cancel each other out. (They will show up in print or+register reports; you can exclude them with a query like+'not:desc:'(opening|closing) balances''.)++ If you're running a business, you might also use this command to+"close the books" at the end of an accounting period, transferring+income statement account balances to retained earnings. (You may want+to change the equity account name to something like "equity:retained+earnings".)++ By default, the closing transaction is dated yesterday, the balances+are calculated as of end of yesterday, and the opening transaction is+dated today. To close on some other date, use: 'hledger close -e+OPENINGDATE'. Eg, to close/open on the 2018/2019 boundary, use '-e+2019'. You can also use -p or 'date:PERIOD' (any starting date is+ignored).++ Both transactions will include balance assertions for the+closed/reopened accounts. You probably shouldn't use status or realness+filters (like -C or -R or 'status:') with this command, or the generated+balance assertions will depend on these flags. Likewise, if you run+this command with -auto, the balance assertions will probably always+require -auto.++ Examples:++ Carrying asset/liability balances into a new file for 2019:++$ hledger close -f 2018.journal -e 2019 assets liabilities --open+ # (copy/paste the output to the start of your 2019 journal file)+$ hledger close -f 2018.journal -e 2019 assets liabilities --close+ # (copy/paste the output to the end of your 2018 journal file)++ Now:++$ hledger bs -f 2019.journal # one file - balances are correct+$ hledger bs -f 2018.journal -f 2019.journal # two files - balances still correct+$ hledger bs -f 2018.journal not:desc:closing # to see year-end balances, must exclude closing txn++ Transactions spanning the closing date can complicate matters,+breaking balance assertions:++2018/12/30 a purchase made in 2018, clearing the following year+ expenses:food 5+ assets:bank:checking -5 ; [2019/1/2]++ Here's one way to resolve that:++; in 2018.journal:+2018/12/30 a purchase made in 2018, clearing the following year+ expenses:food 5+ liabilities:pending++; in 2019.journal:+2019/1/2 clearance of last year's pending transactions+ liabilities:pending 5 = 0+ assets:checking+++File: hledger.info, Node: codes, Next: commodities, Prev: close, Up: COMMANDS++3.11 codes+==========++codes+List the codes seen in transactions, in the order parsed.++ This command prints the value of each transaction's 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.++ Transactions aren't required to have a code, and missing or empty+codes will not be shown by default. With the '-E'/'--empty' flag, they+will be printed as blank lines.++ You can add a query to select a subset of transactions.++ Examples:++1/1 (123)+ (a) 1++1/1 ()+ (a) 1++1/1+ (a) 1++1/1 (126)+ (a) 1++$ hledger codes+123+124+126++$ hledger codes -E+123+124+++126+++File: hledger.info, Node: commodities, Next: descriptions, Prev: codes, Up: COMMANDS++3.12 commodities+================++commodities+List all commodity/currency symbols used or declared in the journal.+++File: hledger.info, Node: descriptions, Next: diff, Prev: commodities, Up: COMMANDS++3.13 descriptions+=================++descriptions+List the unique descriptions that appear in transactions.++ This command lists the unique descriptions that appear in+transactions, in alphabetic order. You can add a query to select a+subset of transactions.++ Example:++$ hledger descriptions+Store Name+Gas Station | Petrol+Person A+++File: hledger.info, Node: diff, Next: files, Prev: descriptions, Up: COMMANDS++3.14 diff+=========++diff+Compares a particular account's transactions in two input files. It+shows any transactions to this account which are in one file but not in+the other.++ More precisely, for each posting affecting this account in either+file, it looks for a corresponding posting in the other file which posts+the same amount to the same account (ignoring date, description, etc.)+Since postings not transactions are compared, this also works when+multiple bank transactions have been combined into a single journal+entry.++ This is useful eg if you have downloaded an account's 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.++ Examples:++$ 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:+++File: hledger.info, Node: files, Next: help, Prev: diff, Up: COMMANDS++3.15 files+==========++files+List all files included in the journal. With a REGEX argument, only+file names matching the regular expression (case sensitive) are shown.+++File: hledger.info, Node: help, Next: import, Prev: files, Up: COMMANDS++3.16 help+=========++help+Show any of the hledger manuals.++ The 'help' command displays any of the main hledger manuals, in one+of several ways. Run it with no argument to list the manuals, or+provide a full or partial manual name to select one.++ hledger manuals are available in several formats. hledger help will+use the first of these display methods that it finds: info, man, $PAGER,+less, stdout (or when non-interactive, just stdout). You can force a+particular viewer with the '--info', '--man', '--pager', '--cat' flags.++ Examples:++$ hledger help+Please choose a manual by typing "hledger help MANUAL" (a substring is ok).+Manuals: hledger hledger-ui hledger-web journal csv timeclock timedot++$ hledger help h --man++hledger(1) hledger User Manuals hledger(1)++NAME+ hledger - a command-line accounting tool++SYNOPSIS+ hledger [-f FILE] COMMAND [OPTIONS] [ARGS]+ hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]+ hledger++DESCRIPTION+ hledger is a cross-platform program for tracking money, time, or any+...+++File: hledger.info, Node: import, Next: incomestatement, Prev: help, Up: COMMANDS++3.17 import+===========++import+Read new transactions added to each FILE since last run, and add them to+the main journal file. Or with -dry-run, just print the transactions+that would be added. Or with -catchup, just mark all of the FILEs'+transactions as imported, without actually importing any.++ The input files are specified as arguments - no need to write -f+before each one. So eg to add new transactions from all CSV files to+the main journal, it's just: 'hledger import *.csv'++ New transactions are detected in the same way as print -new: by+assuming transactions are always added to the input files in increasing+date order, and by saving '.latest.FILE' state files.++ The -dry-run output is in journal format, so you can filter it, eg to+see only uncategorised transactions:++$ hledger import --dry ... | hledger -f- print unknown --ignore-assertions++* Menu:++* Importing balance assignments::+* Commodity display styles::+++File: hledger.info, Node: Importing balance assignments, Next: Commodity display styles, Up: import++3.17.1 Importing balance assignments+------------------------------------++Entries added by import will have their posting amounts made explicit+(like 'hledger print -x'). This means that any balance assignments in+imported files must be evaluated; but, imported files don't get to see+the main file's account balances. As a result, importing entries with+balance assignments (eg from an institution that provides only balances+and not posting amounts) will probably generate incorrect posting+amounts. To avoid this problem, use print instead of import:++$ hledger print IMPORTFILE [--new] >> $LEDGER_FILE++ (If you think import should leave amounts implicit like print does,+please test it and send a pull request.)+++File: hledger.info, Node: Commodity display styles, Prev: Importing balance assignments, Up: import++3.17.2 Commodity display styles+-------------------------------++Imported amounts will be formatted according to the canonical commodity+styles (declared or inferred) in the main journal file.+++File: hledger.info, Node: incomestatement, Next: notes, Prev: import, Up: COMMANDS++3.18 incomestatement+====================++incomestatement, is++ This command displays an income statement, showing revenues and+expenses during one or more periods. Amounts are shown with normal+positive sign, as in conventional financial statements.++ The revenue and expense accounts shown are those accounts declared+with the 'Revenue' or 'Expense' type, or otherwise all accounts under a+top-level 'revenue' or 'income' or 'expense' account (case insensitive,+plurals allowed).++ Example:++$ hledger incomestatement+Income Statement++Revenues:+ $-2 income+ $-1 gifts+ $-1 salary+--------------------+ $-2++Expenses:+ $2 expenses+ $1 food+ $1 supplies+--------------------+ $2++Total:+--------------------+ 0++ With a reporting interval, multiple columns will be shown, one for+each report period. Normally incomestatement shows revenues/expenses+per period, though as with multicolumn balance reports you can alter the+report mode with '--change'/'--cumulative'/'--historical'. Instead of+absolute values percentages can be displayed with '-%'.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'html', and+(experimental) 'json'.+++File: hledger.info, Node: notes, Next: payees, Prev: incomestatement, Up: COMMANDS++3.19 notes+==========++notes+List the unique notes that appear in transactions.++ 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).++ Example:++$ hledger notes+Petrol+Snacks+++File: hledger.info, Node: payees, Next: prices, Prev: notes, Up: COMMANDS++3.20 payees+===========++payees+List the unique payee/payer names that appear in transactions.++ This command lists the unique payee/payer names that appear in+transactions, in alphabetic order. You can add a query to select a+subset of transactions. The payee/payer is the part of the transaction+description before a | character (or if there is no |, the whole+description).++ Example:++$ hledger payees+Store Name+Gas Station+Person A+++File: hledger.info, Node: prices, Next: print, Prev: payees, Up: COMMANDS++3.21 prices+===========++prices+Print market price directives from the journal. With -costs, also print+synthetic market prices based on transaction prices. With+-inverted-costs, also print inverse prices based on transaction prices.+Prices (and postings providing prices) can be filtered by a query.+Price amounts are always displayed with their full precision.+++File: hledger.info, Node: print, Next: print-unique, Prev: prices, Up: COMMANDS++3.22 print+==========++print, txns, p+Show transaction journal entries, sorted by date.++ The print command displays full journal entries (transactions) from+the journal file in date order, tidily formatted. With -date2,+transactions are sorted by secondary date instead.++ print's output is always a valid hledger journal.+It preserves all transaction information, but it does not preserve+directives or inter-transaction comments++$ hledger print+2008/01/01 income+ assets:bank:checking $1+ income:salary $-1++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++2008/12/31 * pay off+ liabilities:debts $1+ assets:bank:checking $-1++ Normally, the journal entry's explicit or implicit amount style is+preserved. For example, when an amount is omitted in the journal, it+will not appear in the output. Similarly, when a transaction price is+implied but not written, it will not appear in the output. You can use+the '-x'/'--explicit' flag to make all amounts and transaction prices+explicit, which can be useful for troubleshooting or for making your+journal more readable and robust against data entry errors. '-x' is+also implied by using any of '-B','-V','-X','--value'.++ Note, '-x'/'--explicit' will cause postings with a multi-commodity+amount (these can arise when a multi-commodity transaction has an+implicit amount) to be split into multiple single-commodity postings,+keeping the output parseable.++ With '-B'/'--cost', amounts with transaction prices are converted to+cost using that price. This can be used for troubleshooting.++ With '-m'/'--match' and a STR argument, print will show at most one+transaction: the one one whose description is most similar to STR, and+is most recent. STR should contain at least two characters. If there+is no similar-enough match, no transaction will be shown.++ With '--new', for each FILE being read, hledger reads (and writes) a+special state file ('.latest.FILE' in the same directory), containing+the latest transaction date(s) that were seen last time FILE was read.+When this file is found, only transactions with newer dates (and new+transactions on the latest date) are printed. This is useful for+ignoring already-seen entries in import data, such as downloaded CSV+files. Eg:++$ hledger -f bank1.csv print --new+(shows transactions added since last print --new on this file)++ This assumes that transactions added to FILE always have same or+increasing dates, and that transactions on the same day do not get+reordered. See also the import command.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', and+(experimental) 'json' and 'sql'.++ Here's an example of print's CSV output:++$ hledger print -Ocsv+"txnidx","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","posting-status","posting-comment"+"1","2008/01/01","","","","income","","assets:bank:checking","1","$","","1","",""+"1","2008/01/01","","","","income","","income:salary","-1","$","1","","",""+"2","2008/06/01","","","","gift","","assets:bank:checking","1","$","","1","",""+"2","2008/06/01","","","","gift","","income:gifts","-1","$","1","","",""+"3","2008/06/02","","","","save","","assets:bank:saving","1","$","","1","",""+"3","2008/06/02","","","","save","","assets:bank:checking","-1","$","1","","",""+"4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","","1","",""+"4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","","1","",""+"4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","2","","",""+"5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","","1","",""+"5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","1","","",""++ * There is one CSV record per posting, with the parent transaction's+ fields repeated.+ * The "txnidx" (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.)+ * The amount is separated into "commodity" (the symbol) and "amount"+ (numeric quantity) fields.+ * The numeric amount is repeated in either the "credit" or "debit"+ column, for convenience. (Those names are not accurate in the+ accounting sense; it just puts negative amounts under credit and+ zero or greater amounts under debit.)+++File: hledger.info, Node: print-unique, Next: register, Prev: print, Up: COMMANDS++3.23 print-unique+=================++print-unique+Print transactions which do not reuse an already-seen description.++ Example:++$ cat unique.journal+1/1 test+ (acct:one) 1+2/2 test+ (acct:two) 2+$ LEDGER_FILE=unique.journal hledger print-unique+(-f option not supported)+2015/01/01 test+ (acct:one) 1+++File: hledger.info, Node: register, Next: register-match, Prev: print-unique, Up: COMMANDS++3.24 register+=============++register, reg, r+Show postings and their running total.++ The register command displays matched postings, across all accounts,+in date order, with their running total or running historical balance.+(See also the 'aregister' command, which shows matched transactions in a+specific account.)++ register normally shows line per posting, but note that+multi-commodity amounts will occupy multiple lines (one line per+commodity).++ It is typically used with a query selecting a particular account, to+see that account's activity:++$ 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++ With -date2, it shows and sorts by secondary date instead.++ The '--historical'/'-H' 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:++$ 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++ The '--depth' option limits the amount of sub-account detail+displayed.++ The '--average'/'-A' 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 '--empty' (see+below). It is affected by '--historical'. It works best when showing+just one account and one commodity.++ The '--related'/'-r' flag shows the _other_ postings in the+transactions of the postings which would normally be shown.++ The '--invert' flag negates all amounts. For example, it can be used+on an income account where amounts are normally displayed as negative+numbers. It's also useful to show postings on the checking account+together with the related account:++$ hledger register --related --invert assets:checking++ With a reporting interval, register shows summary postings, one per+interval, aggregating the postings to each account:++$ hledger register --monthly income+2008/01 income:salary $-1 $-1+2008/06 income:gifts $-1 $-2++ Periods with no activity, and summary postings with a zero amount,+are not shown by default; use the '--empty'/'-E' flag to see them:++$ 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++ Often, you'll want to see just one line per interval. The '--depth'+option helps with this, causing subaccounts to be aggregated:++$ hledger register --monthly assets --depth 1h+2008/01 assets $1 $1+2008/06 assets $-1 0+2008/12 assets $-1 $-1++ 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.++* Menu:++* Custom register output::+++File: hledger.info, Node: Custom register output, Up: register++3.24.1 Custom register output+-----------------------------++register uses the full terminal width by default, except on windows.+You can override this by setting the 'COLUMNS' environment variable (not+a bash shell variable) or by using the '--width'/'-w' option.++ 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's argument, comma-separated:+'--width W,D' . Here's a diagram (won't display correctly in -help):++<--------------------------------- width (W) ---------------------------------->+date (10) description (D) account (W-41-D) amount (12) balance (12)+DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA++ and some examples:++$ hledger reg # use terminal width (or 80 on windows)+$ hledger reg -w 100 # use width 100+$ COLUMNS=100 hledger reg # set with one-time environment variable+$ export COLUMNS=100; hledger reg # set till session end (or window resize)+$ hledger reg -w 100,40 # set overall width 100, description width 40+$ hledger reg -w $COLUMNS,40 # use terminal width, & description width 40++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', and+(experimental) 'json'.+++File: hledger.info, Node: register-match, Next: rewrite, Prev: register, Up: COMMANDS++3.25 register-match+===================++register-match+Print the one posting whose transaction description is closest to DESC,+in the style of the register command. If there are multiple equally+good matches, it shows the most recent. Query options (options, not+arguments) can be used to restrict the search space. Helps+ledger-autosync detect already-seen transactions when importing.+++File: hledger.info, Node: rewrite, Next: roi, Prev: register-match, Up: COMMANDS++3.26 rewrite+============++rewrite+Print all transactions, rewriting the postings of matched transactions.+For now the only rewrite available is adding new postings, like print+-auto.++ 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's first posting amount.++ Examples:++$ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'+$ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'+$ hledger-rewrite.hs -f rewrites.hledger++ rewrites.hledger may consist of entries like:++= ^income 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++ Note the single quotes to protect the dollar sign from bash, and the+two spaces between account and amount.++ More:++$ hledger rewrite -- [QUERY] --add-posting "ACCT AMTEXPR" ...+$ hledger rewrite -- ^income --add-posting '(liabilities:tax) *.33'+$ hledger rewrite -- expenses:gifts --add-posting '(budget:gifts) *-1"'+$ hledger rewrite -- ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'++ Argument for '--add-posting' option is a usual posting of transaction+with an exception for amount specification. More precisely, you can use+''*'' (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's+commodity.++* Menu:++* Re-write rules in a file::+++File: hledger.info, Node: Re-write rules in a file, Up: rewrite++3.26.1 Re-write rules in a file+-------------------------------++During the run this tool will execute so called "Automated Transactions"+found in any journal it process. I.e instead of specifying this+operations in command line you can put them in a journal file.++$ rewrite-rules.journal++ Make contents look like this:++= ^income+ (liabilities:tax) *.33++= expenses:gifts+ budget:gifts *-1+ assets:budget *1++ Note that ''='' (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.++$ hledger rewrite -- -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal++ This is something similar to the commands pipeline:++$ hledger rewrite -- -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \+ | hledger rewrite -- -f - expenses:gifts --add-posting 'budget:gifts *-1' \+ --add-posting 'assets:budget *1' \+ > rewritten-tidy-output.journal++ It is important to understand that relative order of such entries in+journal is important. You can re-use result of previously added+postings.++* Menu:++* Diff output format::+* rewrite vs print --auto::+++File: hledger.info, Node: Diff output format, Next: rewrite vs print --auto, Up: Re-write rules in a file++3.26.1.1 Diff output format+...........................++To use this tool for batch modification of your journal files you may+find useful output in form of unified diff.++$ hledger rewrite -- --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'++ Output might look like:++--- /tmp/examples/sample.journal++++ /tmp/examples/sample.journal+@@ -18,3 +18,4 @@+ 2008/01/01 income+- assets:bank:checking $1++ assets:bank:checking $1+ income:salary++ (liabilities:tax) 0+@@ -22,3 +23,4 @@+ 2008/06/01 gift+- assets:bank:checking $1++ assets:bank:checking $1+ income:gifts++ (liabilities:tax) 0++ If you'll pass this through 'patch' tool you'll 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 '--file' options and 'include' directives inside of these+files.++ Be careful. Whole transaction being re-formatted in a style of+output from 'hledger print'.++ See also:++ https://github.com/simonmichael/hledger/issues/99+++File: hledger.info, Node: rewrite vs print --auto, Prev: Diff output format, Up: Re-write rules in a file++3.26.1.2 rewrite vs. print -auto+................................++This command predates print -auto, and currently does much the same+thing, but with these differences:++ * with multiple files, rewrite lets rules in any file affect all+ other files. print -auto uses standard directive scoping; rules+ affect only child files.++ * rewrite's query limits which transactions can be rewritten; all are+ printed. print -auto's query limits which transactions are+ printed.++ * rewrite applies rules specified on command line or in the journal.+ print -auto applies rules specified in the journal.+++File: hledger.info, Node: roi, Next: stats, Prev: rewrite, Up: COMMANDS++3.27 roi+========++roi+Shows the time-weighted (TWR) and money-weighted (IRR) rate of return on+your investments.++ This command assumes that you have account(s) that hold nothing but+your investments and whenever you record current appraisal/valuation of+these investments you offset unrealized profit and loss into account(s)+that, again, hold nothing but unrealized profit and loss.++ Any transactions affecting balance of investment account(s) and not+originating from unrealized profit and loss account(s) are assumed to be+your investments or withdrawals.++ At a minimum, you need to supply a query (which could be just an+account name) to select your investments with '--inv', and another query+to identify your profit and loss transactions with '--pnl'.++ This command will compute and display the internalized rate of return+(IRR) and time-weighted rate of return (TWR) for your investments for+the time period requested. Both rates of return are annualized before+display, regardless of the length of reporting interval.++ Note, in some cases this report can fail, for these reasons:++ * Error (NotBracketed): No solution for Internal Rate of Return+ (IRR). Possible causes: IRR is huge (>1000000%), balance of+ investment becomes negative at some point in time.+ * Error (SearchFailed): Failed to find solution for Internal Rate of+ Return (IRR). Either search does not converge to a solution, or+ converges too slowly.++ Examples:++ * Using roi to report unrealised gains:+ https://github.com/simonmichael/hledger/blob/master/examples/roi-unrealised.ledger++ More background:++ "ROI" stands for "return on investment". Traditionally this was+computed as a difference between current value of investment and its+initial value, expressed in percentage of the initial value.++ However, this approach is only practical in simple cases, where+investments receives no in-flows or out-flows of money, and where 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.++ Internal rate of return, or "IRR" (also called "money-weighted rate+of return") takes into account effects of in-flows and out-flows.+Naively, if you are withdrawing from your investment, your future gains+would be smaller (in absolute numbers), and will be a smaller percentage+of your initial investment, and if you are adding to your investment,+you will receive bigger absolute gains (but probably at the same rate of+return). IRR is a way to compute rate of return for each period between+in-flow or out-flow of money, and then combine them in a way that gives+you an annual rate of return that investment is expected to generate.++ As mentioned before, in-flows and out-flows would be any cash that+you personally put in or withdraw, and for the "roi" command, these are+transactions that involve account(s) matching '--inv' argument and NOT+involve account(s) matching '--pnl' argument.++ Presumably, you will also record changes in the value of your+investment, and balance them against "profit and loss" (or "unrealized+gains") account. Note that in order for IRR to compute the precise+effect of your in-flows and out-flows on the rate of return, you will+need to record the value of your investement on or close to the days+when in- or out-flows occur.++ Implementation of IRR in hledger should match the 'XIRR' formula in+Excel.++ Second way to compute rate of return that 'roi' command implements is+called "time-weighted rate of return" or "TWR". Like IRR, it will also+break the history of your investment into periods between in-flows and+out-flows to compute rate of return per each period and then a compound+rate of return. However, internal workings of TWR are quite different.++ In technical terms, IRR uses the same approach as computation of net+present value, and tries to find a discount rate that makes net present+value of all the cash flows of your investment to add up to zero. This+could be hard to wrap your head around, especially if you haven't done+discounted cash flow analysis before.++ TWR represents your investment as an imaginary "unit fund" where+in-flows/ out-flows lead to buying or selling "units" of your investment+and changes in its value change the value of "investment unit". Change+in "unit price" over the reporting period gives you rate of return of+your investment.++ References: * Explanation of rate of return * Explanation of IRR *+Explanation of TWR * Examples of computing IRR and TWR and discussion of+the limitations of both metrics++ More examples:++ Lets say that we found an investment in Snake Oil that is proising to+give us 10% annually:++2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-12-24 Recording the growth of Snake Oil+ investment:snake oil = $110+ equity:unrealized gains++ For now, basic computation of the rate of return, as well as IRR and+TWR, gives us the expected 10%:++$ hledger roi -Y --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+-----++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 110 | 10 || 10.00% | 10.00% |++---++------------+------------++---------------+----------+-------------+-----++--------+--------+++ However, lets say that shorty after investing in the Snake Oil we+started to have second thoughs, so we prompty withdrew $90, leaving only+$10 in. Before Christmas, though, we started to get the "fear of+mission out", so we put the $90 back in. So for most of the year, our+investment was just $10 dollars, and it gave us just $1 in growth:++2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil+ +2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil = $101+ equity:unrealized gains++ Now IRR and TWR are drastically different:++$ hledger roi -Y --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+-----++-------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++=======+=======++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101 | 1 || 9.32% | 1.00% |++---++------------+------------++---------------+----------+-------------+-----++-------+-------+++ Here, IRR tells us that we made close to 10% on the $10 dollars that+we had in the account most of the time. And TWR is ... just 1%? Why?++ Based on the transactions in our journal, TWR "think" that we are+buying back $90 worst of Snake Oil at the same price that it had at the+beginning of they year, and then after that our $100 investment gets $1+increase in value, or 1% of $100. Let's take a closer look at what is+happening here by asking for quarterly reports instead of annual:++$ hledger roi -Q --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+-----++--------+-------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+=====++========+=======++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10 | 0 || 0.00% | 0.00% |+| 2 || 2019-04-01 | 2019-06-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 3 || 2019-07-01 | 2019-09-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+| 4 || 2019-10-01 | 2019-12-31 || 10 | 90 | 101 | 1 || 37.80% | 4.03% |++---++------------+------------++---------------+----------+-------------+-----++--------+-------+++ Now both IRR and TWR are thrown off by the fact that all of the+growth for our investment happens in Q4 2019. This happes because IRR+computation is still yielding 9.32% and TWR is still 1%, but this time+these are rates for three month period instead of twelve, so in order to+get an annual rate they should be multiplied by four!++ Let's try to keep a better record of how Snake Oil grew in value:++2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil++2019-02-28 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-06-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-09-30 Recording the growth of Snake Oil+ investment:snake oil + equity:unrealized gains -$0.25++2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++2019-12-31 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ Would our quartery report look better now? Almost:++$ hledger roi -Q --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 1.00% |++---++------------+------------++---------------+----------+-------------+------++--------+--------+++ Something is still wrong with TWR computation for Q4, and if you have+been paying attention you know what it is already: big $90 buy-back is+recorded prior to the only transaction that captures the change of value+of Snake Oil that happened in this time period. Lets combine+transactions from 30th and 31st of Dec into one:++2019-12-30 Fear of missing out and growth of Snake Oil+ assets:cash -$90+ investment:snake oil+ equity:unrealized gains -$0.25++ Now growth of investment properly affects its price at the time of+buy-back:++$ hledger roi -Q --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+------++--------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++========+========++| 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+| 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+| 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+| 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 9.57% |++---++------------+------------++---------------+----------+-------------+------++--------+--------+++ And for annual report, TWR now reports the exact profitability of our+investment:++$ hledger roi -Y --inv investment --pnl "unrealized"++---++------------+------------++---------------+----------+-------------+------++-------+--------++| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |++===++============+============++===============+==========+=============+======++=======+========++| 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101.00 | 1.00 || 9.32% | 10.00% |++---++------------+------------++---------------+----------+-------------+------++-------+--------++++File: hledger.info, Node: stats, Next: tags, Prev: roi, Up: COMMANDS++3.28 stats+==========++stats+Show some journal statistics.++ The stats command displays summary information for the whole journal,+or a matched part of it. With a reporting interval, it shows a report+for each report period.++ Example:++$ hledger stats+Main journal file : /src/hledger/examples/sample.journal+Included journal files : +Transactions span : 2008-01-01 to 2009-01-01 (366 days)+Last transaction : 2008-12-31 (2333 days ago)+Transactions : 5 (0.0 per day)+Transactions last 30 days: 0 (0.0 per day)+Transactions last 7 days : 0 (0.0 per day)+Payees/descriptions : 5+Accounts : 8 (depth 3)+Commodities : 1 ($)+Market prices : 12 ($)++ This command also supports output destination and output format+selection.+++File: hledger.info, Node: tags, Next: test, Prev: stats, Up: COMMANDS++3.29 tags+=========++tags+List the unique tag names used in the journal. With a TAGREGEX+argument, only tag names matching the regular expression (case+insensitive) are shown. With QUERY arguments, only transactions+matching the query are considered.++ With the -values flag, the tags' unique values are listed instead.++ With -parsed flag, all tags or values are shown in the order they are+parsed from the input data, including duplicates.++ With -E/-empty, any blank/empty values will also be shown, otherwise+they are omitted.+++File: hledger.info, Node: test, Next: Add-on commands, Prev: tags, Up: COMMANDS++3.30 test+=========++test+Run built-in unit tests.++ This command runs the unit tests built in to hledger and hledger-lib,+printing the results on stdout. If any test fails, the exit code will+be non-zero.++ This is mainly used by hledger developers, but you can also use it to+sanity-check the installed hledger executable on your platform. All+tests are expected to pass - if you ever see a failure, please report as+a bug!++ This command also accepts tasty test runner options, written after a+- (double hyphen). Eg to run only the tests in Hledger.Data.Amount,+with ANSI colour codes disabled:++$ hledger test -- -pData.Amount --color=never++ For help on these, see https://github.com/feuerbach/tasty#options+('-- --help' currently doesn't show them).+++File: hledger.info, Node: Add-on commands, Prev: test, Up: COMMANDS++3.31 Add-on commands+====================++hledger also searches for external add-on commands, and will include+these in the commands list. These are programs or scripts in your PATH+whose name starts with 'hledger-' and ends with a recognised file+extension (currently: no extension, 'bat','com','exe',+'hs','lhs','pl','py','rb','rkt','sh').++ Add-ons can be invoked like any hledger command, but there are a few+things to be aware of. Eg if the 'hledger-web' add-on is installed,++ * 'hledger -h web' shows hledger's help, while 'hledger web -h' shows+ hledger-web's help.++ * Flags specific to the add-on must have a preceding '--' to hide+ them from hledger. So 'hledger web --serve --port 9000' will be+ rejected; you must use 'hledger web -- --serve --port 9000'.++ * You can always run add-ons directly if preferred: 'hledger-web+ --serve --port 9000'.++ Add-ons are a relatively easy way to add local features or experiment+with new ideas. They can be written in any language, but haskell+scripts have a big advantage: they can use the same hledger (and+haskell) library functions that built-in commands do, for command-line+options, journal parsing, reporting, etc.++ Two important add-ons are the hledger-ui and hledger-web user+interfaces. These are maintained and released along with hledger:++* Menu:++* ui::+* web::+* iadd::+* interest::+++File: hledger.info, Node: ui, Next: web, Up: Add-on commands++3.31.1 ui+---------++hledger-ui provides an efficient terminal interface.+++File: hledger.info, Node: web, Next: iadd, Prev: ui, Up: Add-on commands++3.31.2 web+----------++hledger-web provides a simple web interface.++ Third party add-ons, maintained separately from hledger, include:+++File: hledger.info, Node: iadd, Next: interest, Prev: web, Up: Add-on commands++3.31.3 iadd+-----------++hledger-iadd is a more interactive, terminal UI replacement for the add+command.+++File: hledger.info, Node: interest, Prev: iadd, Up: Add-on commands++3.31.4 interest+---------------++hledger-interest generates interest transactions for an account+according to various schemes.++ A few more experimental or old add-ons can be found in hledger's bin/+directory. These are typically prototypes and not guaranteed to work.+++File: hledger.info, Node: ENVIRONMENT, Next: FILES, Prev: COMMANDS, Up: Top++4 ENVIRONMENT+*************++*LEDGER_FILE* The journal file path when not specified with '-f'.+Default: '~/.hledger.journal' (on windows, perhaps+'C:/Users/USER/.hledger.journal').++ A typical value is '~/DIR/YYYY.journal', where DIR is a+version-controlled finance directory and YYYY is the current year. Or+'~/DIR/current.journal', where current.journal is a symbolic link to+YYYY.journal.++ On Mac computers, you can set this and other environment variables in+a more thorough way that also affects applications started from the GUI+(say, an Emacs dock icon). Eg on MacOS Catalina I have a+'~/.MacOSX/environment.plist' file containing++{+ "LEDGER_FILE" : "~/finance/current.journal"+}++ To see the effect you may need to 'killall Dock', or reboot.++ *COLUMNS* The screen width used by the register command. Default:+the full terminal width.++ *NO_COLOR* If this variable exists with any value, hledger will not+use ANSI color codes in terminal output. This overrides the+-color/-colour option.+++File: hledger.info, Node: FILES, Next: LIMITATIONS, Prev: ENVIRONMENT, Up: Top++5 FILES+*******++Reads data from one or more files in hledger journal, timeclock,+timedot, or CSV format specified with '-f', or '$LEDGER_FILE', or+'$HOME/.hledger.journal' (on windows, perhaps+'C:/Users/USER/.hledger.journal').+++File: hledger.info, Node: LIMITATIONS, Next: TROUBLESHOOTING, Prev: FILES, Up: Top++6 LIMITATIONS+*************++The need to precede addon command options with '--' when invoked from+hledger is awkward.++ When input data contains non-ascii characters, a suitable system+locale must be configured (or there will be an unhelpful error). Eg on+POSIX, set LANG to something other than C.++ In a Microsoft Windows CMD window, non-ascii characters and colours+are not supported.++ On Windows, non-ascii characters may not display correctly when+running a hledger built in CMD in MSYS/CYGWIN, or vice-versa.++ In a Cygwin/MSYS/Mintty window, the tab key is not supported in+hledger add.++ Not all of Ledger's journal file syntax is supported. See file+format differences.++ On large data files, hledger is slower and uses more memory than+Ledger.+++File: hledger.info, Node: TROUBLESHOOTING, Prev: LIMITATIONS, Up: Top++7 TROUBLESHOOTING+*****************++Here are some issues you might encounter when you run hledger (and+remember you can also seek help from the IRC channel, mail list or bug+tracker):++ *Successfully installed, but "No command 'hledger' found"*+stack and cabal install binaries into a special directory, which should+be added to your PATH environment variable. Eg on unix-like systems,+that is ~/.local/bin and ~/.cabal/bin respectively.++ *I set a custom LEDGER_FILE, but hledger is still using the default+file*+'LEDGER_FILE' should be a real environment variable, not just a shell+variable. The command 'env | grep LEDGER_FILE' should show it. You may+need to use 'export'. Here's an explanation.++ *Getting errors like "Illegal byte sequence" or "Invalid or+incomplete multibyte or wide character" or "commitAndReleaseBuffer:+invalid argument (invalid character)"*+Programs compiled with GHC (hledger, haskell build tools, etc.) need to+have a UTF-8-aware locale configured in the environment, otherwise they+will fail with these kinds of errors when they encounter non-ascii+characters.++ To fix it, set the LANG environment variable to some locale which+supports UTF-8. The locale you choose must be installed on your system.++ Here's an example of setting LANG temporarily, on Ubuntu GNU/Linux:++$ file my.journal+my.journal: UTF-8 Unicode text # the file is UTF8-encoded+$ echo $LANG+C # LANG is set to the default locale, which does not support UTF8+$ locale -a # which locales are installed ?+C+en_US.utf8 # here's a UTF8-aware one we can use+POSIX+$ LANG=en_US.utf8 hledger -f my.journal print # ensure it is used for this command++ If available, 'C.UTF-8' will also work. If your preferred locale+isn't listed by 'locale -a', you might need to install it. Eg on+Ubuntu/Debian:++$ apt-get install language-pack-fr+$ locale -a+C+en_US.utf8+fr_BE.utf8+fr_CA.utf8+fr_CH.utf8+fr_FR.utf8+fr_LU.utf8+POSIX+$ LANG=fr_FR.utf8 hledger -f my.journal print++ Here's how you could set it permanently, if you use a bash shell:++$ echo "export LANG=en_US.utf8" >>~/.bash_profile+$ bash --login++ Exact spelling and capitalisation may be important. Note the+difference on MacOS ('UTF-8', not 'utf8'). Some platforms (eg ubuntu)+allow variant spellings, but others (eg macos) require it to be exact:++$ locale -a | grep -iE en_us.*utf+en_US.UTF-8+$ LANG=en_US.UTF-8 hledger -f my.journal print+++Tag Table:+Node: Top68+Node: COMMON TASKS2315+Ref: #common-tasks2427+Node: Getting help2834+Ref: #getting-help2966+Node: Constructing command lines3519+Ref: #constructing-command-lines3711+Node: Starting a journal file4408+Ref: #starting-a-journal-file4606+Node: Setting opening balances5794+Ref: #setting-opening-balances5990+Node: Recording transactions9131+Ref: #recording-transactions9311+Node: Reconciling9867+Ref: #reconciling10010+Node: Reporting12267+Ref: #reporting12407+Node: Migrating to a new file16406+Ref: #migrating-to-a-new-file16554+Node: OPTIONS16853+Ref: #options16960+Node: General options17346+Ref: #general-options17471+Node: Command options20872+Ref: #command-options21023+Node: Command arguments21421+Ref: #command-arguments21568+Node: Queries22448+Ref: #queries22603+Node: Special characters in arguments and queries26565+Ref: #special-characters-in-arguments-and-queries26793+Node: More escaping27244+Ref: #more-escaping27406+Node: Even more escaping27702+Ref: #even-more-escaping27896+Node: Less escaping28567+Ref: #less-escaping28729+Node: Unicode characters28974+Ref: #unicode-characters29156+Node: Input files30568+Ref: #input-files30704+Node: Strict mode33003+Ref: #strict-mode33139+Node: Output destination33787+Ref: #output-destination33939+Node: Output format34364+Ref: #output-format34516+Node: Regular expressions36683+Ref: #regular-expressions36840+Node: Smart dates38576+Ref: #smart-dates38727+Node: Report start & end date40088+Ref: #report-start-end-date40260+Node: Report intervals41757+Ref: #report-intervals41922+Node: Period expressions42312+Ref: #period-expressions42472+Node: Depth limiting46845+Ref: #depth-limiting46989+Node: Pivoting47321+Ref: #pivoting47444+Node: Valuation49120+Ref: #valuation49222+Node: -B Cost49911+Ref: #b-cost50015+Node: -V Value50148+Ref: #v-value50294+Node: -X Value in specified commodity50489+Ref: #x-value-in-specified-commodity50688+Node: Valuation date50837+Ref: #valuation-date51005+Node: Market prices51427+Ref: #market-prices51607+Node: --infer-value market prices from transactions52549+Ref: #infer-value-market-prices-from-transactions52798+Node: Valuation commodity54080+Ref: #valuation-commodity54289+Node: Simple valuation examples55515+Ref: #simple-valuation-examples55717+Node: --value Flexible valuation56376+Ref: #value-flexible-valuation56584+Node: More valuation examples58531+Ref: #more-valuation-examples58740+Node: Effect of valuation on reports60745+Ref: #effect-of-valuation-on-reports60933+Node: COMMANDS67952+Ref: #commands68060+Node: accounts69146+Ref: #accounts69244+Node: activity69943+Ref: #activity70053+Node: add70436+Ref: #add70537+Node: aregister73330+Ref: #aregister73442+Node: aregister and custom posting dates74815+Ref: #aregister-and-custom-posting-dates74988+Ref: #output-format-175581+Node: balance75986+Ref: #balance76103+Node: Classic balance report77583+Ref: #classic-balance-report77756+Node: Customising the classic balance report79080+Ref: #customising-the-classic-balance-report79308+Node: Colour support81384+Ref: #colour-support81551+Node: Flat mode81647+Ref: #flat-mode81795+Node: Depth limited balance reports82208+Ref: #depth-limited-balance-reports82393+Node: Percentages82849+Ref: #percentages83006+Node: Sorting by amount84143+Ref: #sorting-by-amount84309+Node: Multicolumn balance report84803+Ref: #multicolumn-balance-report84989+Node: Budget report90586+Ref: #budget-report90729+Node: Budget report start date96018+Ref: #budget-report-start-date96183+Node: Nested budgets97515+Ref: #nested-budgets97660+Ref: #output-format-2101143+Node: balancesheet101304+Ref: #balancesheet101440+Node: balancesheetequity102952+Ref: #balancesheetequity103101+Node: cashflow104177+Ref: #cashflow104299+Node: check105515+Ref: #check105618+Node: Basic checks106222+Ref: #basic-checks106338+Node: Strict checks106831+Ref: #strict-checks106970+Node: Other checks107213+Ref: #other-checks107350+Node: Addon checks107648+Ref: #addon-checks107763+Node: close108216+Ref: #close108318+Node: close usage109840+Ref: #close-usage109933+Node: codes112746+Ref: #codes112854+Node: commodities113566+Ref: #commodities113693+Node: descriptions113775+Ref: #descriptions113903+Node: diff114207+Ref: #diff114313+Node: files115360+Ref: #files115460+Node: help115607+Ref: #help115707+Node: import116788+Ref: #import116902+Node: Importing balance assignments117824+Ref: #importing-balance-assignments118005+Node: Commodity display styles118654+Ref: #commodity-display-styles118825+Node: incomestatement118954+Ref: #incomestatement119087+Node: notes120432+Ref: #notes120545+Node: payees120913+Ref: #payees121019+Node: prices121439+Ref: #prices121545+Node: print121886+Ref: #print121996+Node: print-unique126792+Ref: #print-unique126918+Node: register127203+Ref: #register127330+Node: Custom register output131779+Ref: #custom-register-output131908+Node: register-match133245+Ref: #register-match133379+Node: rewrite133730+Ref: #rewrite133845+Node: Re-write rules in a file135700+Ref: #re-write-rules-in-a-file135834+Node: Diff output format137044+Ref: #diff-output-format137213+Node: rewrite vs print --auto138305+Ref: #rewrite-vs.-print---auto138484+Node: roi139040+Ref: #roi139138+Node: stats151348+Ref: #stats151447+Node: tags152235+Ref: #tags152333+Node: test152852+Ref: #test152960+Node: Add-on commands153707+Ref: #add-on-commands153824+Node: ui155167+Ref: #ui155255+Node: web155309+Ref: #web155412+Node: iadd155528+Ref: #iadd155639+Node: interest155721+Ref: #interest155828+Node: ENVIRONMENT156068+Ref: #environment156180+Node: FILES157165+Ref: #files-1157268+Node: LIMITATIONS157481+Ref: #limitations157600+Node: TROUBLESHOOTING158342+Ref: #troubleshooting158455 End Tag Table
hledger.txt view
@@ -464,3000 +464,3381 @@ disable balance assertion checks (note: does not disable balance assignments) - General reporting options:-- -b --begin=DATE- include postings/txns on or after this date-- -e --end=DATE- include postings/txns before this date-- -D --daily- multiperiod/multicolumn report by day-- -W --weekly- multiperiod/multicolumn report by week-- -M --monthly- multiperiod/multicolumn report by month-- -Q --quarterly- multiperiod/multicolumn report by quarter-- -Y --yearly- multiperiod/multicolumn report by year-- -p --period=PERIODEXP- set start date, end date, and/or reporting interval all at once- using period expressions syntax-- --date2- match the secondary date instead (see command help for other ef-- fects)-- -U --unmarked- include only unmarked postings/txns (can combine with -P or -C)-- -P --pending- include only pending postings/txns-- -C --cleared- include only cleared postings/txns-- -R --real- include only non-virtual postings-- -NUM --depth=NUM- hide/aggregate accounts or postings more than NUM levels deep-- -E --empty- show items with zero amount, normally hidden (and vice-versa in- hledger-ui/hledger-web)-- -B --cost- convert amounts to their cost/selling amount at transaction time-- -V --market- convert amounts to their market value in default valuation com-- modities-- -X --exchange=COMM- convert amounts to their market value in commodity COMM-- --value- convert amounts to cost or market value, more flexibly than- -B/-V/-X-- --infer-value- with -V/-X/--value, also infer market prices from transactions-- --auto apply automated posting rules to modify transactions.-- --forecast- generate future transactions from periodic transaction rules,- for the next 6 months or till report end date. In hledger-ui,- also make ordinary future transactions visible.-- --color=WHEN (or --colour=WHEN)- Should color-supporting commands use ANSI color codes in text- output. 'auto' (default): whenever stdout seems to be a color-- supporting terminal. 'always' or 'yes': always, useful eg when- piping output into 'less -R'. 'never' or 'no': never. A- NO_COLOR environment variable overrides this.-- When a reporting option appears more than once in the command line, the- last one takes precedence.-- Some reporting options can also be written as query arguments.-- Command options- To see options for a particular command, including command-specific op-- tions, run: hledger COMMAND -h.-- Command-specific options must be written after the command name, eg:- hledger print -x.-- Additionally, if the command is an addon, you may need to put its op-- tions after a double-hyphen, eg: hledger ui -- --watch. Or, you can- run the addon executable directly: hledger-ui --watch.-- Command arguments- Most hledger commands accept arguments after the command name, which- are often a query, filtering the data in some way.-- You can save a set of command line options/arguments in a file, and- then reuse them by writing @FILENAME as a command line argument. Eg:- hledger bal @foo.args. (To prevent this, eg if you have an argument- that begins with a literal @, precede it with --, eg: hledger bal --- @ARG).-- Inside the argument file, each line should contain just one option or- argument. Avoid the use of spaces, except inside quotes (or you'll see- a confusing error). Between a flag and its argument, use = (or noth-- ing). Bad:-- assets depth:2- -X USD-- Good:-- assets- depth:2- -X=USD-- For special characters (see below), use one less level of quoting than- you would at the command prompt. Bad:-- -X"$"-- Good:-- -X$-- See also: Save frequently used options.-- Queries- One of hledger's strengths is being able to quickly report on precise- subsets of your data. Most commands accept an optional query expres-- sion, written as arguments after the command name, to filter the data- by date, account name or other criteria. The syntax is similar to a- web search: one or more space-separated search terms, quotes to enclose- whitespace, prefixes to match specific fields, a not: prefix to negate- the match.-- We do not yet support arbitrary boolean combinations of search terms;- instead most commands show transactions/postings/accounts which match- (or negatively match):-- o any of the description terms AND-- o any of the account terms AND-- o any of the status terms AND-- o all the other terms.-- The print command instead shows transactions which:-- o match any of the description terms AND-- o have any postings matching any of the positive account terms AND-- o have no postings matching any of the negative account terms AND-- o match all the other terms.-- The following kinds of search terms can be used. Remember these can- also be prefixed with not:, eg to exclude a particular subaccount.-- REGEX, acct:REGEX- match account names by this regular expression. (With no pre-- fix, acct: is assumed.) same as above-- amt:N, amt:<N, amt:<=N, amt:>N, amt:>=N- match postings with a single-commodity amount that is equal to,- less than, or greater than N. (Multi-commodity amounts are not- tested, and will always match.) 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.-- code:REGEX- match by transaction code (eg check number)-- cur:REGEX- match postings or transactions including any amounts whose cur-- rency/commodity symbol is fully matched by REGEX. (For a par-- tial match, use .*REGEX.*). Note, to match characters which are- regex-significant, like the dollar sign ($), you need to prepend- \. And when using the command line you need to add one more- level of quoting to hide it from the shell, so eg do: hledger- print cur:'\$' or hledger print cur:\\$.-- desc:REGEX- match transaction descriptions.-- date:PERIODEXPR- match dates within the specified period. PERIODEXPR is a period- expression (with no report interval). Examples: date:2016,- date:thismonth, date:2000/2/1-2/15, date:lastweek-. If the- --date2 command line flag is present, this matches secondary- dates instead.-- date2:PERIODEXPR- match secondary dates within the specified period.-- depth:N- match (or display, depending on command) accounts at or above- this depth-- note:REGEX- match transaction notes (part of description right of |, or- whole description when there's no |)-- payee:REGEX- match transaction payee/payer names (part of description left of- |, or whole description when there's no |)-- real:, real:0- match real or virtual postings respectively-- status:, status:!, status:*- match unmarked, pending, or cleared transactions respectively-- tag:REGEX[=REGEX]- match by tag name, and optionally also by tag value. Note a- tag: query is considered to match a transaction if it matches- any of the postings. Also remember that postings inherit the- tags of their parent transaction.-- The following special search term is used automatically in hledger-web,- only:-- inacct:ACCTNAME- tells hledger-web to show the transaction register for this ac-- count. Can be filtered further with acct etc.-- Some of these can also be expressed as command-line options (eg depth:2- is equivalent to --depth 2). Generally you can mix options and query- arguments, and the resulting query will be their intersection (perhaps- excluding the -p/--period option).-- Special characters in arguments and queries- In shell command lines, option and argument values which contain "prob-- lematic" characters, ie spaces, and also characters significant to your- shell such as <, >, (, ), | and $, should be escaped by enclosing them- in quotes or by writing backslashes before the characters. Eg:-- hledger register -p 'last year' "accounts receivable (receiv-- able|payable)" amt:\>100.-- More escaping- Characters significant both to the shell and in regular expressions may- need one extra level of escaping. These include parentheses, the pipe- symbol and the dollar sign. Eg, to match the dollar symbol, bash users- should do:-- hledger balance cur:'\$'-- or:-- hledger balance cur:\\$-- Even more escaping- When hledger runs an addon executable (eg you type hledger ui, hledger- runs hledger-ui), it de-escapes command-line options and arguments- once, so you might need to triple-escape. Eg in bash, running the ui- command and matching the dollar sign, it's:-- hledger ui cur:'\\$'-- or:-- hledger ui cur:\\\\$-- If you asked why four slashes above, this may help:-- unescaped: $- escaped: \$- double-escaped: \\$- triple-escaped: \\\\$-- (The number of backslashes in fish shell is left as an exercise for the- reader.)-- You can always avoid the extra escaping for addons by running the addon- directly:-- hledger-ui cur:\\$-- Less escaping- Inside an argument file, or in the search field of hledger-ui or- hledger-web, or at a GHCI prompt, you need one less level of escaping- than at the command line. And backslashes may work better than quotes.- Eg:-- ghci> :main balance cur:\$-- Unicode characters- hledger is expected to handle non-ascii characters correctly:-- o they should be parsed correctly in input files and on the command- line, by all hledger tools (add, iadd, hledger-web's search/add/edit- forms, etc.)-- o they should be displayed correctly by all hledger tools, and on-- screen alignment should be preserved.-- This requires a well-configured environment. Here are some tips:-- o A system locale must be configured, and it must be one that can de-- code the characters being used. In bash, you can set a locale like- this: export LANG=en_US.UTF-8. There are some more details in Trou-- bleshooting. This step is essential - without it, hledger will quit- on encountering a non-ascii character (as with all GHC-compiled pro-- grams).-- o your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)- must support unicode-- o the terminal must be using a font which includes the required unicode- glyphs-- o the terminal should be configured to display wide characters as dou-- ble width (for report alignment)-- o 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 stan-- dard 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).-- Input files- hledger reads transactions from a data file (and the add command writes- to it). By default this file is $HOME/.hledger.journal (or on Windows,- something like C:/Users/USER/.hledger.journal). You can override this- with the $LEDGER_FILE environment variable:-- $ setenv LEDGER_FILE ~/finance/2016.journal- $ hledger stats-- or with the -f/--file option:-- $ hledger -f /some/file stats-- The file name - (hyphen) means standard input:-- $ cat some.journal | hledger -f--- Usually the data file is in hledger's journal format, but it can be in- any of the supported file formats, which currently are:-- Reader: Reads: Used for file exten-- sions:- ------------------------------------------------------------------------------ journal hledger journal files and some Ledger .journal .j .hledger- journals, for transactions .ledger- time- timeclock files, for precise time log- .timeclock- clock ging- timedot timedot files, for approximate time .timedot- logging- csv comma/semicolon/tab/other-separated .csv .ssv .tsv- values, for data import-- hledger detects the format automatically based on the file extensions- shown above. If it can't recognise the file extension, it assumes- journal format. So for non-journal files, it's important to use a- recognised file extension, so as to either read successfully or to show- relevant error messages.-- When you can't ensure the right file extension, not to worry: you can- force a specific reader/format by prefixing the file path with the for-- mat and a colon. Eg to read a .dat file as csv:-- $ hledger -f csv:/some/csv-file.dat stats- $ echo 'i 2009/13/1 08:00:00' | hledger print -ftimeclock:--- You can specify multiple -f options, to read multiple files as one big- journal. There are some limitations with this:-- o directives in one file will not affect the other files-- o balance assertions will not see any account balances from previous- files-- If you need either of those things, you can-- o use a single parent file which includes the others-- o or concatenate the files into one before reading, eg: cat a.journal- b.journal | hledger -f- CMD.-- 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:-- $ hledger print > foo.txt-- Some commands (print, register, stats, the balance commands) also pro-- vide the -o/--output-file option, which does the same thing without- needing the shell. Eg:-- $ hledger print -o foo.txt- $ hledger print -o - # write to stdout (the default)-- Output format- Some commands (print, register, the balance commands) offer a choice of- output format. In addition to the usual plain text format (txt), there- are CSV (csv), HTML (html), JSON (json) and SQL (sql). This is con-- trolled by the -O/--output-format option:-- $ hledger print -O csv-- or, by a file extension specified with -o/--output-file:-- $ hledger balancesheet -o foo.html # write HTML to foo.html-- The -O option can be used to override the file extension if needed:-- $ hledger balancesheet -o foo.txt -O html # write HTML to foo.txt-- Some notes about JSON output:-- o This feature is marked experimental, and not yet much used; you- should expect our JSON to evolve. Real-world feedback is welcome.-- o Our JSON is rather large and verbose, as it is quite a faithful rep-- resentation of hledger's internal data types. To understand the- JSON, read the Haskell type definitions, which are mostly in- https://github.com/simonmichael/hledger/blob/master/hledger-- lib/Hledger/Data/Types.hs.-- o hledger represents quantities as Decimal values storing up to 255- significant digits, eg for repeating decimals. Such numbers can- arise in practice (from automatically-calculated transaction prices),- and would break most JSON consumers. So in JSON, we show quantities- as simple Numbers with at most 10 decimal places. We don't limit the- number of integer digits, but that part is under your control. We- hope this approach will not cause problems in practice; if you find- otherwise, please let us know. (Cf #1195)-- Notes about SQL output:-- o SQL output is also marked experimental, and much like JSON could use- real-world feedback.-- o SQL output is expected to work with sqlite, MySQL and PostgreSQL-- o SQL output is structured with the expectations that statements will- be executed in the empty database. If you already have tables cre-- ated via SQL output of hledger, you would probably want to either- clear tables of existing data (via delete or truncate SQL statements)- or drop tables completely as otherwise your postings will be duped.-- Regular expressions- hledger uses regular expressions in a number of places:-- o query terms, on the command line and in the hledger-web search form:- REGEX, desc:REGEX, cur:REGEX, tag:...=REGEX-- o CSV rules conditional blocks: if REGEX ...-- o account alias directives and options: alias /REGEX/ = REPLACEMENT,- --alias /REGEX/=REPLACEMENT-- hledger's regular expressions come from the regex-tdfa library. If- they're not doing what you expect, it's important to know exactly what- they support:-- 1. they are case insensitive-- 2. they are infix matching (they do not need to match the entire thing- being matched)-- 3. they are POSIX ERE (extended regular expressions)-- 4. they also support GNU word boundaries (\b, \B, \<, \>)-- 5. they do not support backreferences; if you write \1, it will match- the digit 1. Except when doing text replacement, eg in account- aliases, where backreferences can be used in the replacement string- to reference capturing groups in the search regexp.-- 6. they do not support mode modifiers ((?s)), character classes (\w,- \d), or anything else not mentioned above.-- Some things to note:-- o In the alias directive and --alias option, regular expressions must- be enclosed in forward slashes (/REGEX/). Elsewhere in hledger,- these are not required.-- o In queries, to match a regular expression metacharacter like $ as a- literal character, prepend a backslash. Eg to search for amounts- with the dollar sign in hledger-web, write cur:\$.-- o On the command line, some metacharacters like $ have a special mean-- ing to the shell and so must be escaped at least once more. See Spe-- cial characters.-- Smart dates- hledger's user interfaces accept a flexible "smart date" syntax (unlike- dates in the journal file). Smart dates allow some english words, can- be relative to today's date, and can have less-significant date parts- omitted (defaulting to 1).-- Examples:-- 2004/10/1, 2004-01-01, exact date, several separators allowed. Year- 2004.9.1 is 4+ digits, month is 1-12, day is 1-31- 2004 start of year- 2004/10 start of month- 10/1 month and day in current year- 21 day in current month- october, oct start of month in current year- yesterday, today, tomor- -1, 0, 1 days from today- row- last/this/next -1, 0, 1 periods from the current period- day/week/month/quar-- ter/year- 20181201 8 digit YYYYMMDD with valid year month and day- 201812 6 digit YYYYMM with valid year and month-- Counterexamples - malformed digit sequences might give surprising re-- sults:-- 201813 6 digits with an invalid month is parsed as start of- 6-digit year- 20181301 8 digits with an invalid month is parsed as start of- 8-digit year- 20181232 8 digits with an invalid day gives an error- 201801012 9+ digits beginning with a valid YYYYMMDD gives an error-- Report start & end date- Most hledger reports show the full span of time represented by the- journal data, by default. So, the effective report start and end dates- will be the earliest and latest transaction or posting dates found in- the journal.-- Often you will want to see a shorter time span, such as the current- month. You can specify a start and/or end date using -b/--begin,- -e/--end, -p/--period or a date: query (described below). All of these- accept the smart date syntax.-- Some notes:-- o As in Ledger, end dates are exclusive, so you need to write the date- after the last day you want to include.-- o As noted in reporting options: among start/end dates specified with- options, the last (i.e. right-most) option takes precedence.-- o The effective report start and end dates are the intersection of the- start/end dates from options and that from date: queries. That is,- date:2019-01 date:2019 -p'2000 to 2030' yields January 2019, the- smallest common time span.-- Examples:-- -b 2016/3/17 begin on St. Patrick's day 2016- -e 12/1 end at the start of december 1st of the current year- (11/30 will be the last date included)- -b thismonth all transactions on or after the 1st of the current month- -p thismonth all transactions in the current month- date:2016/3/17.. the above written as queries instead (.. can also be re-- placed with -)- date:..12/1- date:thismonth..- date:thismonth-- Report intervals- A report interval can be specified so that commands like register, bal-- ance and activity will divide their reports into multiple subperiods.- The basic intervals can be selected with one of -D/--daily,- -W/--weekly, -M/--monthly, -Q/--quarterly, or -Y/--yearly. More com-- plex intervals may be specified with a period expression. Report in-- tervals can not be specified with a query.-- Period expressions- The -p/--period option accepts period expressions, a shorthand way of- expressing a start date, end date, and/or report interval all at once.-- Here's a basic period expression specifying the first quarter of 2009.- Note, hledger always treats start dates as inclusive and end dates as- exclusive:-- -p "from 2009/1/1 to 2009/4/1"-- Keywords like "from" and "to" are optional, and so are the spaces, as- long as you don't run two dates together. "to" can also be written as- ".." or "-". These are equivalent to the above:-- -p "2009/1/1 2009/4/1"- -p2009/1/1to2009/4/1- -p2009/1/1..2009/4/1-- Dates are smart dates, so if the current year is 2009, the above can- also be written as:-- -p "1/1 4/1"- -p "january-apr"- -p "this year to 4/1"-- If you specify only one date, the missing start or end date will be the- earliest or latest transaction in your journal:-- -p "from 2009/1/1" everything after january- 1, 2009- -p "from 2009/1" the same- -p "from 2009" the same-- -p "to 2009" everything before january- 1, 2009-- A single date with no "from" or "to" defines both the start and end- date like so:-- -p "2009" the year 2009; equivalent- to "2009/1/1 to 2010/1/1"- -p "2009/1" the month of jan; equiva-- lent to "2009/1/1 to- 2009/2/1"- -p "2009/1/1" just that day; equivalent- to "2009/1/1 to 2009/1/2"-- Or you can specify a single quarter like so:-- -p "2009Q1" first quarter of 2009,- equivalent to "2009/1/1 to- 2009/4/1"- -p "q4" fourth quarter of the cur-- rent year-- The argument of -p can also begin with, or be, a report interval ex-- pression. The basic report intervals are daily, weekly, monthly, quar-- terly, or yearly, which have the same effect as the -D,-W,-M,-Q, or -Y- flags. Between report interval and start/end dates (if any), the word- in is optional. Examples:-- -p "weekly from 2009/1/1 to 2009/4/1"- -p "monthly in 2008"- -p "quarterly"-- Note that weekly, monthly, quarterly and yearly intervals will always- start on the first day on week, month, quarter or year accordingly, and- will end on the last day of same period, even if associated period ex-- pression specifies different explicit start and end date.-- For example:-- -p "weekly from 2009/1/1 starts on 2008/12/29, closest preceding Mon-- to 2009/4/1" day- -p "monthly in starts on 2018/11/01- 2008/11/25"- -p "quarterly from starts on 2009/04/01, ends on 2009/06/30,- 2009-05-05 to 2009-06-01" which are first and last days of Q2 2009- -p "yearly from starts on 2009/01/01, first day of 2009- 2009-12-29"-- The following more complex report intervals are also supported: bi-- weekly, fortnightly, bimonthly, every day|week|month|quarter|year, ev-- ery N days|weeks|months|quarters|years.-- All of these will start on the first day of the requested period and- end on the last one, as described above.-- Examples:-- -p "bimonthly from 2008" periods will have boundaries on 2008/01/01,- 2008/03/01, ...- -p "every 2 weeks" starts on closest preceding Monday- -p "every 5 month from periods will have boundaries on 2009/03/01,- 2009/03" 2009/08/01, ...-- If you want intervals that start on arbitrary day of your choosing and- span a week, month or year, you need to use any of the following:-- every Nth day of week, every <weekday>, every Nth day [of month], every- Nth weekday [of month], every MM/DD [of year], every Nth MMM [of year],- every MMM Nth [of year].-- Examples:-- -p "every 2nd day of periods will go from Tue to Tue- week"- -p "every Tue" same- -p "every 15th day" period boundaries will be on 15th of each- month- -p "every 2nd Monday" period boundaries will be on second Monday of- each month- -p "every 11/05" yearly periods with boundaries on 5th of Nov- -p "every 5th Nov" same- -p "every Nov 5th" same-- Show historical balances at end of 15th each month (N is exclusive end- date):-- hledger balance -H -p "every 16th day"-- Group postings from start of wednesday to end of next tuesday (N is- start date and exclusive end date):-- hledger register checking -p "every 3rd day of week"-- Depth limiting- With the --depth N option (short form: -N), commands like account, bal-- ance and register will show only the uppermost accounts in the account- tree, down to level N. Use this when you want a summary with less de-- tail. This flag has the same effect as a depth: query argument (so -2,- --depth=2 or depth:2 are equivalent).-- Pivoting- Normally hledger sums amounts, and organizes them in a hierarchy, based- on account name. The --pivot FIELD option causes it to sum and orga-- nize hierarchy based on the value of some other field instead. FIELD- can be: code, description, payee, note, or the full name (case insensi-- tive) of any tag. As with account names, values containing colon:sepa-- rated:parts will be displayed hierarchically in reports.-- --pivot is a general option affecting all reports; you can think of- hledger transforming the journal before any other processing, replacing- every posting's account name with the value of the specified field on- that posting, inheriting it from the transaction or using a blank value- if it's not present.-- An example:-- 2016/02/16 Member Fee Payment- assets:bank account 2 EUR- income:member fees -2 EUR ; member: John Doe-- Normal balance report showing account names:-- $ hledger balance- 2 EUR assets:bank account- -2 EUR income:member fees- --------------------- 0-- Pivoted balance report, using member: tag values instead:-- $ hledger balance --pivot member- 2 EUR- -2 EUR John Doe- --------------------- 0-- One way to show only amounts with a member: value (using a query, de-- scribed below):-- $ hledger balance --pivot member tag:member=.- -2 EUR John Doe- --------------------- -2 EUR-- Another way (the acct: query matches against the pivoted "account- name"):-- $ hledger balance --pivot member acct:.- -2 EUR John Doe- --------------------- -2 EUR-- Valuation- Instead of reporting amounts in their original commodity, hledger can- convert them to cost/sale amount (using the conversion rate recorded in- the transaction), or to market value (using some market price on a cer-- tain date). This is controlled by the --value=TYPE[,COMMODITY] option,- but we also provide the simpler -B/-V/-X flags, and usually one of- those is all you need.-- -B: Cost- The -B/--cost flag converts amounts to their cost or sale amount at- transaction time, if they have a transaction price specified.-- -V: Value- The -V/--market flag converts amounts to market value in their default- valuation commodity, using the market prices in effect on the valuation- date(s), if any. More on these in a minute.-- -X: Value in specified commodity- The -X/--exchange=COMM option is like -V, except you tell it which cur-- rency you want to convert to, and it tries to convert everything to- that.-- Valuation date- Since market prices can change from day to day, market value reports- have a valuation date (or more than one), which determines which market- prices will be used.-- For single period reports, if an explicit report end date is specified,- that will be used as the valuation date; otherwise the valuation date- is "today".-- For multiperiod reports, each column/period is valued on the last day- of the period.-- Market prices- (experimental)-- 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 :-- 1. A declared market price or inferred market price: A's latest market- price in B on or before the valuation date as declared by a P direc-- tive, or (if the --infer-value flag is used) inferred from transac-- tion prices.-- 2. A reverse market price: the inverse of a declared or inferred market- price from B to A.-- 3. A chained market price: a synthetic price formed by combining the- shortest chain of market prices (any of the above types) leading- from A to B.-- Amounts for which no applicable market price can be found, are not con-- verted.-- --infer-value: market prices from transactions- (experimental)-- 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 transaction prices as additional market- prices (as Ledger does) ? We could produce value reports without need-- ing P directives at all.-- Adding the --infer-value flag to -V, -X or --value enables this. So- for example, hledger bs -V --infer-value will get market prices both- from P directives and from transactions.-- There is a downside: value reports can sometimes be affected in confus-- ing/undesired ways by your journal entries. If this happens to you,- read all of this Valuation section carefully, and try adding --debug or- --debug=2 to troubleshoot.-- --infer-value can infer market prices from:-- o multicommodity transactions with explicit prices (@/@@)-- o multicommodity transactions with implicit prices (no @, two commodi-- ties, unbalanced). (With these, the order of postings matters.- hledger print -x can be useful for troubleshooting.)-- o but not, currently, from "more correct" multicommodity transactions- (no @, multiple commodities, balanced).-- Valuation commodity- (experimental)-- When you specify a valuation commodity (-X COMM or --value TYPE,COMM):- hledger will convert all amounts to COMM, wherever it can find a suit-- able market price (including by reversing or chaining prices).-- When you leave the valuation commodity unspecified (-V or --value- TYPE):- For each commodity A, hledger picks a default valuation commodity as- follows, in this order of preference:-- 1. The price commodity from the latest P-declared market price for A on- or before valuation date.-- 2. 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.)-- 3. If there are no P directives at all (any commodity or date) and the- --infer-value flag is used: the price commodity from the latest- transaction-inferred price for A on or before valuation date.-- This means:-- o If you have P directives, they determine which commodities -V will- convert, and to what.-- o If you have no P directives, and use the --infer-value flag, transac-- tion prices determine it.-- Amounts for which no valuation commodity can be found are not con-- verted.-- Simple valuation examples- Here are some quick examples of -V:-- ; one euro is worth this many dollars from nov 1- P 2016/11/01 EUR $1.10-- ; purchase some euros on nov 3- 2016/11/3- assets:euros EUR100- assets:checking-- ; the euro is worth fewer dollars by dec 21- P 2016/12/21 EUR $1.03-- How many euros do I have ?-- $ hledger -f t.j bal -N euros- EUR100 assets:euros-- What are they worth at end of nov 3 ?-- $ hledger -f t.j bal -N euros -V -e 2016/11/4- $110.00 assets:euros-- What are they worth after 2016/12/21 ? (no report end date specified,- defaults to today)-- $ hledger -f t.j bal -N euros -V- $103.00 assets:euros-- --value: Flexible valuation- -B, -V and -X are special cases of the more general --value option:-- --value=TYPE[,COMM] TYPE is cost, then, end, now or YYYY-MM-DD.- COMM is an optional commodity symbol.- Shows amounts converted to:- - cost commodity using transaction prices (then optionally to COMM using market prices at period end(s))- - 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-- The TYPE part selects cost or value and valuation date:-- --value=cost- Convert amounts to cost, using the prices recorded in transac-- tions.-- --value=then- Convert amounts to their value in the default valuation commod-- ity, using market prices on each posting's date. This is cur-- rently supported only by the print and register commands.-- --value=end- Convert amounts to their value in the default valuation commod-- ity, using market prices on the last day of the report period- (or if unspecified, the journal's end date); or in multiperiod- reports, market prices on the last day of each subperiod.-- --value=now- Convert amounts to their value in the default valuation commod-- ity using current market prices (as of when report is gener-- ated).-- --value=YYYY-MM-DD- Convert amounts to their value in the default valuation commod-- ity using market prices on this date.-- To select a different valuation commodity, add the optional ,COMM part:- a comma, then the target commodity's symbol. Eg: --value=now,EUR.- hledger will do its best to convert amounts to this commodity, deducing- market prices as described above.-- More valuation examples- Here are some examples showing the effect of --value, as seen with- print:-- 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 @ 5 B-- 2000-02-01- (a) 1 A @ 6 B-- 2000-03-01- (a) 1 A @ 7 B-- Show the cost of each posting:-- $ hledger -f- print --value=cost- 2000-01-01- (a) 5 B-- 2000-02-01- (a) 6 B-- 2000-03-01- (a) 7 B-- Show the value as of the last day of the report period (2000-02-29):-- $ hledger -f- print --value=end date:2000/01-2000/03- 2000-01-01- (a) 2 B-- 2000-02-01- (a) 2 B-- With no report period specified, that shows the value as of the last- day of the journal (2000-03-01):-- $ hledger -f- print --value=end- 2000-01-01- (a) 3 B-- 2000-02-01- (a) 3 B-- 2000-03-01- (a) 3 B-- Show the current value (the 2000-04-01 price is still in effect today):-- $ hledger -f- print --value=now- 2000-01-01- (a) 4 B-- 2000-02-01- (a) 4 B-- 2000-03-01- (a) 4 B-- Show the value on 2000/01/15:-- $ 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-- You may need to explicitly set a commodity's display style, when re-- verse prices are used. Eg this output might be surprising:-- P 2000-01-01 A 2B-- 2000-01-01- a 1B- b-- $ hledger print -x -X A- 2000-01-01- a 0- b 0-- Explanation: because there's no amount or commodity directive specify-- ing a display style for A, 0.5A gets the default style, which shows no- decimal digits. Because the displayed amount looks like zero, the com-- modity symbol and minus sign are not displayed either. Adding a com-- modity directive sets a more useful display style for A:-- P 2000-01-01 A 2B- commodity 0.00A-- 2000-01-01- a 1B- b-- $ hledger print -X A- 2000-01-01- a 0.50A- b -0.50A-- Effect of valuation on reports- Here is a reference for how valuation is supposed to affect each part- of hledger's reports (and a glossary). (It's wide, you'll have to- scroll sideways.) It may be useful when troubleshooting. If you find- problems, please report them, ideally with a reproducible example. Re-- lated: #329, #1083.-- Report type -B, -V, -X --value=then --value=end --value=DATE,- --value=cost --value=now- ------------------------------------------------------------------------------------------- print- posting cost value at re- value at value at re- value at- amounts port end or posting date port or DATE/today- today journal end- balance as- unchanged unchanged unchanged unchanged unchanged- sertions /- assignments-- register- starting cost value at day not supported value at day value at- balance before re- before re- DATE/today- (with -H) port or port or- journal journal- start start- posting cost value at re- value at value at re- value at- amounts (no port end or posting date port or DATE/today- report in- today journal end- terval)- summary summarised value at pe- sum of post- value at pe- value at- posting cost riod ends ings in in- riod ends DATE/today- amounts terval, val-- (with report ued at inter-- interval) val start- running to- sum/average sum/average sum/average sum/average sum/average- tal/average of displayed of displayed of displayed of displayed of displayed- values values values values values--- balance (bs,- bse, cf,- is..)- balances (no sums of value at re- not supported value at re- value at- report in- costs port end or port or DATE/today of- terval) today of journal end sums of post-- sums of of sums of ings- postings postings- balances sums of value at pe- not supported value at pe- value at- (with report costs riod ends of riod ends of DATE/today of- interval) sums of sums of sums of post-- postings postings ings- starting sums of sums of not supported sums of sums of post-- balances costs of postings be- postings be- ings before- (with report postings be- fore report fore report report start- interval and fore report start start- -H) start- budget like bal- like bal- not supported like bal- like balances- amounts with ances ances ances- --budget- grand total sum of dis- sum of dis- not supported sum of dis- sum of dis-- (no report played val- played val- played val- played values- interval) ues ues ues- row to- sums/aver- sums/aver- not supported sums/aver- sums/averages- tals/aver- ages of dis- ages of dis- ages of dis- of displayed- ages (with played val- played val- played val- values- report in- ues ues ues- terval)- column to- sums of dis- sums of dis- not supported sums of dis- sums of dis-- tals played val- played val- played val- played values- ues ues ues- grand to- sum/average sum/average not supported sum/average sum/average- tal/average of column of column of column of column to-- totals totals totals tals--- Glossary:-- cost calculated using price(s) recorded in the transaction(s).-- value market value using available market price declarations, or the- unchanged amount if no conversion rate can be found.-- report start- the first day of the report period specified with -b or -p or- date:, otherwise today.-- report or journal start- the first day of the report period specified with -b or -p or- date:, otherwise the earliest transaction date in the journal,- otherwise today.-- report end- the last day of the report period specified with -e or -p or- date:, otherwise today.-- report or journal end- the last day of the report period specified with -e or -p or- date:, otherwise the latest transaction date in the journal,- otherwise today.-- report interval- a flag (-D/-W/-M/-Q/-Y) or period expression that activates the- report's multi-period mode (whether showing one or many subperi-- ods).--COMMANDS- hledger provides a number of subcommands; hledger with no arguments- shows a list.-- If you install additional hledger-* packages, or if you put programs or- scripts named hledger-NAME in your PATH, these will also be listed as- subcommands.-- Run a subcommand by writing its name as first argument (eg hledger in-- comestatement). You can also write one of the standard short aliases- displayed in parentheses in the command list (hledger b), or any any- unambiguous prefix of a command name (hledger inc).-- Here are all the builtin commands in alphabetical order. See also- hledger for a more organised command list, and hledger CMD -h for de-- tailed command help.-- accounts- accounts, a- Show account names.-- This command lists account names, either declared with account direc-- tives (--declared), posted to (--used), or both (the default). With- query arguments, only matched account names and account names refer-- enced by matched postings are shown. It shows a flat list by default.- With --tree, it uses indentation to show the account hierarchy. In- flat mode you can add --drop N to omit the first few account name com-- ponents. Account names can be depth-clipped with depth:N or --depth N- or -N.-- Examples:-- $ hledger accounts- assets:bank:checking- assets:bank:saving- assets:cash- expenses:food- expenses:supplies- income:gifts- income:salary- liabilities:debts-- activity- activity- Show an ascii barchart of posting counts per interval.-- The activity command displays an ascii histogram showing transaction- counts by day, week, month or other reporting interval (by day is the- default). With query arguments, it counts only matched transactions.-- Examples:-- $ hledger activity --quarterly- 2008-01-01 **- 2008-04-01 *******- 2008-07-01- 2008-10-01 **-- add- add- Prompt for transactions and add them to the journal. Any arguments- will be used as default inputs for the first N prompts.-- Many hledger users edit their journals directly with a text editor, or- generate them from CSV. For more interactive data entry, there is the- add command, which prompts interactively on the console for new trans-- actions, and appends them to the journal file (if there are multiple -f- FILE options, the first file is used.) Existing transactions are not- changed. This is the only hledger command that writes to the journal- file.-- To use it, just run hledger add and follow the prompts. You can add as- many transactions as you like; when you are finished, enter . or press- control-d or control-c to exit.-- Features:-- o add tries to provide useful defaults, using the most similar (by de-- scription) recent transaction (filtered by the query, if any) as a- template.-- o You can also set the initial defaults with command line arguments.-- o Readline-style edit keys can be used during data entry.-- o The tab key will auto-complete whenever possible - accounts, descrip-- tions, dates (yesterday, today, tomorrow). If the input area is- empty, it will insert the default value.-- o If the journal defines a default commodity, it will be added to any- bare numbers entered.-- o A parenthesised transaction code may be entered following a date.-- o Comments and tags may be entered following a description or amount.-- o If you make a mistake, enter < at any prompt to go one step backward.-- o Input prompts are displayed in a different colour when the terminal- supports it.-- Example (see the tutorial for a detailed explanation):-- $ hledger add- Adding transactions to journal file /src/hledger/examples/sample.journal- Any command line arguments will be used as defaults.- Use tab key to complete, readline keys to edit, enter to accept defaults.- An optional (CODE) may follow transaction dates.- An optional ; COMMENT may follow descriptions or amounts.- If you make a mistake, enter < at any prompt to go one step backward.- To end a transaction, enter . when prompted.- To quit, enter . at a date prompt or press control-d or control-c.- Date [2015/05/22]:- Description: supermarket- Account 1: expenses:food- Amount 1: $10- Account 2: assets:checking- Amount 2 [$-10.0]:- Account 3 (or . or enter to finish this transaction): .- 2015/05/22 supermarket- expenses:food $10- assets:checking $-10.0-- Save this transaction to the journal ? [y]:- Saved.- Starting the next transaction (. or ctrl-D/ctrl-C to quit)- Date [2015/05/22]: <CTRL-D> $-- On Microsoft Windows, the add command makes sure that no part of the- file path ends with a period, as that would cause problems (#1056).-- aregister- aregister, areg- Show transactions affecting a particular account, and the account's- running balance.-- aregister shows the transactions affecting a particular account (and- its subaccounts), from the point of view of that account. Each line- shows:-- o the transaction's (or posting's, see below) date-- o the names of the other account(s) involved-- o the net change to this account's balance-- o the account's historical running balance (including balance from- transactions before the report start date).-- With aregister, each line represents a whole transaction - as in- hledger-ui, hledger-web, and your bank statement. By contrast, the- register command shows individual postings, across all accounts. You- might prefer aregister for reconciling with real-world asset/liability- accounts, and register for reviewing detailed revenues/expenses.-- An account must be specified as the first argument, which should be the- full account name or an account pattern (regular expression). aregis-- ter will show transactions in this account (the first one matched) and- any of its subaccounts.-- Any additional arguments form a query which will filter the transac-- tions shown.-- Transactions making a net change of zero are not shown by default; add- the -E/--empty flag to show them.-- aregister and custom posting dates- Transactions whose date is outside the report period can still be- shown, if they have a posting to this account dated inside the report- period. (And in this case it's the posting date that is shown.) This- ensures that aregister can show an accurate historical running balance,- matching the one shown by register -H with the same arguments.-- To filter strictly by transaction date instead, add the --txn-dates- flag. If you use this flag and some of your postings have custom- dates, it's probably best to assume the running balance is wrong.-- Output format- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, and json.-- Examples:-- Show all transactions and historical running balance in the first ac-- count whose name contains "checking":-- $ hledger areg checking-- Show transactions and historical running balance in all asset accounts- during july:-- $ hledger areg assets date:jul-- balance- balance, bal, b- Show accounts and their balances.-- The balance command is hledger's most versatile command. Note, despite- the name, it is not always used for showing real-world account bal-- ances; the more accounting-aware balancesheet and incomestatement may- be more convenient for that.-- By default, it displays all accounts, and each account's change in bal-- ance during the entire period of the journal. Balance changes are cal-- culated by adding up the postings in each account. You can limit the- postings matched, by a query, to see fewer accounts, changes over a- different time period, changes from only cleared transactions, etc.-- If you include an account's complete history of postings in the report,- the balance change is equivalent to the account's current ending bal-- ance. For a real-world account, typically you won't have all transac-- tions in the journal; instead you'll have all transactions after a cer-- tain date, and an "opening balances" transaction setting the correct- starting balance on that date. Then the balance command will show- real-world account balances. In some cases the -H/--historical flag is- used to ensure this (more below).-- The balance command can produce several styles of report:-- Classic balance report- This is the original balance report, as found in Ledger. It usually- looks like this:-- $ hledger balance- $-1 assets- $1 bank:saving- $-2 cash- $2 expenses- $1 food- $1 supplies- $-2 income- $-1 gifts- $-1 salary- $1 liabilities:debts- --------------------- 0-- By default, accounts are displayed hierarchically, with subaccounts in-- dented below their parent. At each level of the tree, accounts are- sorted by account code if any, then by account name. Or with- -S/--sort-amount, by their balance amount, largest first.-- "Boring" accounts, which contain a single interesting subaccount and no- balance of their own, are elided into the following line for more com-- pact output. (Eg above, the "liabilities" account.) Use --no-elide to- prevent this.-- Account balances are "inclusive" - they include the balances of any- subaccounts.-- Accounts which have zero balance (and no non-zero subaccounts) are- omitted. Use -E/--empty to show them.-- A final total is displayed by default; use -N/--no-total to suppress- it, eg:-- $ hledger balance -p 2008/6 expenses --no-total- $2 expenses- $1 food- $1 supplies-- Customising the classic balance report- You can customise the layout of classic balance reports with --format- FMT:-- $ hledger balance --format "%20(account) %12(total)"- assets $-1- bank:saving $1- cash $-2- expenses $2- food $1- supplies $1- income $-2- gifts $-1- salary $-1- liabilities:debts $1- ---------------------------------- 0-- The FMT format string (plus a newline) specifies the formatting applied- to each account/balance pair. It may contain any suitable text, with- data fields interpolated like so:-- %[MIN][.MAX](FIELDNAME)-- o MIN pads with spaces to at least this width (optional)-- o MAX truncates at this width (optional)-- o FIELDNAME must be enclosed in parentheses, and can be one of:-- o depth_spacer - a number of spaces equal to the account's depth, or- if MIN is specified, MIN * depth spaces.-- o account - the account's name-- o total - the account's balance/posted total, right justified-- Also, FMT can begin with an optional prefix to control how multi-com-- modity amounts are rendered:-- o %_ - render on multiple lines, bottom-aligned (the default)-- o %^ - render on multiple lines, top-aligned-- o %, - render on one line, comma-separated-- There are some quirks. Eg in one-line mode, %(depth_spacer) has no ef-- fect, instead %(account) has indentation built in. Experimentation may- be needed to get pleasing results.-- Some example formats:-- o %(total) - the account's total-- o %-20.20(account) - the account's name, left justified, padded to 20- characters and clipped at 20 characters-- o %,%-50(account) %25(total) - account name padded to 50 characters,- total padded to 20 characters, with multiple commodities rendered on- one line-- o %20(total) %2(depth_spacer)%-(account) - the default format for the- single-column balance report-- Colour support- In terminal output, when colour is enabled, the balance command shows- negative amounts in red.-- Flat mode- To see a flat list instead of the default hierarchical display, use- --flat. In this mode, accounts (unless depth-clipped) show their full- names and "exclusive" balance, excluding any subaccount balances. In- this mode, you can also use --drop N to omit the first few account name- components.-- $ hledger balance -p 2008/6 expenses -N --flat --drop 1- $1 food- $1 supplies-- Depth limited balance reports- With --depth N or depth:N or just -N, balance reports show accounts- only to the specified numeric depth. This is very useful to summarise- a complex set of accounts and get an overview.-- $ hledger balance -N -1- $-1 assets- $2 expenses- $-2 income- $1 liabilities-- Flat-mode balance reports, which normally show exclusive balances, show- inclusive balances at the depth limit.-- Percentages- With -% or --percent, balance reports show each account's value ex-- pressed as a percentage of the column's total. This is useful to get- an overview of the relative sizes of account balances. For example to- obtain an overview of expenses:-- $ hledger balance expenses -%- 100.0 % expenses- 50.0 % food- 50.0 % supplies- --------------------- 100.0 %-- Note that --tree does not have an effect on -%. The percentages are- always relative to the total sum of each column, they are never rela-- tive to the parent account.-- Since the percentages are relative to the columns sum, it is usually- not useful to calculate percentages if the signs of the amounts are- mixed. Although the results are technically correct, they are most- likely useless. Especially in a balance report that sums up to zero- (eg hledger balance -B) all percentage values will be zero.-- This flag does not work if the report contains any mixed commodity ac-- counts. If there are mixed commodity accounts in the report be sure to- use -V or -B to coerce the report into using a single commodity.-- Multicolumn balance report- Multicolumn or tabular balance reports are a very useful hledger fea-- ture, and usually the preferred style. They share many of the above- features, but they show the report as a table, with columns represent-- ing time periods. This mode is activated by providing a reporting in-- terval.-- There are three types of multicolumn balance report, showing different- information:-- 1. By default: each column shows the sum of postings in that period, ie- the account's change of balance in that period. This is useful eg- for a monthly income statement:-- $ hledger balance --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-- 2. With --cumulative: each column shows the ending balance for that pe-- riod, accumulating the changes across periods, starting from 0 at- the report start date:-- $ hledger balance --quarterly income expenses -E --cumulative- Ending balances (cumulative) in 2008:-- || 2008/03/31 2008/06/30 2008/09/30 2008/12/31- ===================++=================================================- expenses:food || 0 $1 $1 $1- expenses:supplies || 0 $1 $1 $1- income:gifts || 0 $-1 $-1 $-1- income:salary || $-1 $-1 $-1 $-1- -------------------++-------------------------------------------------- || $-1 0 0 0-- 3. With --historical/-H: each column shows the actual historical ending- balance for that period, accumulating the changes across periods,- starting from the actual balance at the report start date. This is- useful eg for a multi-period balance sheet, and when you are showing- only the data after a certain start date:-- $ hledger balance ^assets ^liabilities --quarterly --historical --begin 2008/4/1- Ending balances (historical) in 2008/04/01-2008/12/31:-- || 2008/06/30 2008/09/30 2008/12/31- ======================++=====================================- assets:bank:checking || $1 $1 0- assets:bank:saving || $1 $1 $1- assets:cash || $-2 $-2 $-2- liabilities:debts || 0 0 $1- ----------------------++-------------------------------------- || 0 0 0-- Note that --cumulative or --historical/-H disable --row-total/-T, since- summing end balances generally does not make sense.-- Multicolumn balance reports display accounts in flat mode by default;- to see the hierarchy, use --tree.-- With a reporting interval (like --quarterly above), the report- start/end dates will be adjusted if necessary so that they encompass- the displayed report periods. This is so that the first and last peri-- ods will be "full" and comparable to the others.-- The -E/--empty flag does two things in multicolumn balance reports:- first, the report will show all columns within the specified report pe-- riod (without -E, leading and trailing columns with all zeroes are not- shown). Second, all accounts which existed at the report start date- will be considered, not just the ones with activity during the report- period (use -E to include low-activity accounts which would otherwise- would be omitted).-- The -T/--row-total flag adds an additional column showing the total for- each row.-- The -A/--average flag adds a column showing the average value in each- row.-- Here's an example of all three:-- $ hledger balance -Q income expenses --tree -ETA- Balance changes in 2008:-- || 2008q1 2008q2 2008q3 2008q4 Total Average- ============++===================================================- expenses || 0 $2 0 0 $2 $1- food || 0 $1 0 0 $1 0- supplies || 0 $1 0 0 $1 0- income || $-1 $-1 0 0 $-2 $-1- gifts || 0 $-1 0 0 $-1 0- salary || $-1 0 0 0 $-1 0- ------------++---------------------------------------------------- || $-1 $1 0 0 0 0-- (Average is rounded to the dollar here since all journal amounts are)-- The --transpose flag can be used to exchange the rows and columns of a- multicolumn report.-- When showing multicommodity amounts, multicolumn balance reports will- elide any amounts which have more than two commodities, since otherwise- columns could get very wide. The --no-elide flag disables this. Hid-- ing totals with the -N/--no-total flag can also help reduce the width- of multicommodity reports.-- When the report is still too wide, a good workaround is to pipe it into- less -RS (-R for colour, -S to chop long lines). Eg: hledger bal -D- --color=yes | less -RS.-- Budget report- With --budget, extra columns are displayed showing budget goals for- each account and period, if any. Budget goals are defined by periodic- transactions. This is very useful for comparing planned and actual in-- come, expenses, time usage, etc. --budget is most often combined with- a report interval.-- For example, you can take average monthly expenses in the common ex-- pense categories to construct a minimal monthly budget:-- ;; Budget- ~ monthly- income $2000- expenses:food $400- expenses:bus $50- expenses:movies $30- assets:bank:checking-- ;; Two months worth of expenses- 2017-11-01- income $1950- expenses:food $396- expenses:bus $49- expenses:movies $30- expenses:supplies $20- assets:bank:checking-- 2017-12-01- income $2100- expenses:food $412- expenses:bus $53- expenses:gifts $100- assets:bank:checking-- You can now see a monthly budget report:-- $ hledger balance -M --budget- Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec- ======================++====================================================- assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- expenses || $495 [ 103% of $480] $565 [ 118% of $480]- expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50]- expenses:food || $396 [ 99% of $400] $412 [ 103% of $400]- expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30]- income || $1950 [ 98% of $2000] $2100 [ 105% of $2000]- ----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0]-- This is different from a normal balance report in several ways:-- o Only accounts with budget goals during the report period are shown,- by default.-- o In each column, in square brackets after the actual amount, budget- goal amounts are shown, and the actual/goal percentage. (Note: bud-- get goals should be in the same commodity as the actual amount.)-- o All parent accounts are always shown, even in flat mode. Eg assets,- assets:bank, and expenses above.-- o Amounts always include all subaccounts, budgeted or unbudgeted, even- in flat mode.-- This means that the numbers displayed will not always add up! Eg above,- the expenses actual amount includes the gifts and supplies transac-- tions, but the expenses:gifts and expenses:supplies accounts are not- shown, as they have no budget amounts declared.-- This can be confusing. When you need to make things clearer, use the- -E/--empty flag, which will reveal all accounts including unbudgeted- ones, giving the full picture. Eg:-- $ hledger balance -M --budget --empty- Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec- ======================++====================================================- assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]- expenses || $495 [ 103% of $480] $565 [ 118% of $480]- expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50]- expenses:food || $396 [ 99% of $400] $412 [ 103% of $400]- expenses:gifts || 0 $100- expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30]- expenses:supplies || $20 0- income || $1950 [ 98% of $2000] $2100 [ 105% of $2000]- ----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0]-- You can roll over unspent budgets to next period with --cumulative:-- $ hledger balance -M --budget --cumulative- Budget performance in 2017/11/01-2017/12/31:-- || Nov Dec- ======================++====================================================- assets || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]- assets:bank || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]- assets:bank:checking || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]- expenses || $495 [ 103% of $480] $1060 [ 110% of $960]- expenses:bus || $49 [ 98% of $50] $102 [ 102% of $100]- expenses:food || $396 [ 99% of $400] $808 [ 101% of $800]- expenses:movies || $30 [ 100% of $30] $30 [ 50% of $60]- income || $1950 [ 98% of $2000] $4050 [ 101% of $4000]- ----------------------++----------------------------------------------------- || 0 [ 0] 0 [ 0]-- For more examples, see Budgeting and Forecasting.-- Nested budgets- You can add budgets to any account in your account hierarchy. If you- have budgets on both parent account and some of its children, then bud-- get(s) of the child account(s) would be added to the budget of their- parent, much like account balances behave.-- In the most simple case this means that once you add a budget to any- account, all its parents would have budget as well.-- To illustrate this, consider the following budget:-- ~ monthly from 2019/01- expenses:personal $1,000.00- expenses:personal:electronics $100.00- liabilities-- With this, monthly budget for electronics is defined to be $100 and- budget for personal expenses is an additional $1000, which implicitly- means that budget for both expenses:personal and expenses is $1100.-- Transactions in expenses:personal:electronics will be counted both to-- wards its $100 budget and $1100 of expenses:personal , and transactions- in any other subaccount of expenses:personal would be counted towards- only towards the budget of expenses:personal.-- For example, let's consider these transactions:-- ~ monthly from 2019/01- expenses:personal $1,000.00- expenses:personal:electronics $100.00- liabilities-- 2019/01/01 Google home hub- expenses:personal:electronics $90.00- liabilities $-90.00-- 2019/01/02 Phone screen protector- expenses:personal:electronics:upgrades $10.00- liabilities-- 2019/01/02 Weekly train ticket- expenses:personal:train tickets $153.00- liabilities-- 2019/01/03 Flowers- expenses:personal $30.00- liabilities-- As you can see, we have transactions in expenses:personal:electron-- ics:upgrades and expenses:personal:train tickets, and since both of- these accounts are without explicitly defined budget, these transac-- tions would be counted towards budgets of expenses:personal:electronics- and expenses:personal accordingly:-- $ hledger balance --budget -M- Budget performance in 2019/01:-- || Jan- ===============================++===============================- expenses || $283.00 [ 26% of $1100.00]- expenses:personal || $283.00 [ 26% of $1100.00]- expenses:personal:electronics || $100.00 [ 100% of $100.00]- liabilities || $-283.00 [ 26% of $-1100.00]- -------------------------------++-------------------------------- || 0 [ 0]-- And with --empty, we can get a better picture of budget allocation and- consumption:-- $ hledger balance --budget -M --empty- Budget performance in 2019/01:-- || Jan- ========================================++===============================- expenses || $283.00 [ 26% of $1100.00]- expenses:personal || $283.00 [ 26% of $1100.00]- expenses:personal:electronics || $100.00 [ 100% of $100.00]- expenses:personal:electronics:upgrades || $10.00- expenses:personal:train tickets || $153.00- liabilities || $-283.00 [ 26% of $-1100.00]- ----------------------------------------++-------------------------------- || 0 [ 0]-- Output format- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, (multicolumn non-bud-- get reports only) html, and (experimental) json.-- balancesheet- balancesheet, bs- This command displays a balance sheet, showing historical ending bal-- ances of asset and liability accounts. (To see equity as well, use the- balancesheetequity command.) Amounts are shown with normal positive- sign, as in conventional financial statements.-- The asset and liability accounts shown are those accounts declared with- the Asset or Cash or Liability type, or otherwise all accounts under a- top-level asset or liability account (case insensitive, plurals al-- lowed).-- Example:-- $ hledger balancesheet- Balance Sheet-- Assets:- $-1 assets- $1 bank:saving- $-2 cash- --------------------- $-1-- Liabilities:- $1 liabilities:debts- --------------------- $1-- Total:- --------------------- 0-- With a reporting interval, multiple columns will be shown, one for each- report period. As with multicolumn balance reports, you can alter the- report mode with --change/--cumulative/--historical. Normally bal-- ancesheet shows historical ending balances, which is what you need for- a balance sheet; note this means it ignores report begin dates (and- -T/--row-total, since summing end balances generally does not make- sense). Instead of absolute values percentages can be displayed with- -%.-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, html, and (experimen-- tal) json.-- balancesheetequity- balancesheetequity, bse- This command displays a balance sheet, showing historical ending bal-- ances of asset, liability and equity accounts. Amounts are shown with- normal positive sign, as in conventional financial statements.-- The asset, liability and equity accounts shown are those accounts de-- clared with the Asset, Cash, Liability or Equity type, or otherwise all- accounts under a top-level asset, liability or equity account (case in-- sensitive, plurals allowed).-- Example:-- $ hledger balancesheetequity- Balance Sheet With Equity-- Assets:- $-2 assets- $1 bank:saving- $-3 cash- --------------------- $-2-- Liabilities:- $1 liabilities:debts- --------------------- $1-- Equity:- $1 equity:owner- --------------------- $1-- Total:- --------------------- 0-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, html, and (experimen-- tal) json.-- cashflow- cashflow, cf- This command displays a cashflow statement, showing the inflows and- outflows affecting "cash" (ie, liquid) assets. Amounts are shown with- normal positive sign, as in conventional financial statements.-- The "cash" accounts shown are those accounts declared with the Cash- type, or otherwise all accounts under a top-level asset account (case- insensitive, plural allowed) which do not have fixed, investment, re-- ceivable or A/R in their name.-- Example:-- $ hledger cashflow- Cashflow Statement-- Cash flows:- $-1 assets- $1 bank:saving- $-2 cash- --------------------- $-1-- Total:- --------------------- $-1-- With a reporting interval, multiple columns will be shown, one for each- report period. Normally cashflow shows changes in assets per period,- though as with multicolumn balance reports you can alter the report- mode with --change/--cumulative/--historical. Instead of absolute val-- ues percentages can be displayed with -%.-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, html, and (experimen-- tal) json.-- check-dates- check-dates- Check that transactions are sorted by increasing date. With --date2,- checks secondary dates instead. With --strict, dates must also be- unique. With a query, only matched transactions' dates are checked.- Reads the default journal file, or another specified with -f.-- check-dupes- check-dupes- Reports account names having the same leaf but different prefixes. In- other words, two or more leaves that are categorized differently.- Reads the default journal file, or another specified as an argument.-- An example: http://stefanorodighiero.net/software/hledger-dupes.html-- close- close, equity- Prints a "closing balances" transaction and an "opening balances"- transaction that bring account balances to and from zero, respectively.- These can be added to your journal file(s), eg to bring asset/liability- balances forward into a new journal file, or to close out revenues/ex-- penses to retained earnings at the end of a period.-- You can print just one of these transactions by using the --close or- --open flag. You can customise their descriptions with the --close-- desc and --open-desc options.-- One amountless posting to "equity:opening/closing balances" is added to- balance the transactions, by default. You can customise this account- name with --close-acct and --open-acct; if you specify only one of- these, it will be used for both.-- With --x/--explicit, the equity posting's amount will be shown. And if- it involves multiple commodities, a posting for each commodity will be- shown, as with the print command.-- With --interleaved, the equity postings are shown next to the postings- they balance, which makes troubleshooting easier.-- By default, transaction prices in the journal are ignored when generat-- ing the closing/opening transactions. With --show-costs, this cost in-- formation is preserved (balance -B reports will be unchanged after the- transition). Separate postings are generated for each cost in each- commodity. Note this can generate very large journal entries, if you- have many foreign currency or investment transactions.-- close usage- If you split your journal files by time (eg yearly), you will typically- run this command at the end of the year, and save the closing transac-- tion as last entry of the old file, and the opening transaction as the- first entry of the new file. This makes the files self contained, so- that correct balances are reported no matter which of them are loaded.- Ie, if you load just one file, the balances are initialised correctly;- or if you load several files, the redundant closing/opening transac-- tions cancel each other out. (They will show up in print or register- reports; you can exclude them with a query like not:desc:'(open-- ing|closing) balances'.)-- If you're running a business, you might also use this command to "close- the books" at the end of an accounting period, transferring income- statement account balances to retained earnings. (You may want to- change the equity account name to something like "equity:retained earn-- ings".)-- By default, the closing transaction is dated yesterday, the balances- are calculated as of end of yesterday, and the opening transaction is- dated today. To close on some other date, use: hledger close -e OPEN-- INGDATE. Eg, to close/open on the 2018/2019 boundary, use -e 2019.- You can also use -p or date:PERIOD (any starting date is ignored).-- Both transactions will include balance assertions for the closed/re-- opened accounts. You probably shouldn't use status or realness filters- (like -C or -R or status:) with this command, or the generated balance- assertions will depend on these flags. Likewise, if you run this com-- mand with --auto, the balance assertions will probably always require- --auto.-- Examples:-- Carrying asset/liability balances into a new file for 2019:-- $ hledger close -f 2018.journal -e 2019 assets liabilities --open- # (copy/paste the output to the start of your 2019 journal file)- $ hledger close -f 2018.journal -e 2019 assets liabilities --close- # (copy/paste the output to the end of your 2018 journal file)-- Now:-- $ hledger bs -f 2019.journal # one file - balances are correct- $ hledger bs -f 2018.journal -f 2019.journal # two files - balances still correct- $ hledger bs -f 2018.journal not:desc:closing # to see year-end balances, must exclude closing txn-- Transactions spanning the closing date can complicate matters, breaking- balance assertions:-- 2018/12/30 a purchase made in 2018, clearing the following year- expenses:food 5- assets:bank:checking -5 ; [2019/1/2]-- Here's one way to resolve that:-- ; in 2018.journal:- 2018/12/30 a purchase made in 2018, clearing the following year- expenses:food 5- liabilities:pending-- ; in 2019.journal:- 2019/1/2 clearance of last year's pending transactions- liabilities:pending 5 = 0- assets:checking-- codes- codes- List the codes seen in transactions, in the order parsed.-- This command prints the value of each transaction's 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.-- Transactions aren't required to have a code, and missing or empty codes- will not be shown by default. With the -E/--empty flag, they will be- printed as blank lines.-- You can add a query to select a subset of transactions.-- Examples:-- 1/1 (123)- (a) 1-- 1/1 ()- (a) 1-- 1/1- (a) 1-- 1/1 (126)- (a) 1-- $ hledger codes- 123- 124- 126-- $ hledger codes -E- 123- 124--- 126-- commodities- commodities- List all commodity/currency symbols used or declared in the journal.-- descriptions- descriptions- List the unique descriptions that appear in transactions.-- This command lists the unique descriptions that appear in transactions,- in alphabetic order. You can add a query to select a subset of trans-- actions.-- Example:-- $ hledger descriptions- Store Name- Gas Station | Petrol- Person A-- diff- diff- Compares a particular account's transactions in two input files. It- shows any transactions to this account which are in one file but not in- the other.-- More precisely, for each posting affecting this account in either file,- it looks for a corresponding posting in the other file which posts the- same amount to the same account (ignoring date, description, etc.)- Since postings not transactions are compared, this also works when mul-- tiple bank transactions have been combined into a single journal entry.-- This is useful eg if you have downloaded an account's 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.-- Examples:-- $ 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:-- files- files- List all files included in the journal. With a REGEX argument, only- file names matching the regular expression (case sensitive) are shown.-- help- help- Show any of the hledger manuals.-- The help command displays any of the main hledger manuals, in one of- several ways. Run it with no argument to list the manuals, or provide- a full or partial manual name to select one.-- hledger manuals are available in several formats. hledger help will- use the first of these display methods that it finds: info, man,- $PAGER, less, stdout (or when non-interactive, just stdout). You can- force a particular viewer with the --info, --man, --pager, --cat flags.-- Examples:-- $ hledger help- Please choose a manual by typing "hledger help MANUAL" (a substring is ok).- Manuals: hledger hledger-ui hledger-web journal csv timeclock timedot-- $ hledger help h --man-- hledger(1) hledger User Manuals hledger(1)-- NAME- hledger - a command-line accounting tool-- SYNOPSIS- hledger [-f FILE] COMMAND [OPTIONS] [ARGS]- hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]- hledger-- DESCRIPTION- hledger is a cross-platform program for tracking money, time, or any- ...-- import- import- Read new transactions added to each FILE since last run, and add them- to the main journal file. Or with --dry-run, just print the transac-- tions that would be added. Or with --catchup, just mark all of the- FILEs' transactions as imported, without actually importing any.-- The input files are specified as arguments - no need to write -f before- each one. So eg to add new transactions from all CSV files to the main- journal, it's just: hledger import *.csv-- New transactions are detected in the same way as print --new: by assum-- ing transactions are always added to the input files in increasing date- order, and by saving .latest.FILE state files.-- The --dry-run output is in journal format, so you can filter it, eg to- see only uncategorised transactions:-- $ hledger import --dry ... | hledger -f- print unknown --ignore-assertions-- Importing balance assignments- Entries added by import will have their posting amounts made explicit- (like hledger print -x). This means that any balance assignments in- imported files must be evaluated; but, imported files don't get to see- the main file's account balances. As a result, importing entries with- balance assignments (eg from an institution that provides only balances- and not posting amounts) will probably generate incorrect posting- amounts. To avoid this problem, use print instead of import:-- $ hledger print IMPORTFILE [--new] >> $LEDGER_FILE-- (If you think import should leave amounts implicit like print does,- please test it and send a pull request.)-- incomestatement- incomestatement, is- This command displays an income statement, showing revenues and ex-- penses during one or more periods. Amounts are shown with normal posi-- tive sign, as in conventional financial statements.-- The revenue and expense accounts shown are those accounts declared with- the Revenue or Expense type, or otherwise all accounts under a top-- level revenue or income or expense account (case insensitive, plurals- allowed).-- Example:-- $ hledger incomestatement- Income Statement-- Revenues:- $-2 income- $-1 gifts- $-1 salary- --------------------- $-2-- Expenses:- $2 expenses- $1 food- $1 supplies- --------------------- $2-- Total:- --------------------- 0-- With a reporting interval, multiple columns will be shown, one for each- report period. Normally incomestatement shows revenues/expenses per- period, though as with multicolumn balance reports you can alter the- report mode with --change/--cumulative/--historical. Instead of abso-- lute values percentages can be displayed with -%.-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, html, and (experimen-- tal) json.-- notes- notes- List the unique notes that appear in transactions.-- This command lists the unique notes that appear in transactions, in al-- phabetic order. You can add a query to select a subset of transac-- tions. The note is the part of the transaction description after a |- character (or if there is no |, the whole description).-- Example:-- $ hledger notes- Petrol- Snacks-- payees- payees- List the unique payee/payer names that appear in transactions.-- This command lists the unique payee/payer names that appear in transac-- tions, in alphabetic order. You can add a query to select a subset of- transactions. The payee/payer is the part of the transaction descrip-- tion before a | character (or if there is no |, the whole description).-- Example:-- $ hledger payees- Store Name- Gas Station- Person A-- prices- prices- Print market price directives from the journal. With --costs, also- print synthetic market prices based on transaction prices. With --in-- verted-costs, also print inverse prices based on transaction prices.- Prices (and postings providing prices) can be filtered by a query.- Price amounts are always displayed with their full precision.-- print- print, txns, p- Show transaction journal entries, sorted by date.-- The print command displays full journal entries (transactions) from the- journal file in date order, tidily formatted. With --date2, transac-- tions are sorted by secondary date instead.-- print's output is always a valid hledger journal.- It preserves all transaction information, but it does not preserve di-- rectives or inter-transaction comments-- $ hledger print- 2008/01/01 income- assets:bank:checking $1- income:salary $-1-- 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-- 2008/12/31 * pay off- liabilities:debts $1- assets:bank:checking $-1-- Normally, the journal entry's explicit or implicit amount style is pre-- served. For example, when an amount is omitted in the journal, it will- not appear in the output. Similarly, when a transaction price is im-- plied but not written, it will not appear in the output. You can use- the -x/--explicit flag to make all amounts and transaction prices ex-- plicit, which can be useful for troubleshooting or for making your- journal more readable and robust against data entry errors. -x is also- implied by using any of -B,-V,-X,--value.-- Note, -x/--explicit will cause postings with a multi-commodity amount- (these can arise when a multi-commodity transaction has an implicit- amount) to be split into multiple single-commodity postings, keeping- the output parseable.-- With -B/--cost, amounts with transaction prices are converted to cost- using that price. This can be used for troubleshooting.-- With -m/--match and a STR argument, print will show at most one trans-- action: the one one whose description is most similar to STR, and is- most recent. STR should contain at least two characters. If there is- no similar-enough match, no transaction will be shown.-- With --new, for each FILE being read, hledger reads (and writes) a spe-- cial state file (.latest.FILE in the same directory), containing the- latest transaction date(s) that were seen last time FILE was read.- When this file is found, only transactions with newer dates (and new- transactions on the latest date) are printed. This is useful for ig-- noring already-seen entries in import data, such as downloaded CSV- files. Eg:-- $ hledger -f bank1.csv print --new- (shows transactions added since last print --new on this file)-- This assumes that transactions added to FILE always have same or in-- creasing dates, and that transactions on the same day do not get re-- ordered. See also the import command.-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, and (experimental)- json and sql.-- Here's an example of print's CSV output:-- $ hledger print -Ocsv- "txnidx","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","posting-status","posting-comment"- "1","2008/01/01","","","","income","","assets:bank:checking","1","$","","1","",""- "1","2008/01/01","","","","income","","income:salary","-1","$","1","","",""- "2","2008/06/01","","","","gift","","assets:bank:checking","1","$","","1","",""- "2","2008/06/01","","","","gift","","income:gifts","-1","$","1","","",""- "3","2008/06/02","","","","save","","assets:bank:saving","1","$","","1","",""- "3","2008/06/02","","","","save","","assets:bank:checking","-1","$","1","","",""- "4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","","1","",""- "4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","","1","",""- "4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","2","","",""- "5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","","1","",""- "5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","1","","",""-- o There is one CSV record per posting, with the parent transaction's- fields repeated.-- o The "txnidx" (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.)-- o The amount is separated into "commodity" (the symbol) and "amount"- (numeric quantity) fields.-- o The numeric amount is repeated in either the "credit" or "debit" col-- umn, for convenience. (Those names are not accurate in the account-- ing sense; it just puts negative amounts under credit and zero or- greater amounts under debit.)-- print-unique- print-unique- Print transactions which do not reuse an already-seen description.-- Example:-- $ cat unique.journal- 1/1 test- (acct:one) 1- 2/2 test- (acct:two) 2- $ LEDGER_FILE=unique.journal hledger print-unique- (-f option not supported)- 2015/01/01 test- (acct:one) 1-- register- register, reg, r- Show postings and their running total.-- The register command displays matched postings, across all accounts, in- date order, with their running total or running historical balance.- (See also the aregister command, which shows matched transactions in a- specific account.)-- register normally shows line per posting, but note that multi-commodity- amounts will occupy multiple lines (one line per commodity).-- It is typically used with a query selecting a particular account, to- see that account's activity:-- $ 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-- With --date2, it shows and sorts by secondary date instead.-- The --historical/-H 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:-- $ 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-- The --depth option limits the amount of sub-account detail displayed.-- The --average/-A 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 --empty (see below). It- is affected by --historical. It works best when showing just one ac-- count and one commodity.-- The --related/-r flag shows the other postings in the transactions of- the postings which would normally be shown.-- The --invert flag negates all amounts. For example, it can be used on- an income account where amounts are normally displayed as negative num-- bers. It's also useful to show postings on the checking account to-- gether with the related account:-- $ hledger register --related --invert assets:checking-- With a reporting interval, register shows summary postings, one per in-- terval, aggregating the postings to each account:-- $ hledger register --monthly income- 2008/01 income:salary $-1 $-1- 2008/06 income:gifts $-1 $-2-- Periods with no activity, and summary postings with a zero amount, are- not shown by default; use the --empty/-E flag to see them:-- $ 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-- Often, you'll want to see just one line per interval. The --depth op-- tion helps with this, causing subaccounts to be aggregated:-- $ hledger register --monthly assets --depth 1h- 2008/01 assets $1 $1- 2008/06 assets $-1 0- 2008/12 assets $-1 $-1-- Note when using report intervals, if you specify start/end dates these- will be adjusted outward if necessary to contain a whole number of in-- tervals. This ensures that the first and last intervals are full- length and comparable to the others in the report.-- Custom register output- register uses the full terminal width by default, except on windows.- You can override this by setting the COLUMNS environment variable (not- a bash shell variable) or by using the --width/-w option.-- The description and account columns normally share the space equally- (about half of (width - 40) each). You can adjust this by adding a de-- scription width as part of --width's argument, comma-separated: --width- W,D . Here's a diagram (won't display correctly in --help):-- <--------------------------------- width (W) ---------------------------------->- date (10) description (D) account (W-41-D) amount (12) balance (12)- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA-- and some examples:-- $ hledger reg # use terminal width (or 80 on windows)- $ hledger reg -w 100 # use width 100- $ COLUMNS=100 hledger reg # set with one-time environment variable- $ export COLUMNS=100; hledger reg # set till session end (or window resize)- $ hledger reg -w 100,40 # set overall width 100, description width 40- $ hledger reg -w $COLUMNS,40 # use terminal width, & description width 40-- This command also supports the output destination and output format op-- tions The output formats supported are txt, csv, and (experimental)- json.-- register-match- register-match- Print the one posting whose transaction description is closest to DESC,- in the style of the register command. If there are multiple equally- good matches, it shows the most recent. Query options (options, not- arguments) can be used to restrict the search space. Helps ledger-au-- tosync detect already-seen transactions when importing.-- rewrite- rewrite- Print all transactions, rewriting the postings of matched transactions.- For now the only rewrite available is adding new postings, like print- --auto.-- 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 transac-- tion's first posting amount.-- Examples:-- $ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'- $ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'- $ hledger-rewrite.hs -f rewrites.hledger-- rewrites.hledger may consist of entries like:-- = ^income 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-- Note the single quotes to protect the dollar sign from bash, and the- two spaces between account and amount.-- More:-- $ hledger rewrite -- [QUERY] --add-posting "ACCT AMTEXPR" ...- $ hledger rewrite -- ^income --add-posting '(liabilities:tax) *.33'- $ hledger rewrite -- expenses:gifts --add-posting '(budget:gifts) *-1"'- $ hledger rewrite -- ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'-- Argument for --add-posting option is a usual posting of transaction- with an exception for amount specification. More precisely, you can- use '*' (star symbol) before the amount to indicate that that this is a- factor for an amount of original matched posting. If the amount in-- cludes a commodity name, the new posting amount will be in the new com-- modity; otherwise, it will be in the matched posting amount's commod-- ity.-- Re-write rules in a file- During the run this tool will execute so called "Automated Transac-- tions" found in any journal it process. I.e instead of specifying this- operations in command line you can put them in a journal file.-- $ rewrite-rules.journal-- Make contents look like this:-- = ^income- (liabilities:tax) *.33-- = expenses:gifts- budget:gifts *-1- assets:budget *1-- Note that '=' (equality symbol) that is used instead of date in trans-- actions you usually write. It indicates the query by which you want to- match the posting to add new ones.-- $ hledger rewrite -- -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal-- This is something similar to the commands pipeline:-- $ hledger rewrite -- -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \- | hledger rewrite -- -f - expenses:gifts --add-posting 'budget:gifts *-1' \- --add-posting 'assets:budget *1' \- > rewritten-tidy-output.journal-- It is important to understand that relative order of such entries in- journal is important. You can re-use result of previously added post-- ings.-- Diff output format- To use this tool for batch modification of your journal files you may- find useful output in form of unified diff.-- $ hledger rewrite -- --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'-- Output might look like:-- --- /tmp/examples/sample.journal- +++ /tmp/examples/sample.journal- @@ -18,3 +18,4 @@- 2008/01/01 income- - assets:bank:checking $1- + assets:bank:checking $1- income:salary- + (liabilities:tax) 0- @@ -22,3 +23,4 @@- 2008/06/01 gift- - assets:bank:checking $1- + assets:bank:checking $1- income:gifts- + (liabilities:tax) 0-- If you'll pass this through patch tool you'll get transactions contain-- ing the posting that matches your query be updated. Note that multiple- files might be update according to list of input files specified via- --file options and include directives inside of these files.-- Be careful. Whole transaction being re-formatted in a style of output- from hledger print.-- See also:-- https://github.com/simonmichael/hledger/issues/99-- rewrite vs. print --auto- This command predates print --auto, and currently does much the same- thing, but with these differences:-- o with multiple files, rewrite lets rules in any file affect all other- files. print --auto uses standard directive scoping; rules affect- only child files.-- o rewrite's query limits which transactions can be rewritten; all are- printed. print --auto's query limits which transactions are printed.-- o rewrite applies rules specified on command line or in the journal.- print --auto applies rules specified in the journal.-- roi- roi- Shows the time-weighted (TWR) and money-weighted (IRR) rate of return- on your investments.-- This command assumes that you have account(s) that hold nothing but- your investments and whenever you record current appraisal/valuation of- these investments you offset unrealized profit and loss into account(s)- that, again, hold nothing but unrealized profit and loss.-- Any transactions affecting balance of investment account(s) and not- originating from unrealized profit and loss account(s) are assumed to- be your investments or withdrawals.-- At a minimum, you need to supply a query (which could be just an ac-- count name) to select your investments with --inv, and another query to- identify your profit and loss transactions with --pnl.-- It will compute and display the internalized rate of return (IRR) and- time-weighted rate of return (TWR) for your investments for the time- period requested. Both rates of return are annualized before display,- regardless of the length of reporting interval.-- stats- stats- Show some journal statistics.-- The stats command displays summary information for the whole journal,- or a matched part of it. With a reporting interval, it shows a report- for each report period.-- Example:-- $ hledger stats- Main journal file : /src/hledger/examples/sample.journal- Included journal files :- Transactions span : 2008-01-01 to 2009-01-01 (366 days)- Last transaction : 2008-12-31 (2333 days ago)- Transactions : 5 (0.0 per day)- Transactions last 30 days: 0 (0.0 per day)- Transactions last 7 days : 0 (0.0 per day)- Payees/descriptions : 5- Accounts : 8 (depth 3)- Commodities : 1 ($)- Market prices : 12 ($)-- This command also supports output destination and output format selec-- tion.-- tags- tags- List the unique tag names used in the journal. With a TAGREGEX argu-- ment, only tag names matching the regular expression (case insensitive)- are shown. With QUERY arguments, only transactions matching the query- are considered.-- With the --values flag, the tags' unique values are listed instead.-- With --parsed flag, all tags or values are shown in the order they are- parsed from the input data, including duplicates.-- With -E/--empty, any blank/empty values will also be shown, otherwise- they are omitted.-- test- test- Run built-in unit tests.-- This command runs the unit tests built in to hledger and hledger-lib,- printing the results on stdout. If any test fails, the exit code will- be non-zero.-- This is mainly used by hledger developers, but you can also use it to- sanity-check the installed hledger executable on your platform. All- tests are expected to pass - if you ever see a failure, please report- as a bug!-- This command also accepts tasty test runner options, written after a --- (double hyphen). Eg to run only the tests in Hledger.Data.Amount, with- ANSI colour codes disabled:-- $ hledger test -- -pData.Amount --color=never-- For help on these, see https://github.com/feuerbach/tasty#options (--- --help currently doesn't show them).-- Add-on commands- hledger also searches for external add-on commands, and will include- these in the commands list. These are programs or scripts in your PATH- whose name starts with hledger- and ends with a recognised file exten-- sion (currently: no extension, bat,com,exe, hs,lhs,pl,py,rb,rkt,sh).-- Add-ons can be invoked like any hledger command, but there are a few- things to be aware of. Eg if the hledger-web add-on is installed,-- o hledger -h web shows hledger's help, while hledger web -h shows- hledger-web's help.-- o Flags specific to the add-on must have a preceding -- to hide them- from hledger. So hledger web --serve --port 9000 will be rejected;- you must use hledger web -- --serve --port 9000.-- o You can always run add-ons directly if preferred: hledger-web --serve- --port 9000.-- Add-ons are a relatively easy way to add local features or experiment- with new ideas. They can be written in any language, but haskell- scripts have a big advantage: they can use the same hledger (and- haskell) library functions that built-in commands do, for command-line- options, journal parsing, reporting, etc.-- Two important add-ons are the hledger-ui and hledger-web user inter-- faces. These are maintained and released along with hledger:-- ui- hledger-ui provides an efficient terminal interface.-- web- hledger-web provides a simple web interface.-- Third party add-ons, maintained separately from hledger, include:-- iadd- hledger-iadd is a more interactive, terminal UI replacement for the add- command.-- interest- hledger-interest generates interest transactions for an account accord-- ing to various schemes.-- A few more experimental or old add-ons can be found in hledger's bin/- directory. These are typically prototypes and not guaranteed to work.--ENVIRONMENT- LEDGER_FILE The journal file path when not specified with -f. Default:- ~/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.jour-- nal).-- A typical value is ~/DIR/YYYY.journal, where DIR is a version-con-- trolled finance directory and YYYY is the current year. Or ~/DIR/cur-- rent.journal, where current.journal is a symbolic link to YYYY.journal.-- On Mac computers, you can set this and other environment variables in a- more thorough way that also affects applications started from the GUI- (say, an Emacs dock icon). Eg on MacOS Catalina I have a ~/.MacOSX/en-- vironment.plist file containing-- {- "LEDGER_FILE" : "~/finance/current.journal"- }-- To see the effect you may need to killall Dock, or reboot.-- COLUMNS The screen width used by the register command. Default: the- full terminal width.-- NO_COLOR If this variable exists with any value, hledger will not use- ANSI color codes in terminal output. This overrides the- --color/--colour option.--FILES- Reads data from one or more files in hledger journal, timeclock, time-- dot, or CSV format specified with -f, or $LEDGER_FILE, or- $HOME/.hledger.journal (on windows, perhaps- C:/Users/USER/.hledger.journal).--LIMITATIONS- The need to precede addon command options with -- when invoked from- hledger is awkward.-- When input data contains non-ascii characters, a suitable system locale- must be configured (or there will be an unhelpful error). Eg on POSIX,- set LANG to something other than C.-- In a Microsoft Windows CMD window, non-ascii characters and colours are- not supported.-- On Windows, non-ascii characters may not display correctly when running- a hledger built in CMD in MSYS/CYGWIN, or vice-versa.-- In a Cygwin/MSYS/Mintty window, the tab key is not supported in hledger- add.-- Not all of Ledger's journal file syntax is supported. See file format- differences.-- On large data files, hledger is slower and uses more memory than- Ledger.--TROUBLESHOOTING- Here are some issues you might encounter when you run hledger (and re-- member you can also seek help from the IRC channel, mail list or bug- tracker):-- Successfully installed, but "No command 'hledger' found"- stack and cabal install binaries into a special directory, which should- be added to your PATH environment variable. Eg on unix-like systems,- that is ~/.local/bin and ~/.cabal/bin respectively.-- I set a custom LEDGER_FILE, but hledger is still using the default file- LEDGER_FILE should be a real environment variable, not just a shell- variable. The command env | grep LEDGER_FILE should show it. You may- need to use export. Here's an explanation.-- Getting errors like "Illegal byte sequence" or "Invalid or incomplete- multibyte or wide character" or "commitAndReleaseBuffer: invalid argu-- ment (invalid character)"- Programs compiled with GHC (hledger, haskell build tools, etc.) need to- have a UTF-8-aware locale configured in the environment, otherwise they- will fail with these kinds of errors when they encounter non-ascii- characters.-- To fix it, set the LANG environment variable to some locale which sup-- ports UTF-8. The locale you choose must be installed on your system.-- Here's an example of setting LANG temporarily, on Ubuntu GNU/Linux:-- $ file my.journal- my.journal: UTF-8 Unicode text # the file is UTF8-encoded- $ echo $LANG- C # LANG is set to the default locale, which does not support UTF8- $ locale -a # which locales are installed ?- C- en_US.utf8 # here's a UTF8-aware one we can use- POSIX- $ LANG=en_US.utf8 hledger -f my.journal print # ensure it is used for this command-- If available, C.UTF-8 will also work. If your preferred locale isn't- listed by locale -a, you might need to install it. Eg on Ubuntu/De-- bian:-- $ apt-get install language-pack-fr- $ locale -a- C- en_US.utf8- fr_BE.utf8- fr_CA.utf8- fr_CH.utf8- fr_FR.utf8- fr_LU.utf8- POSIX- $ LANG=fr_FR.utf8 hledger -f my.journal print-- Here's how you could set it permanently, if you use a bash shell:-- $ echo "export LANG=en_US.utf8" >>~/.bash_profile- $ bash --login-- Exact spelling and capitalisation may be important. Note the differ-- ence on MacOS (UTF-8, not utf8). Some platforms (eg ubuntu) allow- variant spellings, but others (eg macos) require it to be exact:-- $ locale -a | grep -iE en_us.*utf- en_US.UTF-8- $ LANG=en_US.UTF-8 hledger -f my.journal print----REPORTING BUGS- Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel- or hledger mail list)---AUTHORS- Simon Michael <simon@joyful.com> and contributors---COPYRIGHT- Copyright (C) 2007-2019 Simon Michael.- Released under GNU GPL v3 or later.---SEE ALSO- hledger(1), hledger-ui(1), hledger-web(1), hledger-api(1),- hledger_csv(5), hledger_journal(5), hledger_timeclock(5), hledger_time-- dot(5), ledger(1)-- http://hledger.org----hledger 1.18.99 September 2020 hledger(1)+ -s --strict+ do extra error checking (check that all posted accounts are de-+ clared)++ General reporting options:++ -b --begin=DATE+ include postings/txns on or after this date++ -e --end=DATE+ include postings/txns before this date++ -D --daily+ multiperiod/multicolumn report by day++ -W --weekly+ multiperiod/multicolumn report by week++ -M --monthly+ multiperiod/multicolumn report by month++ -Q --quarterly+ multiperiod/multicolumn report by quarter++ -Y --yearly+ multiperiod/multicolumn report by year++ -p --period=PERIODEXP+ set start date, end date, and/or reporting interval all at once+ using period expressions syntax++ --date2+ match the secondary date instead (see command help for other ef-+ fects)++ -U --unmarked+ include only unmarked postings/txns (can combine with -P or -C)++ -P --pending+ include only pending postings/txns++ -C --cleared+ include only cleared postings/txns++ -R --real+ include only non-virtual postings++ -NUM --depth=NUM+ hide/aggregate accounts or postings more than NUM levels deep++ -E --empty+ show items with zero amount, normally hidden (and vice-versa in+ hledger-ui/hledger-web)++ -B --cost+ convert amounts to their cost/selling amount at transaction time++ -V --market+ convert amounts to their market value in default valuation com-+ modities++ -X --exchange=COMM+ convert amounts to their market value in commodity COMM++ --value+ convert amounts to cost or market value, more flexibly than+ -B/-V/-X++ --infer-value+ with -V/-X/--value, also infer market prices from transactions++ --auto apply automated posting rules to modify transactions.++ --forecast+ generate future transactions from periodic transaction rules,+ for the next 6 months or till report end date. In hledger-ui,+ also make ordinary future transactions visible.++ --color=WHEN (or --colour=WHEN)+ Should color-supporting commands use ANSI color codes in text+ output. 'auto' (default): whenever stdout seems to be a color-+ supporting terminal. 'always' or 'yes': always, useful eg when+ piping output into 'less -R'. 'never' or 'no': never. A+ NO_COLOR environment variable overrides this.++ When a reporting option appears more than once in the command line, the+ last one takes precedence.++ Some reporting options can also be written as query arguments.++ Command options+ To see options for a particular command, including command-specific op-+ tions, run: hledger COMMAND -h.++ Command-specific options must be written after the command name, eg:+ hledger print -x.++ Additionally, if the command is an addon, you may need to put its op-+ tions after a double-hyphen, eg: hledger ui -- --watch. Or, you can+ run the addon executable directly: hledger-ui --watch.++ Command arguments+ Most hledger commands accept arguments after the command name, which+ are often a query, filtering the data in some way.++ You can save a set of command line options/arguments in a file, and+ then reuse them by writing @FILENAME as a command line argument. Eg:+ hledger bal @foo.args. (To prevent this, eg if you have an argument+ that begins with a literal @, precede it with --, eg: hledger bal --+ @ARG).++ Inside the argument file, each line should contain just one option or+ argument. Avoid the use of spaces, except inside quotes (or you'll see+ a confusing error). Between a flag and its argument, use = (or noth-+ ing). Bad:++ assets depth:2+ -X USD++ Good:++ assets+ depth:2+ -X=USD++ For special characters (see below), use one less level of quoting than+ you would at the command prompt. Bad:++ -X"$"++ Good:++ -X$++ See also: Save frequently used options.++ Queries+ One of hledger's strengths is being able to quickly report on precise+ subsets of your data. Most commands accept an optional query expres-+ sion, written as arguments after the command name, to filter the data+ by date, account name or other criteria. The syntax is similar to a+ web search: one or more space-separated search terms, quotes to enclose+ whitespace, prefixes to match specific fields, a not: prefix to negate+ the match.++ We do not yet support arbitrary boolean combinations of search terms;+ instead most commands show transactions/postings/accounts which match+ (or negatively match):++ o any of the description terms AND++ o any of the account terms AND++ o any of the status terms AND++ o all the other terms.++ The print command instead shows transactions which:++ o match any of the description terms AND++ o have any postings matching any of the positive account terms AND++ o have no postings matching any of the negative account terms AND++ o match all the other terms.++ The following kinds of search terms can be used. Remember these can+ also be prefixed with not:, eg to exclude a particular subaccount.++ REGEX, acct:REGEX+ match account names by this regular expression. (With no pre-+ fix, acct: is assumed.) same as above++ amt:N, amt:<N, amt:<=N, amt:>N, amt:>=N+ match postings with a single-commodity amount that is equal to,+ less than, or greater than N. (Multi-commodity amounts are not+ tested, and will always match.) 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.++ code:REGEX+ match by transaction code (eg check number)++ cur:REGEX+ match postings or transactions including any amounts whose cur-+ rency/commodity symbol is fully matched by REGEX. (For a par-+ tial match, use .*REGEX.*). Note, to match characters which are+ regex-significant, like the dollar sign ($), you need to prepend+ \. And when using the command line you need to add one more+ level of quoting to hide it from the shell, so eg do: hledger+ print cur:'\$' or hledger print cur:\\$.++ desc:REGEX+ match transaction descriptions.++ date:PERIODEXPR+ match dates within the specified period. PERIODEXPR is a period+ expression (with no report interval). Examples: date:2016,+ date:thismonth, date:2000/2/1-2/15, date:lastweek-. If the+ --date2 command line flag is present, this matches secondary+ dates instead.++ date2:PERIODEXPR+ match secondary dates within the specified period.++ depth:N+ match (or display, depending on command) accounts at or above+ this depth++ note:REGEX+ match transaction notes (part of description right of |, or+ whole description when there's no |)++ payee:REGEX+ match transaction payee/payer names (part of description left of+ |, or whole description when there's no |)++ real:, real:0+ match real or virtual postings respectively++ status:, status:!, status:*+ match unmarked, pending, or cleared transactions respectively++ tag:REGEX[=REGEX]+ match by tag name, and optionally also by tag value. Note a+ tag: query is considered to match a transaction if it matches+ any of the postings. Also remember that postings inherit the+ tags of their parent transaction.++ The following special search term is used automatically in hledger-web,+ only:++ inacct:ACCTNAME+ tells hledger-web to show the transaction register for this ac-+ count. Can be filtered further with acct etc.++ Some of these can also be expressed as command-line options (eg depth:2+ is equivalent to --depth 2). Generally you can mix options and query+ arguments, and the resulting query will be their intersection (perhaps+ excluding the -p/--period option).++ Special characters in arguments and queries+ In shell command lines, option and argument values which contain "prob-+ lematic" characters, ie spaces, and also characters significant to your+ shell such as <, >, (, ), | and $, should be escaped by enclosing them+ in quotes or by writing backslashes before the characters. Eg:++ hledger register -p 'last year' "accounts receivable (receiv-+ able|payable)" amt:\>100.++ More escaping+ Characters significant both to the shell and in regular expressions may+ need one extra level of escaping. These include parentheses, the pipe+ symbol and the dollar sign. Eg, to match the dollar symbol, bash users+ should do:++ hledger balance cur:'\$'++ or:++ hledger balance cur:\\$++ Even more escaping+ When hledger runs an addon executable (eg you type hledger ui, hledger+ runs hledger-ui), it de-escapes command-line options and arguments+ once, so you might need to triple-escape. Eg in bash, running the ui+ command and matching the dollar sign, it's:++ hledger ui cur:'\\$'++ or:++ hledger ui cur:\\\\$++ If you asked why four slashes above, this may help:++ unescaped: $+ escaped: \$+ double-escaped: \\$+ triple-escaped: \\\\$++ (The number of backslashes in fish shell is left as an exercise for the+ reader.)++ You can always avoid the extra escaping for addons by running the addon+ directly:++ hledger-ui cur:\\$++ Less escaping+ Inside an argument file, or in the search field of hledger-ui or+ hledger-web, or at a GHCI prompt, you need one less level of escaping+ than at the command line. And backslashes may work better than quotes.+ Eg:++ ghci> :main balance cur:\$++ Unicode characters+ hledger is expected to handle non-ascii characters correctly:++ o they should be parsed correctly in input files and on the command+ line, by all hledger tools (add, iadd, hledger-web's search/add/edit+ forms, etc.)++ o they should be displayed correctly by all hledger tools, and on-+ screen alignment should be preserved.++ This requires a well-configured environment. Here are some tips:++ o A system locale must be configured, and it must be one that can de-+ code the characters being used. In bash, you can set a locale like+ this: export LANG=en_US.UTF-8. There are some more details in Trou-+ bleshooting. This step is essential - without it, hledger will quit+ on encountering a non-ascii character (as with all GHC-compiled pro-+ grams).++ o your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)+ must support unicode++ o the terminal must be using a font which includes the required unicode+ glyphs++ o the terminal should be configured to display wide characters as dou-+ ble width (for report alignment)++ o 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 stan-+ dard 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).++ Input files+ hledger reads transactions from a data file (and the add command writes+ to it). By default this file is $HOME/.hledger.journal (or on Windows,+ something like C:/Users/USER/.hledger.journal). You can override this+ with the $LEDGER_FILE environment variable:++ $ setenv LEDGER_FILE ~/finance/2016.journal+ $ hledger stats++ or with the -f/--file option:++ $ hledger -f /some/file stats++ The file name - (hyphen) means standard input:++ $ cat some.journal | hledger -f-++ Usually the data file is in hledger's journal format, but it can be in+ any of the supported file formats, which currently are:++ Reader: Reads: Used for file exten-+ sions:+ -----------------------------------------------------------------------------+ journal hledger journal files and some Ledger .journal .j .hledger+ journals, for transactions .ledger+ time- timeclock files, for precise time log- .timeclock+ clock ging+ timedot timedot files, for approximate time .timedot+ logging+ csv comma/semicolon/tab/other-separated .csv .ssv .tsv+ values, for data import++ hledger detects the format automatically based on the file extensions+ shown above. If it can't recognise the file extension, it assumes+ journal format. So for non-journal files, it's important to use a+ recognised file extension, so as to either read successfully or to show+ relevant error messages.++ When you can't ensure the right file extension, not to worry: you can+ force a specific reader/format by prefixing the file path with the for-+ mat and a colon. Eg to read a .dat file as csv:++ $ hledger -f csv:/some/csv-file.dat stats+ $ echo 'i 2009/13/1 08:00:00' | hledger print -ftimeclock:-++ You can specify multiple -f options, to read multiple files as one big+ journal. There are some limitations with this:++ o directives in one file will not affect the other files++ o balance assertions will not see any account balances from previous+ files++ If you need either of those things, you can++ o use a single parent file which includes the others++ o or concatenate the files into one before reading, eg: cat a.journal+ b.journal | hledger -f- CMD.++ Strict mode+ hledger checks input files for valid data. By default, the most impor-+ tant errors are detected, while still accepting easy journal files+ without a lot of declarations:++ o Are the input files parseable, with valid syntax ?++ o Are all transactions balanced ?++ o Do all balance assertions pass ?++ With the -s/--strict flag, additional checks are performed:++ o Are all accounts posted to, declared with an account directive ?+ (Account error checking)++ o Are all commodities declared with a commodity directive ? (Commodity+ error checking)++ See also: https://hledger.org/checking-for-errors.html++ experimental.++ 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:++ $ hledger print > foo.txt++ Some commands (print, register, stats, the balance commands) also pro-+ vide the -o/--output-file option, which does the same thing without+ needing the shell. Eg:++ $ hledger print -o foo.txt+ $ hledger print -o - # write to stdout (the default)++ Output format+ Some commands (print, register, the balance commands) offer a choice of+ output format. In addition to the usual plain text format (txt), there+ are CSV (csv), HTML (html), JSON (json) and SQL (sql). This is con-+ trolled by the -O/--output-format option:++ $ hledger print -O csv++ or, by a file extension specified with -o/--output-file:++ $ hledger balancesheet -o foo.html # write HTML to foo.html++ The -O option can be used to override the file extension if needed:++ $ hledger balancesheet -o foo.txt -O html # write HTML to foo.txt++ Some notes about JSON output:++ o This feature is marked experimental, and not yet much used; you+ should expect our JSON to evolve. Real-world feedback is welcome.++ o Our JSON is rather large and verbose, as it is quite a faithful rep-+ resentation of hledger's internal data types. To understand the+ JSON, read the Haskell type definitions, which are mostly in+ https://github.com/simonmichael/hledger/blob/master/hledger-+ lib/Hledger/Data/Types.hs.++ o hledger represents quantities as Decimal values storing up to 255+ significant digits, eg for repeating decimals. Such numbers can+ arise in practice (from automatically-calculated transaction prices),+ and would break most JSON consumers. So in JSON, we show quantities+ as simple Numbers with at most 10 decimal places. We don't limit the+ number of integer digits, but that part is under your control. We+ hope this approach will not cause problems in practice; if you find+ otherwise, please let us know. (Cf #1195)++ Notes about SQL output:++ o SQL output is also marked experimental, and much like JSON could use+ real-world feedback.++ o SQL output is expected to work with sqlite, MySQL and PostgreSQL++ o SQL output is structured with the expectations that statements will+ be executed in the empty database. If you already have tables cre-+ ated via SQL output of hledger, you would probably want to either+ clear tables of existing data (via delete or truncate SQL statements)+ or drop tables completely as otherwise your postings will be duped.++ Regular expressions+ hledger uses regular expressions in a number of places:++ o query terms, on the command line and in the hledger-web search form:+ REGEX, desc:REGEX, cur:REGEX, tag:...=REGEX++ o CSV rules conditional blocks: if REGEX ...++ o account alias directives and options: alias /REGEX/ = REPLACEMENT,+ --alias /REGEX/=REPLACEMENT++ hledger's regular expressions come from the regex-tdfa library. If+ they're not doing what you expect, it's important to know exactly what+ they support:++ 1. they are case insensitive++ 2. they are infix matching (they do not need to match the entire thing+ being matched)++ 3. they are POSIX ERE (extended regular expressions)++ 4. they also support GNU word boundaries (\b, \B, \<, \>)++ 5. they do not support backreferences; if you write \1, it will match+ the digit 1. Except when doing text replacement, eg in account+ aliases, where backreferences can be used in the replacement string+ to reference capturing groups in the search regexp.++ 6. they do not support mode modifiers ((?s)), character classes (\w,+ \d), or anything else not mentioned above.++ Some things to note:++ o In the alias directive and --alias option, regular expressions must+ be enclosed in forward slashes (/REGEX/). Elsewhere in hledger,+ these are not required.++ o In queries, to match a regular expression metacharacter like $ as a+ literal character, prepend a backslash. Eg to search for amounts+ with the dollar sign in hledger-web, write cur:\$.++ o On the command line, some metacharacters like $ have a special mean-+ ing to the shell and so must be escaped at least once more. See Spe-+ cial characters.++ Smart dates+ hledger's user interfaces accept a flexible "smart date" syntax (unlike+ dates in the journal file). Smart dates allow some english words, can+ be relative to today's date, and can have less-significant date parts+ omitted (defaulting to 1).++ Examples:++ 2004/10/1, 2004-01-01, exact date, several separators allowed. Year+ 2004.9.1 is 4+ digits, month is 1-12, day is 1-31+ 2004 start of year+ 2004/10 start of month+ 10/1 month and day in current year+ 21 day in current month+ october, oct start of month in current year++ yesterday, today, tomor- -1, 0, 1 days from today+ row+ last/this/next -1, 0, 1 periods from the current period+ day/week/month/quar-+ ter/year+ 20181201 8 digit YYYYMMDD with valid year month and day+ 201812 6 digit YYYYMM with valid year and month++ Counterexamples - malformed digit sequences might give surprising re-+ sults:++ 201813 6 digits with an invalid month is parsed as start of+ 6-digit year+ 20181301 8 digits with an invalid month is parsed as start of+ 8-digit year+ 20181232 8 digits with an invalid day gives an error+ 201801012 9+ digits beginning with a valid YYYYMMDD gives an error++ Report start & end date+ Most hledger reports show the full span of time represented by the+ journal data, by default. So, the effective report start and end dates+ will be the earliest and latest transaction or posting dates found in+ the journal.++ Often you will want to see a shorter time span, such as the current+ month. You can specify a start and/or end date using -b/--begin,+ -e/--end, -p/--period or a date: query (described below). All of these+ accept the smart date syntax.++ Some notes:++ o As in Ledger, end dates are exclusive, so you need to write the date+ after the last day you want to include.++ o As noted in reporting options: among start/end dates specified with+ options, the last (i.e. right-most) option takes precedence.++ o The effective report start and end dates are the intersection of the+ start/end dates from options and that from date: queries. That is,+ date:2019-01 date:2019 -p'2000 to 2030' yields January 2019, the+ smallest common time span.++ Examples:++ -b 2016/3/17 begin on St. Patrick's day 2016+ -e 12/1 end at the start of december 1st of the current year+ (11/30 will be the last date included)+ -b thismonth all transactions on or after the 1st of the current month+ -p thismonth all transactions in the current month+ date:2016/3/17.. the above written as queries instead (.. can also be re-+ placed with -)+ date:..12/1+ date:thismonth..+ date:thismonth++ Report intervals+ A report interval can be specified so that commands like register, bal-+ ance and activity will divide their reports into multiple subperiods.+ The basic intervals can be selected with one of -D/--daily,+ -W/--weekly, -M/--monthly, -Q/--quarterly, or -Y/--yearly. More com-+ plex intervals may be specified with a period expression. Report in-+ tervals can not be specified with a query.++ Period expressions+ The -p/--period option accepts period expressions, a shorthand way of+ expressing a start date, end date, and/or report interval all at once.++ Here's a basic period expression specifying the first quarter of 2009.+ Note, hledger always treats start dates as inclusive and end dates as+ exclusive:++ -p "from 2009/1/1 to 2009/4/1"++ Keywords like "from" and "to" are optional, and so are the spaces, as+ long as you don't run two dates together. "to" can also be written as+ ".." or "-". These are equivalent to the above:++ -p "2009/1/1 2009/4/1"+ -p2009/1/1to2009/4/1+ -p2009/1/1..2009/4/1++ Dates are smart dates, so if the current year is 2009, the above can+ also be written as:++ -p "1/1 4/1"+ -p "january-apr"+ -p "this year to 4/1"++ If you specify only one date, the missing start or end date will be the+ earliest or latest transaction in your journal:++ -p "from 2009/1/1" everything after january+ 1, 2009+ -p "from 2009/1" the same+ -p "from 2009" the same+ -p "to 2009" everything before january+ 1, 2009++ A single date with no "from" or "to" defines both the start and end+ date like so:++ -p "2009" the year 2009; equivalent+ to "2009/1/1 to 2010/1/1"+ -p "2009/1" the month of jan; equiva-+ lent to "2009/1/1 to+ 2009/2/1"+ -p "2009/1/1" just that day; equivalent+ to "2009/1/1 to 2009/1/2"++ Or you can specify a single quarter like so:++ -p "2009Q1" first quarter of 2009,+ equivalent to "2009/1/1 to+ 2009/4/1"+ -p "q4" fourth quarter of the cur-+ rent year++ The argument of -p can also begin with, or be, a report interval ex-+ pression. The basic report intervals are daily, weekly, monthly, quar-+ terly, or yearly, which have the same effect as the -D,-W,-M,-Q, or -Y+ flags. Between report interval and start/end dates (if any), the word+ in is optional. Examples:++ -p "weekly from 2009/1/1 to 2009/4/1"+ -p "monthly in 2008"+ -p "quarterly"++ Note that weekly, monthly, quarterly and yearly intervals will always+ start on the first day on week, month, quarter or year accordingly, and+ will end on the last day of same period, even if associated period ex-+ pression specifies different explicit start and end date.++ For example:++ -p "weekly from 2009/1/1 starts on 2008/12/29, closest preceding Mon-+ to 2009/4/1" day+ -p "monthly in starts on 2018/11/01+ 2008/11/25"+ -p "quarterly from starts on 2009/04/01, ends on 2009/06/30,+ 2009-05-05 to 2009-06-01" which are first and last days of Q2 2009+ -p "yearly from starts on 2009/01/01, first day of 2009+ 2009-12-29"++ The following more complex report intervals are also supported: bi-+ weekly, fortnightly, bimonthly, every day|week|month|quarter|year, ev-+ ery N days|weeks|months|quarters|years.++ All of these will start on the first day of the requested period and+ end on the last one, as described above.++ Examples:++ -p "bimonthly from 2008" periods will have boundaries on 2008/01/01,+ 2008/03/01, ...+ -p "every 2 weeks" starts on closest preceding Monday+ -p "every 5 month from periods will have boundaries on 2009/03/01,+ 2009/03" 2009/08/01, ...++ If you want intervals that start on arbitrary day of your choosing and+ span a week, month or year, you need to use any of the following:++ every Nth day of week, every WEEKDAYNAME (eg+ mon|tue|wed|thu|fri|sat|sun), every Nth day [of month], every Nth WEEK-+ DAYNAME [of month], every MM/DD [of year], every Nth MMM [of year], ev-+ ery MMM Nth [of year].++ Examples:++ -p "every 2nd day of periods will go from Tue to Tue+ week"+ -p "every Tue" same+ -p "every 15th day" period boundaries will be on 15th of each+ month+ -p "every 2nd Monday" period boundaries will be on second Monday of+ each month+ -p "every 11/05" yearly periods with boundaries on 5th of Nov+ -p "every 5th Nov" same+ -p "every Nov 5th" same++ Show historical balances at end of 15th each month (N is exclusive end+ date):++ hledger balance -H -p "every 16th day"++ Group postings from start of wednesday to end of next tuesday (N is+ start date and exclusive end date):++ hledger register checking -p "every 3rd day of week"++ Depth limiting+ With the --depth N option (short form: -N), commands like account, bal-+ ance and register will show only the uppermost accounts in the account+ tree, down to level N. Use this when you want a summary with less de-+ tail. This flag has the same effect as a depth: query argument (so -2,+ --depth=2 or depth:2 are equivalent).++ Pivoting+ Normally hledger sums amounts, and organizes them in a hierarchy, based+ on account name. The --pivot FIELD option causes it to sum and orga-+ nize hierarchy based on the value of some other field instead. FIELD+ can be: code, description, payee, note, or the full name (case insensi-+ tive) of any tag. As with account names, values containing colon:sepa-+ rated:parts will be displayed hierarchically in reports.++ --pivot is a general option affecting all reports; you can think of+ hledger transforming the journal before any other processing, replacing+ every posting's account name with the value of the specified field on+ that posting, inheriting it from the transaction or using a blank value+ if it's not present.++ An example:++ 2016/02/16 Member Fee Payment+ assets:bank account 2 EUR+ income:member fees -2 EUR ; member: John Doe++ Normal balance report showing account names:++ $ hledger balance+ 2 EUR assets:bank account+ -2 EUR income:member fees+ --------------------+ 0++ Pivoted balance report, using member: tag values instead:++ $ hledger balance --pivot member+ 2 EUR+ -2 EUR John Doe+ --------------------+ 0++ One way to show only amounts with a member: value (using a query, de-+ scribed below):++ $ hledger balance --pivot member tag:member=.+ -2 EUR John Doe+ --------------------+ -2 EUR++ Another way (the acct: query matches against the pivoted "account+ name"):++ $ hledger balance --pivot member acct:.+ -2 EUR John Doe+ --------------------+ -2 EUR++ Valuation+ Instead of reporting amounts in their original commodity, hledger can+ convert them to cost/sale amount (using the conversion rate recorded in+ the transaction), or to market value (using some market price on a cer-+ tain date). This is controlled by the --value=TYPE[,COMMODITY] option,+ but we also provide the simpler -B/-V/-X flags, and usually one of+ those is all you need.++ -B: Cost+ The -B/--cost flag converts amounts to their cost or sale amount at+ transaction time, if they have a transaction price specified.++ -V: Value+ The -V/--market flag converts amounts to market value in their default+ valuation commodity, using the market prices in effect on the valuation+ date(s), if any. More on these in a minute.++ -X: Value in specified commodity+ The -X/--exchange=COMM option is like -V, except you tell it which cur-+ rency you want to convert to, and it tries to convert everything to+ that.++ Valuation date+ Since market prices can change from day to day, market value reports+ have a valuation date (or more than one), which determines which market+ prices will be used.++ For single period reports, if an explicit report end date is specified,+ that will be used as the valuation date; otherwise the valuation date+ is "today".++ For multiperiod reports, each column/period is valued on the last day+ of the period, by default.++ Market prices+ (experimental)++ 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 :++ 1. A declared market price or inferred market price: A's latest market+ price in B on or before the valuation date as declared by a P direc-+ tive, or (with the --infer-value flag) inferred from transaction+ prices.++ 2. A reverse market price: the inverse of a declared or inferred market+ price from B to A.++ 3. A a forward chain of market prices: a synthetic price formed by com-+ bining the shortest chain of "forward" (only 1 above) market prices,+ leading from A to B.++ 4. A any chain of market prices: a chain of any market prices, includ-+ ing both forward and reverse prices (1 and 2 above), leading from A+ to B.++ Amounts for which no applicable market price can be found, are not con-+ verted.++ --infer-value: market prices from transactions+ (experimental)++ 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 transaction prices as additional market+ prices (as Ledger does) ? We could produce value reports without need-+ ing P directives at all.++ Adding the --infer-value flag to -V, -X or --value enables this. So+ for example, hledger bs -V --infer-value will get market prices both+ from P directives and from transactions.++ There is a downside: value reports can sometimes be affected in confus-+ ing/undesired ways by your journal entries. If this happens to you,+ read all of this Valuation section carefully, and try adding --debug or+ --debug=2 to troubleshoot.++ --infer-value can infer market prices from:++ o multicommodity transactions with explicit prices (@/@@)++ o multicommodity transactions with implicit prices (no @, two commodi-+ ties, unbalanced). (With these, the order of postings matters.+ hledger print -x can be useful for troubleshooting.)++ o but not, currently, from "more correct" multicommodity transactions+ (no @, multiple commodities, balanced).++ Valuation commodity+ (experimental)++ When you specify a valuation commodity (-X COMM or --value TYPE,COMM):+ hledger will convert all amounts to COMM, wherever it can find a suit-+ able market price (including by reversing or chaining prices).++ When you leave the valuation commodity unspecified (-V or --value+ TYPE):+ For each commodity A, hledger picks a default valuation commodity as+ follows, in this order of preference:++ 1. The price commodity from the latest P-declared market price for A on+ or before valuation date.++ 2. 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.)++ 3. If there are no P directives at all (any commodity or date) and the+ --infer-value flag is used: the price commodity from the latest+ transaction-inferred price for A on or before valuation date.++ This means:++ o If you have P directives, they determine which commodities -V will+ convert, and to what.++ o If you have no P directives, and use the --infer-value flag, transac-+ tion prices determine it.++ Amounts for which no valuation commodity can be found are not con-+ verted.++ Simple valuation examples+ Here are some quick examples of -V:++ ; one euro is worth this many dollars from nov 1+ P 2016/11/01 EUR $1.10++ ; purchase some euros on nov 3+ 2016/11/3+ assets:euros EUR100+ assets:checking++ ; the euro is worth fewer dollars by dec 21+ P 2016/12/21 EUR $1.03++ How many euros do I have ?++ $ hledger -f t.j bal -N euros+ EUR100 assets:euros++ What are they worth at end of nov 3 ?++ $ hledger -f t.j bal -N euros -V -e 2016/11/4+ $110.00 assets:euros++ What are they worth after 2016/12/21 ? (no report end date specified,+ defaults to today)++ $ hledger -f t.j bal -N euros -V+ $103.00 assets:euros++ --value: Flexible valuation+ -B, -V and -X are special cases of the more general --value option:++ --value=TYPE[,COMM] TYPE is cost, then, end, now or YYYY-MM-DD.+ COMM is an optional commodity symbol.+ Shows amounts converted to:+ - cost commodity using transaction prices (then optionally to COMM using market prices at period end(s))+ - 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++ The TYPE part selects cost or value and valuation date:++ --value=cost+ Convert amounts to cost, using the prices recorded in transac-+ tions.++ --value=then+ Convert amounts to their value in the default valuation commod-+ ity, using market prices on each posting's date. This is cur-+ rently supported only by the print and register commands.++ --value=end+ Convert amounts to their value in the default valuation commod-+ ity, using market prices on the last day of the report period+ (or if unspecified, the journal's end date); or in multiperiod+ reports, market prices on the last day of each subperiod.++ --value=now+ Convert amounts to their value in the default valuation commod-+ ity using current market prices (as of when report is gener-+ ated).++ --value=YYYY-MM-DD+ Convert amounts to their value in the default valuation commod-+ ity using market prices on this date.++ To select a different valuation commodity, add the optional ,COMM part:+ a comma, then the target commodity's symbol. Eg: --value=now,EUR.+ hledger will do its best to convert amounts to this commodity, deducing+ market prices as described above.++ More valuation examples+ Here are some examples showing the effect of --value, as seen with+ print:++ 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 @ 5 B++ 2000-02-01+ (a) 1 A @ 6 B++ 2000-03-01+ (a) 1 A @ 7 B++ Show the cost of each posting:++ $ hledger -f- print --value=cost+ 2000-01-01+ (a) 5 B++ 2000-02-01+ (a) 6 B++ 2000-03-01+ (a) 7 B++ Show the value as of the last day of the report period (2000-02-29):++ $ hledger -f- print --value=end date:2000/01-2000/03+ 2000-01-01+ (a) 2 B++ 2000-02-01+ (a) 2 B++ With no report period specified, that shows the value as of the last+ day of the journal (2000-03-01):++ $ hledger -f- print --value=end+ 2000-01-01+ (a) 3 B++ 2000-02-01+ (a) 3 B++ 2000-03-01+ (a) 3 B++ Show the current value (the 2000-04-01 price is still in effect today):++ $ hledger -f- print --value=now+ 2000-01-01+ (a) 4 B++ 2000-02-01+ (a) 4 B++ 2000-03-01+ (a) 4 B++ Show the value on 2000/01/15:++ $ 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++ You may need to explicitly set a commodity's display style, when re-+ verse prices are used. Eg this output might be surprising:++ P 2000-01-01 A 2B++ 2000-01-01+ a 1B+ b++ $ hledger print -x -X A+ 2000-01-01+ a 0+ b 0++ Explanation: because there's no amount or commodity directive specify-+ ing a display style for A, 0.5A gets the default style, which shows no+ decimal digits. Because the displayed amount looks like zero, the com-+ modity symbol and minus sign are not displayed either. Adding a com-+ modity directive sets a more useful display style for A:++ P 2000-01-01 A 2B+ commodity 0.00A++ 2000-01-01+ a 1B+ b++ $ hledger print -X A+ 2000-01-01+ a 0.50A+ b -0.50A++ Effect of valuation on reports+ Here is a reference for how valuation is supposed to affect each part+ of hledger's reports (and a glossary). (It's wide, you'll have to+ scroll sideways.) It may be useful when troubleshooting. If you find+ problems, please report them, ideally with a reproducible example. Re-+ lated: #329, #1083.++ Report type -B, -V, -X --value=then --value=end --value=DATE,+ --value=cost --value=now+ --------------------------------------------------------------------------------------------+ print+ posting cost value at re- value at value at re- value at+ amounts port end or posting date port or jour- DATE/today+ today nal end+ balance as- unchanged unchanged unchanged unchanged unchanged+ ser-+ tions/as-+ signments++ register+ starting cost value at day not sup- value at day value at+ balance before report ported before report DATE/today+ (-H) or journal or journal+ start start+ posting cost value at re- value at value at re- value at+ amounts port end or posting date port or jour- DATE/today+ today nal end+ summary summarised value at pe- sum of post- value at pe- value at+ posting cost riod ends ings in in- riod ends DATE/today+ amounts terval, val-+ with report ued at in-+ interval terval start+ running to- sum/average sum/average sum/average sum/average sum/average+ tal/average of displayed of displayed of displayed of displayed of displayed+ values values values values values++ balance+ (bs, bse,+ cf, is)+ balance sums of costs value at re- not sup- value at re- value at+ changes port end or ported port or jour- DATE/today of+ today of sums nal end of sums of post-+ of postings sums of post- ings+ ings+ budget like balance like balance not sup- like balances like balance+ amounts changes changes ported changes+ (--budget)+ grand total sum of dis- sum of dis- not sup- sum of dis- sum of dis-+ played values played values ported played values played values++ balance+ (bs, bse,+ cf, is)+ with report+ interval+ starting sums of costs value at re- not sup- value at re- sums of post-+ balances of postings port start of ported port start of ings before+ (-H) before report sums of all sums of all report start+ start postings be- postings be-+ fore report fore report+ start start+++++++ balance sums of costs same as not sup- balance value at+ changes of postings --value=end ported change in DATE/today of+ (bal, is, in period each period, sums of post-+ bs valued at pe- ings+ --change, riod ends+ cf+ --change)+ end bal- sums of costs same as not sup- period end value at+ ances (bal of postings --value=end ported balances, DATE/today of+ -H, is --H, from before valued at pe- sums of post-+ bs, cf) report start riod ends ings+ to period end+ budget like balance like balance not sup- like balances like balance+ amounts changes/end changes/end ported changes/end+ (--budget) balances balances balances+ row totals, sums, aver- sums, aver- not sup- sums, aver- sums, aver-+ row aver- ages of dis- ages of dis- ported ages of dis- ages of dis-+ ages (-T, played values played values played values played values+ -A)+ column to- sums of dis- sums of dis- not sup- sums of dis- sums of dis-+ tals played values played values ported played values played values+ grand to- sum, average sum, average not sup- sum, average sum, average+ tal, grand of column to- of column to- ported of column to- of column to-+ average tals tals tals tals+++ --cumulative is omitted to save space, it works like -H but with a zero+ starting balance.++ Glossary:++ cost calculated using price(s) recorded in the transaction(s).++ value market value using available market price declarations, or the+ unchanged amount if no conversion rate can be found.++ report start+ the first day of the report period specified with -b or -p or+ date:, otherwise today.++ report or journal start+ the first day of the report period specified with -b or -p or+ date:, otherwise the earliest transaction date in the journal,+ otherwise today.++ report end+ the last day of the report period specified with -e or -p or+ date:, otherwise today.++ report or journal end+ the last day of the report period specified with -e or -p or+ date:, otherwise the latest transaction date in the journal,+ otherwise today.++ report interval+ a flag (-D/-W/-M/-Q/-Y) or period expression that activates the+ report's multi-period mode (whether showing one or many subperi-+ ods).++COMMANDS+ hledger provides a number of subcommands; hledger with no arguments+ shows a list.++ If you install additional hledger-* packages, or if you put programs or+ scripts named hledger-NAME in your PATH, these will also be listed as+ subcommands.++ Run a subcommand by writing its name as first argument (eg hledger in-+ comestatement). You can also write one of the standard short aliases+ displayed in parentheses in the command list (hledger b), or any any+ unambiguous prefix of a command name (hledger inc).++ Here are all the builtin commands in alphabetical order. See also+ hledger for a more organised command list, and hledger CMD -h for de-+ tailed command help.++ accounts+ accounts, a+ Show account names.++ This command lists account names, either declared with account direc-+ tives (--declared), posted to (--used), or both (the default). With+ query arguments, only matched account names and account names refer-+ enced by matched postings are shown. It shows a flat list by default.+ With --tree, it uses indentation to show the account hierarchy. In+ flat mode you can add --drop N to omit the first few account name com-+ ponents. Account names can be depth-clipped with depth:N or --depth N+ or -N.++ Examples:++ $ hledger accounts+ assets:bank:checking+ assets:bank:saving+ assets:cash+ expenses:food+ expenses:supplies+ income:gifts+ income:salary+ liabilities:debts++ activity+ activity+ Show an ascii barchart of posting counts per interval.++ The activity command displays an ascii histogram showing transaction+ counts by day, week, month or other reporting interval (by day is the+ default). With query arguments, it counts only matched transactions.++ Examples:++ $ hledger activity --quarterly+ 2008-01-01 **+ 2008-04-01 *******+ 2008-07-01+ 2008-10-01 **++ add+ add+ Prompt for transactions and add them to the journal. Any arguments+ will be used as default inputs for the first N prompts.++ Many hledger users edit their journals directly with a text editor, or+ generate them from CSV. For more interactive data entry, there is the+ add command, which prompts interactively on the console for new trans-+ actions, and appends them to the journal file (if there are multiple -f+ FILE options, the first file is used.) Existing transactions are not+ changed. This is the only hledger command that writes to the journal+ file.++ To use it, just run hledger add and follow the prompts. You can add as+ many transactions as you like; when you are finished, enter . or press+ control-d or control-c to exit.++ Features:++ o add tries to provide useful defaults, using the most similar (by de-+ scription) recent transaction (filtered by the query, if any) as a+ template.++ o You can also set the initial defaults with command line arguments.++ o Readline-style edit keys can be used during data entry.++ o The tab key will auto-complete whenever possible - accounts, descrip-+ tions, dates (yesterday, today, tomorrow). If the input area is+ empty, it will insert the default value.++ o If the journal defines a default commodity, it will be added to any+ bare numbers entered.++ o A parenthesised transaction code may be entered following a date.++ o Comments and tags may be entered following a description or amount.++ o If you make a mistake, enter < at any prompt to go one step backward.++ o Input prompts are displayed in a different colour when the terminal+ supports it.++ Example (see the tutorial for a detailed explanation):++ $ hledger add+ Adding transactions to journal file /src/hledger/examples/sample.journal+ Any command line arguments will be used as defaults.+ Use tab key to complete, readline keys to edit, enter to accept defaults.+ An optional (CODE) may follow transaction dates.+ An optional ; COMMENT may follow descriptions or amounts.+ If you make a mistake, enter < at any prompt to go one step backward.+ To end a transaction, enter . when prompted.+ To quit, enter . at a date prompt or press control-d or control-c.+ Date [2015/05/22]:+ Description: supermarket+ Account 1: expenses:food+ Amount 1: $10+ Account 2: assets:checking+ Amount 2 [$-10.0]:+ Account 3 (or . or enter to finish this transaction): .+ 2015/05/22 supermarket+ expenses:food $10+ assets:checking $-10.0++ Save this transaction to the journal ? [y]:+ Saved.+ Starting the next transaction (. or ctrl-D/ctrl-C to quit)+ Date [2015/05/22]: <CTRL-D> $++ On Microsoft Windows, the add command makes sure that no part of the+ file path ends with a period, as that would cause problems (#1056).++ aregister+ aregister, areg+ Show transactions affecting a particular account, and the account's+ running balance.++ aregister shows the transactions affecting a particular account (and+ its subaccounts), from the point of view of that account. Each line+ shows:++ o the transaction's (or posting's, see below) date++ o the names of the other account(s) involved++ o the net change to this account's balance++ o the account's historical running balance (including balance from+ transactions before the report start date).++ With aregister, each line represents a whole transaction - as in+ hledger-ui, hledger-web, and your bank statement. By contrast, the+ register command shows individual postings, across all accounts. You+ might prefer aregister for reconciling with real-world asset/liability+ accounts, and register for reviewing detailed revenues/expenses.++ An account must be specified as the first argument, which should be the+ full account name or an account pattern (regular expression). aregis-+ ter will show transactions in this account (the first one matched) and+ any of its subaccounts.++ Any additional arguments form a query which will filter the transac-+ tions shown.++ Transactions making a net change of zero are not shown by default; add+ the -E/--empty flag to show them.++ aregister and custom posting dates+ Transactions whose date is outside the report period can still be+ shown, if they have a posting to this account dated inside the report+ period. (And in this case it's the posting date that is shown.) This+ ensures that aregister can show an accurate historical running balance,+ matching the one shown by register -H with the same arguments.++ To filter strictly by transaction date instead, add the --txn-dates+ flag. If you use this flag and some of your postings have custom+ dates, it's probably best to assume the running balance is wrong.++ Output format+ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, and json.++ Examples:++ Show all transactions and historical running balance in the first ac-+ count whose name contains "checking":++ $ hledger areg checking++ Show transactions and historical running balance in all asset accounts+ during july:++ $ hledger areg assets date:jul++ balance+ balance, bal, b+ Show accounts and their balances.++ The balance command is hledger's most versatile command. Note, despite+ the name, it is not always used for showing real-world account bal-+ ances; the more accounting-aware balancesheet and incomestatement may+ be more convenient for that.++ By default, it displays all accounts, and each account's change in bal-+ ance during the entire period of the journal. Balance changes are cal-+ culated by adding up the postings in each account. You can limit the+ postings matched, by a query, to see fewer accounts, changes over a+ different time period, changes from only cleared transactions, etc.++ If you include an account's complete history of postings in the report,+ the balance change is equivalent to the account's current ending bal-+ ance. For a real-world account, typically you won't have all transac-+ tions in the journal; instead you'll have all transactions after a cer-+ tain date, and an "opening balances" transaction setting the correct+ starting balance on that date. Then the balance command will show+ real-world account balances. In some cases the -H/--historical flag is+ used to ensure this (more below).++ The balance command can produce several styles of report:++ Classic balance report+ This is the original balance report, as found in Ledger. It usually+ looks like this:++ $ hledger balance+ $-1 assets+ $1 bank:saving+ $-2 cash+ $2 expenses+ $1 food+ $1 supplies+ $-2 income+ $-1 gifts+ $-1 salary+ $1 liabilities:debts+ --------------------+ 0++ By default, accounts are displayed hierarchically, with subaccounts in-+ dented below their parent, with accounts at each level of the tree+ sorted by declaration order if declared, then by account name.++ "Boring" accounts, which contain a single interesting subaccount and no+ balance of their own, are elided into the following line for more com-+ pact output. (Eg above, the "liabilities" account.) Use --no-elide to+ prevent this.++ Account balances are "inclusive" - they include the balances of any+ subaccounts.++ Accounts which have zero balance (and no non-zero subaccounts) are+ omitted. Use -E/--empty to show them.++ A final total is displayed by default; use -N/--no-total to suppress+ it, eg:++ $ hledger balance -p 2008/6 expenses --no-total+ $2 expenses+ $1 food+ $1 supplies++ Customising the classic balance report+ You can customise the layout of classic balance reports with --format+ FMT:++ $ hledger balance --format "%20(account) %12(total)"+ assets $-1+ bank:saving $1+ cash $-2+ expenses $2+ food $1+ supplies $1+ income $-2+ gifts $-1+ salary $-1+ liabilities:debts $1+ ---------------------------------+ 0++ The FMT format string (plus a newline) specifies the formatting applied+ to each account/balance pair. It may contain any suitable text, with+ data fields interpolated like so:++ %[MIN][.MAX](FIELDNAME)++ o MIN pads with spaces to at least this width (optional)++ o MAX truncates at this width (optional)++ o FIELDNAME must be enclosed in parentheses, and can be one of:++ o depth_spacer - a number of spaces equal to the account's depth, or+ if MIN is specified, MIN * depth spaces.++ o account - the account's name++ o total - the account's balance/posted total, right justified++ Also, FMT can begin with an optional prefix to control how multi-com-+ modity amounts are rendered:++ o %_ - render on multiple lines, bottom-aligned (the default)++ o %^ - render on multiple lines, top-aligned++ o %, - render on one line, comma-separated++ There are some quirks. Eg in one-line mode, %(depth_spacer) has no ef-+ fect, instead %(account) has indentation built in. Experimentation may+ be needed to get pleasing results.++ Some example formats:++ o %(total) - the account's total++ o %-20.20(account) - the account's name, left justified, padded to 20+ characters and clipped at 20 characters++ o %,%-50(account) %25(total) - account name padded to 50 characters,+ total padded to 20 characters, with multiple commodities rendered on+ one line++ o %20(total) %2(depth_spacer)%-(account) - the default format for the+ single-column balance report++ Colour support+ In terminal output, when colour is enabled, the balance command shows+ negative amounts in red.++ Flat mode+ To see a flat list instead of the default hierarchical display, use+ --flat. In this mode, accounts (unless depth-clipped) show their full+ names and "exclusive" balance, excluding any subaccount balances. In+ this mode, you can also use --drop N to omit the first few account name+ components.++ $ hledger balance -p 2008/6 expenses -N --flat --drop 1+ $1 food+ $1 supplies++ Depth limited balance reports+ With --depth N or depth:N or just -N, balance reports show accounts+ only to the specified numeric depth. This is very useful to summarise+ a complex set of accounts and get an overview.++ $ hledger balance -N -1+ $-1 assets+ $2 expenses+ $-2 income+ $1 liabilities++ Flat-mode balance reports, which normally show exclusive balances, show+ inclusive balances at the depth limit.++ Percentages+ With -% or --percent, balance reports show each account's value ex-+ pressed as a percentage of the column's total. This is useful to get+ an overview of the relative sizes of account balances. For example to+ obtain an overview of expenses:++ $ hledger balance expenses -%+ 100.0 % expenses+ 50.0 % food+ 50.0 % supplies+ --------------------+ 100.0 %++ Note that --tree does not have an effect on -%. The percentages are+ always relative to the total sum of each column, they are never rela-+ tive to the parent account.++ Since the percentages are relative to the columns sum, it is usually+ not useful to calculate percentages if the signs of the amounts are+ mixed. Although the results are technically correct, they are most+ likely useless. Especially in a balance report that sums up to zero+ (eg hledger balance -B) all percentage values will be zero.++ This flag does not work if the report contains any mixed commodity ac-+ counts. If there are mixed commodity accounts in the report be sure to+ use -V or -B to coerce the report into using a single commodity.++ Sorting by amount+ With -S/--sort-amount, accounts with the largest (most positive) bal-+ ances are shown first. For example, hledger bal expenses -MAS shows+ your biggest averaged monthly expenses first.++ Revenues and liability balances are typically negative, however, so -S+ shows these in reverse order. To work around this, you can add --in-+ vert to flip the signs. Or, use one of the sign-flipping reports like+ balancesheet or incomestatement, which also support -S. Eg: hledger is+ -MAS.++ Multicolumn balance report+ Multicolumn or tabular balance reports are a very useful hledger fea-+ ture, and usually the preferred style. They share many of the above+ features, but they show the report as a table, with columns represent-+ ing time periods. This mode is activated by providing a reporting in-+ terval.++ There are three types of multicolumn balance report, showing different+ information:++ 1. By default: each column shows the sum of postings in that period, ie+ the account's change of balance in that period. This is useful eg+ for a monthly income statement:++ $ hledger balance --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++ 2. With --cumulative: each column shows the ending balance for that pe-+ riod, accumulating the changes across periods, starting from 0 at+ the report start date:++ $ hledger balance --quarterly income expenses -E --cumulative+ Ending balances (cumulative) in 2008:++ || 2008/03/31 2008/06/30 2008/09/30 2008/12/31+ ===================++=================================================+ expenses:food || 0 $1 $1 $1+ expenses:supplies || 0 $1 $1 $1+ income:gifts || 0 $-1 $-1 $-1+ income:salary || $-1 $-1 $-1 $-1+ -------------------++-------------------------------------------------+ || $-1 0 0 0++ 3. With --historical/-H: each column shows the actual historical ending+ balance for that period, accumulating the changes across periods,+ starting from the actual balance at the report start date. This is+ useful eg for a multi-period balance sheet, and when you are showing+ only the data after a certain start date:++ $ hledger balance ^assets ^liabilities --quarterly --historical --begin 2008/4/1+ Ending balances (historical) in 2008/04/01-2008/12/31:++ || 2008/06/30 2008/09/30 2008/12/31+ ======================++=====================================+ assets:bank:checking || $1 $1 0+ assets:bank:saving || $1 $1 $1+ assets:cash || $-2 $-2 $-2+ liabilities:debts || 0 0 $1+ ----------------------++-------------------------------------+ || 0 0 0++ Note that --cumulative or --historical/-H disable --row-total/-T, since+ summing end balances generally does not make sense.++ Multicolumn balance reports display accounts in flat mode by default;+ to see the hierarchy, use --tree.++ With a reporting interval (like --quarterly above), the report+ start/end dates will be adjusted if necessary so that they encompass+ the displayed report periods. This is so that the first and last peri-+ ods will be "full" and comparable to the others.++ The -E/--empty flag does two things in multicolumn balance reports:+ first, the report will show all columns within the specified report pe-+ riod (without -E, leading and trailing columns with all zeroes are not+ shown). Second, all accounts which existed at the report start date+ will be considered, not just the ones with activity during the report+ period (use -E to include low-activity accounts which would otherwise+ would be omitted).++ The -T/--row-total flag adds an additional column showing the total for+ each row.++ The -A/--average flag adds a column showing the average value in each+ row.++ Here's an example of all three:++ $ hledger balance -Q income expenses --tree -ETA+ Balance changes in 2008:++ || 2008q1 2008q2 2008q3 2008q4 Total Average+ ============++===================================================+ expenses || 0 $2 0 0 $2 $1+ food || 0 $1 0 0 $1 0+ supplies || 0 $1 0 0 $1 0+ income || $-1 $-1 0 0 $-2 $-1+ gifts || 0 $-1 0 0 $-1 0+ salary || $-1 0 0 0 $-1 0+ ------------++---------------------------------------------------+ || $-1 $1 0 0 0 0++ (Average is rounded to the dollar here since all journal amounts are)++ The --transpose flag can be used to exchange the rows and columns of a+ multicolumn report.++ When showing multicommodity amounts, multicolumn balance reports will+ elide any amounts which have more than two commodities, since otherwise+ columns could get very wide. The --no-elide flag disables this. Hid-+ ing totals with the -N/--no-total flag can also help reduce the width+ of multicommodity reports.++ When the report is still too wide, a good workaround is to pipe it into+ less -RS (-R for colour, -S to chop long lines). Eg: hledger bal -D+ --color=yes | less -RS.++ Budget report+ With --budget, extra columns are displayed showing budget goals for+ each account and period, if any. Budget goals are defined by periodic+ transactions. This is very useful for comparing planned and actual in-+ come, expenses, time usage, etc. --budget is most often combined with+ a report interval.++ For example, you can take average monthly expenses in the common ex-+ pense categories to construct a minimal monthly budget:++ ;; Budget+ ~ monthly+ income $2000+ expenses:food $400+ expenses:bus $50+ expenses:movies $30+ assets:bank:checking++ ;; Two months worth of expenses+ 2017-11-01+ income $1950+ expenses:food $396+ expenses:bus $49+ expenses:movies $30+ expenses:supplies $20+ assets:bank:checking++ 2017-12-01+ income $2100+ expenses:food $412+ expenses:bus $53+ expenses:gifts $100+ assets:bank:checking++ You can now see a monthly budget report:++ $ hledger balance -M --budget+ Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec+ ======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ expenses || $495 [ 103% of $480] $565 [ 118% of $480]+ expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50]+ expenses:food || $396 [ 99% of $400] $412 [ 103% of $400]+ expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30]+ income || $1950 [ 98% of $2000] $2100 [ 105% of $2000]+ ----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0]++ This is different from a normal balance report in several ways:++ o Only accounts with budget goals during the report period are shown,+ by default.++ o In each column, in square brackets after the actual amount, budget+ goal amounts are shown, and the actual/goal percentage. (Note: bud-+ get goals should be in the same commodity as the actual amount.)++ o All parent accounts are always shown, even in flat mode. Eg assets,+ assets:bank, and expenses above.++ o Amounts always include all subaccounts, budgeted or unbudgeted, even+ in flat mode.++ This means that the numbers displayed will not always add up! Eg above,+ the expenses actual amount includes the gifts and supplies transac-+ tions, but the expenses:gifts and expenses:supplies accounts are not+ shown, as they have no budget amounts declared.++ This can be confusing. When you need to make things clearer, use the+ -E/--empty flag, which will reveal all accounts including unbudgeted+ ones, giving the full picture. Eg:++ $ hledger balance -M --budget --empty+ Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec+ ======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ assets:bank || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ assets:bank:checking || $-2445 [ 99% of $-2480] $-2665 [ 107% of $-2480]+ expenses || $495 [ 103% of $480] $565 [ 118% of $480]+ expenses:bus || $49 [ 98% of $50] $53 [ 106% of $50]+ expenses:food || $396 [ 99% of $400] $412 [ 103% of $400]+ expenses:gifts || 0 $100+ expenses:movies || $30 [ 100% of $30] 0 [ 0% of $30]+ expenses:supplies || $20 0+ income || $1950 [ 98% of $2000] $2100 [ 105% of $2000]+ ----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0]++ You can roll over unspent budgets to next period with --cumulative:++ $ hledger balance -M --budget --cumulative+ Budget performance in 2017/11/01-2017/12/31:++ || Nov Dec+ ======================++====================================================+ assets || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]+ assets:bank || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]+ assets:bank:checking || $-2445 [ 99% of $-2480] $-5110 [ 103% of $-4960]+ expenses || $495 [ 103% of $480] $1060 [ 110% of $960]+ expenses:bus || $49 [ 98% of $50] $102 [ 102% of $100]+ expenses:food || $396 [ 99% of $400] $808 [ 101% of $800]+ expenses:movies || $30 [ 100% of $30] $30 [ 50% of $60]+ income || $1950 [ 98% of $2000] $4050 [ 101% of $4000]+ ----------------------++----------------------------------------------------+ || 0 [ 0] 0 [ 0]++ For more examples and notes, see Budgeting.++ Budget report start date+ This might be a bug, but for now: when making budget reports, it's a+ good idea to explicitly set the report's start date to the first day of+ a reporting period, because a periodic rule like ~ monthly generates+ its transactions on the 1st of each month, and if your journal has no+ regular transactions on the 1st, the default report start date could+ exclude that budget goal, which can be a little surprising. Eg here+ the default report period is just the day of 2020-01-15:++ ~ monthly in 2020+ (expenses:food) $500++ 2020-01-15+ expenses:food $400+ assets:checking++ $ hledger bal expenses --budget+ Budget performance in 2020-01-15:++ || 2020-01-15+ ==============++============+ <unbudgeted> || $400+ --------------++------------+ || $400++ To avoid this, specify the budget report's period, or at least the+ start date, with -b/-e/-p/date:, to ensure it includes the budget goal+ transactions (periodic transactions) that you want. Eg, adding -b+ 2020/1/1 to the above:++ $ hledger bal expenses --budget -b 2020/1/1+ Budget performance in 2020-01-01..2020-01-15:++ || 2020-01-01..2020-01-15+ ===============++========================+ expenses:food || $400 [80% of $500]+ ---------------++------------------------+ || $400 [80% of $500]++ Nested budgets+ You can add budgets to any account in your account hierarchy. If you+ have budgets on both parent account and some of its children, then bud-+ get(s) of the child account(s) would be added to the budget of their+ parent, much like account balances behave.++ In the most simple case this means that once you add a budget to any+ account, all its parents would have budget as well.++ To illustrate this, consider the following budget:++ ~ monthly from 2019/01+ expenses:personal $1,000.00+ expenses:personal:electronics $100.00+ liabilities++ With this, monthly budget for electronics is defined to be $100 and+ budget for personal expenses is an additional $1000, which implicitly+ means that budget for both expenses:personal and expenses is $1100.++ Transactions in expenses:personal:electronics will be counted both to-+ wards its $100 budget and $1100 of expenses:personal , and transactions+ in any other subaccount of expenses:personal would be counted towards+ only towards the budget of expenses:personal.++ For example, let's consider these transactions:++ ~ monthly from 2019/01+ expenses:personal $1,000.00+ expenses:personal:electronics $100.00+ liabilities++ 2019/01/01 Google home hub+ expenses:personal:electronics $90.00+ liabilities $-90.00++ 2019/01/02 Phone screen protector+ expenses:personal:electronics:upgrades $10.00+ liabilities++ 2019/01/02 Weekly train ticket+ expenses:personal:train tickets $153.00+ liabilities++ 2019/01/03 Flowers+ expenses:personal $30.00+ liabilities++ As you can see, we have transactions in expenses:personal:electron-+ ics:upgrades and expenses:personal:train tickets, and since both of+ these accounts are without explicitly defined budget, these transac-+ tions would be counted towards budgets of expenses:personal:electronics+ and expenses:personal accordingly:++ $ hledger balance --budget -M+ Budget performance in 2019/01:++ || Jan+ ===============================++===============================+ expenses || $283.00 [ 26% of $1100.00]+ expenses:personal || $283.00 [ 26% of $1100.00]+ expenses:personal:electronics || $100.00 [ 100% of $100.00]+ liabilities || $-283.00 [ 26% of $-1100.00]+ -------------------------------++-------------------------------+ || 0 [ 0]++ And with --empty, we can get a better picture of budget allocation and+ consumption:++ $ hledger balance --budget -M --empty+ Budget performance in 2019/01:++ || Jan+ ========================================++===============================+ expenses || $283.00 [ 26% of $1100.00]+ expenses:personal || $283.00 [ 26% of $1100.00]+ expenses:personal:electronics || $100.00 [ 100% of $100.00]+ expenses:personal:electronics:upgrades || $10.00+ expenses:personal:train tickets || $153.00+ liabilities || $-283.00 [ 26% of $-1100.00]+ ----------------------------------------++-------------------------------+ || 0 [ 0]++ Output format+ This command also supports the output destination and output format op-+ tions The output formats supported are (in most modes): txt, csv, html,+ and json.++ balancesheet+ balancesheet, bs+ This command displays a balance sheet, showing historical ending bal-+ ances of asset and liability accounts. (To see equity as well, use the+ balancesheetequity command.) Amounts are shown with normal positive+ sign, as in conventional financial statements.++ The asset and liability accounts shown are those accounts declared with+ the Asset or Cash or Liability type, or otherwise all accounts under a+ top-level asset or liability account (case insensitive, plurals al-+ lowed).++ Example:++ $ hledger balancesheet+ Balance Sheet++ Assets:+ $-1 assets+ $1 bank:saving+ $-2 cash+ --------------------+ $-1++ Liabilities:+ $1 liabilities:debts+ --------------------+ $1++ Total:+ --------------------+ 0++ With a reporting interval, multiple columns will be shown, one for each+ report period. As with multicolumn balance reports, you can alter the+ report mode with --change/--cumulative/--historical. Normally bal-+ ancesheet shows historical ending balances, which is what you need for+ a balance sheet; note this means it ignores report begin dates (and+ -T/--row-total, since summing end balances generally does not make+ sense). Instead of absolute values percentages can be displayed with+ -%.++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, html, and (experimen-+ tal) json.++ balancesheetequity+ balancesheetequity, bse+ This command displays a balance sheet, showing historical ending bal-+ ances of asset, liability and equity accounts. Amounts are shown with+ normal positive sign, as in conventional financial statements.++ The asset, liability and equity accounts shown are those accounts de-+ clared with the Asset, Cash, Liability or Equity type, or otherwise all+ accounts under a top-level asset, liability or equity account (case in-+ sensitive, plurals allowed).++ Example:++ $ hledger balancesheetequity+ Balance Sheet With Equity++ Assets:+ $-2 assets+ $1 bank:saving+ $-3 cash+ --------------------+ $-2++ Liabilities:+ $1 liabilities:debts+ --------------------+ $1++ Equity:+ $1 equity:owner+ --------------------+ $1++ Total:+ --------------------+ 0++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, html, and (experimen-+ tal) json.++ cashflow+ cashflow, cf+ This command displays a cashflow statement, showing the inflows and+ outflows affecting "cash" (ie, liquid) assets. Amounts are shown with+ normal positive sign, as in conventional financial statements.++ The "cash" accounts shown are those accounts declared with the Cash+ type, or otherwise all accounts under a top-level asset account (case+ insensitive, plural allowed) which do not have fixed, investment, re-+ ceivable or A/R in their name.++ Example:++ $ hledger cashflow+ Cashflow Statement++ Cash flows:+ $-1 assets+ $1 bank:saving+ $-2 cash+ --------------------+ $-1++ Total:+ --------------------+ $-1++ With a reporting interval, multiple columns will be shown, one for each+ report period. Normally cashflow shows changes in assets per period,+ though as with multicolumn balance reports you can alter the report+ mode with --change/--cumulative/--historical. Instead of absolute val-+ ues percentages can be displayed with -%.++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, html, and (experimen-+ tal) json.++ check+ check+ Check for various kinds of errors in your data. experimental++ hledger provides a number of built-in error checks to help prevent+ problems in your data. Some of these are run automatically; or, you+ can use this check command to run them on demand, with no output and a+ zero exit code if all is well. Some examples:++ hledger check # basic checks+ hledger check -s # basic + strict checks+ hledger check ordereddates uniqueleafnames # basic + specified checks++ Here are the checks currently available:++ Basic checks+ These are always run by this command and other commands:++ o parseable - data files are well-formed and can be successfully parsed++ o autobalanced - all transactions are balanced, inferring missing+ amounts where necessary, and possibly converting commodities using+ transaction prices or automatically-inferred transaction prices++ o assertions - all balance assertions in the journal are passing.+ (This check can be disabled with -I/--ignore-assertions.)++ Strict checks+ These are always run by this and other commands when -s/--strict is+ used (strict mode):++ o accounts - all account names used by transactions have been declared++ o commodities - all commodity symbols used have been declared++ Other checks+ These checks can be run by specifying their names as arguments to the+ check command:++ o ordereddates - transactions are ordered by date (similar to the old+ check-dates command)++ o uniqueleafnames - all account leaf names are unique (similar to the+ old check-dupes command)++ Addon checks+ Some checks are not yet integrated with this command, but are available+ as add-on commands in https://github.com/simonmichael/hledger/tree/mas-+ ter/bin:++ o hledger-check-tagfiles - all tag values containing / (a forward+ slash) exist as file paths++ o hledger-check-fancyassertions - more complex balance assertions are+ passing++ You could make your own similar scripts to perform custom checks; Cook-+ book -> Scripting may be helpful.++ close+ close, equity+ Prints a "closing balances" transaction and an "opening balances"+ transaction that bring account balances to and from zero, respectively.+ These can be added to your journal file(s), eg to bring asset/liability+ balances forward into a new journal file, or to close out revenues/ex-+ penses to retained earnings at the end of a period.++ You can print just one of these transactions by using the --close or+ --open flag. You can customise their descriptions with the --close-+ desc and --open-desc options.++ One amountless posting to "equity:opening/closing balances" is added to+ balance the transactions, by default. You can customise this account+ name with --close-acct and --open-acct; if you specify only one of+ these, it will be used for both.++ With --x/--explicit, the equity posting's amount will be shown. And if+ it involves multiple commodities, a posting for each commodity will be+ shown, as with the print command.++ With --interleaved, the equity postings are shown next to the postings+ they balance, which makes troubleshooting easier.++ By default, transaction prices in the journal are ignored when generat-+ ing the closing/opening transactions. With --show-costs, this cost in-+ formation is preserved (balance -B reports will be unchanged after the+ transition). Separate postings are generated for each cost in each+ commodity. Note this can generate very large journal entries, if you+ have many foreign currency or investment transactions.++ close usage+ If you split your journal files by time (eg yearly), you will typically+ run this command at the end of the year, and save the closing transac-+ tion as last entry of the old file, and the opening transaction as the+ first entry of the new file. This makes the files self contained, so+ that correct balances are reported no matter which of them are loaded.+ Ie, if you load just one file, the balances are initialised correctly;+ or if you load several files, the redundant closing/opening transac-+ tions cancel each other out. (They will show up in print or register+ reports; you can exclude them with a query like not:desc:'(open-+ ing|closing) balances'.)++ If you're running a business, you might also use this command to "close+ the books" at the end of an accounting period, transferring income+ statement account balances to retained earnings. (You may want to+ change the equity account name to something like "equity:retained earn-+ ings".)++ By default, the closing transaction is dated yesterday, the balances+ are calculated as of end of yesterday, and the opening transaction is+ dated today. To close on some other date, use: hledger close -e OPEN-+ INGDATE. Eg, to close/open on the 2018/2019 boundary, use -e 2019.+ You can also use -p or date:PERIOD (any starting date is ignored).++ Both transactions will include balance assertions for the closed/re-+ opened accounts. You probably shouldn't use status or realness filters+ (like -C or -R or status:) with this command, or the generated balance+ assertions will depend on these flags. Likewise, if you run this com-+ mand with --auto, the balance assertions will probably always require+ --auto.++ Examples:++ Carrying asset/liability balances into a new file for 2019:++ $ hledger close -f 2018.journal -e 2019 assets liabilities --open+ # (copy/paste the output to the start of your 2019 journal file)+ $ hledger close -f 2018.journal -e 2019 assets liabilities --close+ # (copy/paste the output to the end of your 2018 journal file)++ Now:++ $ hledger bs -f 2019.journal # one file - balances are correct+ $ hledger bs -f 2018.journal -f 2019.journal # two files - balances still correct+ $ hledger bs -f 2018.journal not:desc:closing # to see year-end balances, must exclude closing txn++ Transactions spanning the closing date can complicate matters, breaking+ balance assertions:++ 2018/12/30 a purchase made in 2018, clearing the following year+ expenses:food 5+ assets:bank:checking -5 ; [2019/1/2]++ Here's one way to resolve that:++ ; in 2018.journal:+ 2018/12/30 a purchase made in 2018, clearing the following year+ expenses:food 5+ liabilities:pending++ ; in 2019.journal:+ 2019/1/2 clearance of last year's pending transactions+ liabilities:pending 5 = 0+ assets:checking++ codes+ codes+ List the codes seen in transactions, in the order parsed.++ This command prints the value of each transaction's 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.++ Transactions aren't required to have a code, and missing or empty codes+ will not be shown by default. With the -E/--empty flag, they will be+ printed as blank lines.++ You can add a query to select a subset of transactions.++ Examples:++ 1/1 (123)+ (a) 1++ 1/1 ()+ (a) 1++ 1/1+ (a) 1++ 1/1 (126)+ (a) 1++ $ hledger codes+ 123+ 124+ 126++ $ hledger codes -E+ 123+ 124+++ 126++ commodities+ commodities+ List all commodity/currency symbols used or declared in the journal.++ descriptions+ descriptions+ List the unique descriptions that appear in transactions.++ This command lists the unique descriptions that appear in transactions,+ in alphabetic order. You can add a query to select a subset of trans-+ actions.++ Example:++ $ hledger descriptions+ Store Name+ Gas Station | Petrol+ Person A++ diff+ diff+ Compares a particular account's transactions in two input files. It+ shows any transactions to this account which are in one file but not in+ the other.++ More precisely, for each posting affecting this account in either file,+ it looks for a corresponding posting in the other file which posts the+ same amount to the same account (ignoring date, description, etc.)+ Since postings not transactions are compared, this also works when mul-+ tiple bank transactions have been combined into a single journal entry.++ This is useful eg if you have downloaded an account's 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.++ Examples:++ $ 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:++ files+ files+ List all files included in the journal. With a REGEX argument, only+ file names matching the regular expression (case sensitive) are shown.++ help+ help+ Show any of the hledger manuals.++ The help command displays any of the main hledger manuals, in one of+ several ways. Run it with no argument to list the manuals, or provide+ a full or partial manual name to select one.++ hledger manuals are available in several formats. hledger help will+ use the first of these display methods that it finds: info, man,+ $PAGER, less, stdout (or when non-interactive, just stdout). You can+ force a particular viewer with the --info, --man, --pager, --cat flags.++ Examples:++ $ hledger help+ Please choose a manual by typing "hledger help MANUAL" (a substring is ok).+ Manuals: hledger hledger-ui hledger-web journal csv timeclock timedot++ $ hledger help h --man++ hledger(1) hledger User Manuals hledger(1)++ NAME+ hledger - a command-line accounting tool++ SYNOPSIS+ hledger [-f FILE] COMMAND [OPTIONS] [ARGS]+ hledger [-f FILE] ADDONCMD -- [OPTIONS] [ARGS]+ hledger++ DESCRIPTION+ hledger is a cross-platform program for tracking money, time, or any+ ...++ import+ import+ Read new transactions added to each FILE since last run, and add them+ to the main journal file. Or with --dry-run, just print the transac-+ tions that would be added. Or with --catchup, just mark all of the+ FILEs' transactions as imported, without actually importing any.++ The input files are specified as arguments - no need to write -f before+ each one. So eg to add new transactions from all CSV files to the main+ journal, it's just: hledger import *.csv++ New transactions are detected in the same way as print --new: by assum-+ ing transactions are always added to the input files in increasing date+ order, and by saving .latest.FILE state files.++ The --dry-run output is in journal format, so you can filter it, eg to+ see only uncategorised transactions:++ $ hledger import --dry ... | hledger -f- print unknown --ignore-assertions++ Importing balance assignments+ Entries added by import will have their posting amounts made explicit+ (like hledger print -x). This means that any balance assignments in+ imported files must be evaluated; but, imported files don't get to see+ the main file's account balances. As a result, importing entries with+ balance assignments (eg from an institution that provides only balances+ and not posting amounts) will probably generate incorrect posting+ amounts. To avoid this problem, use print instead of import:++ $ hledger print IMPORTFILE [--new] >> $LEDGER_FILE++ (If you think import should leave amounts implicit like print does,+ please test it and send a pull request.)++ Commodity display styles+ Imported amounts will be formatted according to the canonical commodity+ styles (declared or inferred) in the main journal file.++ incomestatement+ incomestatement, is+ This command displays an income statement, showing revenues and ex-+ penses during one or more periods. Amounts are shown with normal posi-+ tive sign, as in conventional financial statements.++ The revenue and expense accounts shown are those accounts declared with+ the Revenue or Expense type, or otherwise all accounts under a top-+ level revenue or income or expense account (case insensitive, plurals+ allowed).++ Example:++ $ hledger incomestatement+ Income Statement++ Revenues:+ $-2 income+ $-1 gifts+ $-1 salary+ --------------------+ $-2++ Expenses:+ $2 expenses+ $1 food+ $1 supplies+ --------------------+ $2++ Total:+ --------------------+ 0++ With a reporting interval, multiple columns will be shown, one for each+ report period. Normally incomestatement shows revenues/expenses per+ period, though as with multicolumn balance reports you can alter the+ report mode with --change/--cumulative/--historical. Instead of abso-+ lute values percentages can be displayed with -%.++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, html, and (experimen-+ tal) json.++ notes+ notes+ List the unique notes that appear in transactions.++ This command lists the unique notes that appear in transactions, in al-+ phabetic order. You can add a query to select a subset of transac-+ tions. The note is the part of the transaction description after a |+ character (or if there is no |, the whole description).++ Example:++ $ hledger notes+ Petrol+ Snacks++ payees+ payees+ List the unique payee/payer names that appear in transactions.++ This command lists the unique payee/payer names that appear in transac-+ tions, in alphabetic order. You can add a query to select a subset of+ transactions. The payee/payer is the part of the transaction descrip-+ tion before a | character (or if there is no |, the whole description).++ Example:++ $ hledger payees+ Store Name+ Gas Station+ Person A++ prices+ prices+ Print market price directives from the journal. With --costs, also+ print synthetic market prices based on transaction prices. With --in-+ verted-costs, also print inverse prices based on transaction prices.+ Prices (and postings providing prices) can be filtered by a query.+ Price amounts are always displayed with their full precision.++ print+ print, txns, p+ Show transaction journal entries, sorted by date.++ The print command displays full journal entries (transactions) from the+ journal file in date order, tidily formatted. With --date2, transac-+ tions are sorted by secondary date instead.++ print's output is always a valid hledger journal.+ It preserves all transaction information, but it does not preserve di-+ rectives or inter-transaction comments++ $ hledger print+ 2008/01/01 income+ assets:bank:checking $1+ income:salary $-1++ 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++ 2008/12/31 * pay off+ liabilities:debts $1+ assets:bank:checking $-1++ Normally, the journal entry's explicit or implicit amount style is pre-+ served. For example, when an amount is omitted in the journal, it will+ not appear in the output. Similarly, when a transaction price is im-+ plied but not written, it will not appear in the output. You can use+ the -x/--explicit flag to make all amounts and transaction prices ex-+ plicit, which can be useful for troubleshooting or for making your+ journal more readable and robust against data entry errors. -x is also+ implied by using any of -B,-V,-X,--value.++ Note, -x/--explicit will cause postings with a multi-commodity amount+ (these can arise when a multi-commodity transaction has an implicit+ amount) to be split into multiple single-commodity postings, keeping+ the output parseable.++ With -B/--cost, amounts with transaction prices are converted to cost+ using that price. This can be used for troubleshooting.++ With -m/--match and a STR argument, print will show at most one trans-+ action: the one one whose description is most similar to STR, and is+ most recent. STR should contain at least two characters. If there is+ no similar-enough match, no transaction will be shown.++ With --new, for each FILE being read, hledger reads (and writes) a spe-+ cial state file (.latest.FILE in the same directory), containing the+ latest transaction date(s) that were seen last time FILE was read.+ When this file is found, only transactions with newer dates (and new+ transactions on the latest date) are printed. This is useful for ig-+ noring already-seen entries in import data, such as downloaded CSV+ files. Eg:++ $ hledger -f bank1.csv print --new+ (shows transactions added since last print --new on this file)++ This assumes that transactions added to FILE always have same or in-+ creasing dates, and that transactions on the same day do not get re-+ ordered. See also the import command.++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, and (experimental)+ json and sql.++ Here's an example of print's CSV output:++ $ hledger print -Ocsv+ "txnidx","date","date2","status","code","description","comment","account","amount","commodity","credit","debit","posting-status","posting-comment"+ "1","2008/01/01","","","","income","","assets:bank:checking","1","$","","1","",""+ "1","2008/01/01","","","","income","","income:salary","-1","$","1","","",""+ "2","2008/06/01","","","","gift","","assets:bank:checking","1","$","","1","",""+ "2","2008/06/01","","","","gift","","income:gifts","-1","$","1","","",""+ "3","2008/06/02","","","","save","","assets:bank:saving","1","$","","1","",""+ "3","2008/06/02","","","","save","","assets:bank:checking","-1","$","1","","",""+ "4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","","1","",""+ "4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","","1","",""+ "4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","2","","",""+ "5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","","1","",""+ "5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","1","","",""++ o There is one CSV record per posting, with the parent transaction's+ fields repeated.++ o The "txnidx" (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.)++ o The amount is separated into "commodity" (the symbol) and "amount"+ (numeric quantity) fields.++ o The numeric amount is repeated in either the "credit" or "debit" col-+ umn, for convenience. (Those names are not accurate in the account-+ ing sense; it just puts negative amounts under credit and zero or+ greater amounts under debit.)++ print-unique+ print-unique+ Print transactions which do not reuse an already-seen description.++ Example:++ $ cat unique.journal+ 1/1 test+ (acct:one) 1+ 2/2 test+ (acct:two) 2+ $ LEDGER_FILE=unique.journal hledger print-unique+ (-f option not supported)+ 2015/01/01 test+ (acct:one) 1++ register+ register, reg, r+ Show postings and their running total.++ The register command displays matched postings, across all accounts, in+ date order, with their running total or running historical balance.+ (See also the aregister command, which shows matched transactions in a+ specific account.)++ register normally shows line per posting, but note that multi-commodity+ amounts will occupy multiple lines (one line per commodity).++ It is typically used with a query selecting a particular account, to+ see that account's activity:++ $ 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++ With --date2, it shows and sorts by secondary date instead.++ The --historical/-H 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:++ $ 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++ The --depth option limits the amount of sub-account detail displayed.++ The --average/-A 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 --empty (see below). It+ is affected by --historical. It works best when showing just one ac-+ count and one commodity.++ The --related/-r flag shows the other postings in the transactions of+ the postings which would normally be shown.++ The --invert flag negates all amounts. For example, it can be used on+ an income account where amounts are normally displayed as negative num-+ bers. It's also useful to show postings on the checking account to-+ gether with the related account:++ $ hledger register --related --invert assets:checking++ With a reporting interval, register shows summary postings, one per in-+ terval, aggregating the postings to each account:++ $ hledger register --monthly income+ 2008/01 income:salary $-1 $-1+ 2008/06 income:gifts $-1 $-2++ Periods with no activity, and summary postings with a zero amount, are+ not shown by default; use the --empty/-E flag to see them:++ $ 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++ Often, you'll want to see just one line per interval. The --depth op-+ tion helps with this, causing subaccounts to be aggregated:++ $ hledger register --monthly assets --depth 1h+ 2008/01 assets $1 $1+ 2008/06 assets $-1 0+ 2008/12 assets $-1 $-1++ Note when using report intervals, if you specify start/end dates these+ will be adjusted outward if necessary to contain a whole number of in-+ tervals. This ensures that the first and last intervals are full+ length and comparable to the others in the report.++ Custom register output+ register uses the full terminal width by default, except on windows.+ You can override this by setting the COLUMNS environment variable (not+ a bash shell variable) or by using the --width/-w option.++ The description and account columns normally share the space equally+ (about half of (width - 40) each). You can adjust this by adding a de-+ scription width as part of --width's argument, comma-separated: --width+ W,D . Here's a diagram (won't display correctly in --help):++ <--------------------------------- width (W) ---------------------------------->+ date (10) description (D) account (W-41-D) amount (12) balance (12)+ DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA++ and some examples:++ $ hledger reg # use terminal width (or 80 on windows)+ $ hledger reg -w 100 # use width 100+ $ COLUMNS=100 hledger reg # set with one-time environment variable+ $ export COLUMNS=100; hledger reg # set till session end (or window resize)+ $ hledger reg -w 100,40 # set overall width 100, description width 40+ $ hledger reg -w $COLUMNS,40 # use terminal width, & description width 40++ This command also supports the output destination and output format op-+ tions The output formats supported are txt, csv, and (experimental)+ json.++ register-match+ register-match+ Print the one posting whose transaction description is closest to DESC,+ in the style of the register command. If there are multiple equally+ good matches, it shows the most recent. Query options (options, not+ arguments) can be used to restrict the search space. Helps ledger-au-+ tosync detect already-seen transactions when importing.++ rewrite+ rewrite+ Print all transactions, rewriting the postings of matched transactions.+ For now the only rewrite available is adding new postings, like print+ --auto.++ 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 transac-+ tion's first posting amount.++ Examples:++ $ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'+ $ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'+ $ hledger-rewrite.hs -f rewrites.hledger++ rewrites.hledger may consist of entries like:++ = ^income 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++ Note the single quotes to protect the dollar sign from bash, and the+ two spaces between account and amount.++ More:++ $ hledger rewrite -- [QUERY] --add-posting "ACCT AMTEXPR" ...+ $ hledger rewrite -- ^income --add-posting '(liabilities:tax) *.33'+ $ hledger rewrite -- expenses:gifts --add-posting '(budget:gifts) *-1"'+ $ hledger rewrite -- ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'++ Argument for --add-posting option is a usual posting of transaction+ with an exception for amount specification. More precisely, you can+ use '*' (star symbol) before the amount to indicate that that this is a+ factor for an amount of original matched posting. If the amount in-+ cludes a commodity name, the new posting amount will be in the new com-+ modity; otherwise, it will be in the matched posting amount's commod-+ ity.++ Re-write rules in a file+ During the run this tool will execute so called "Automated Transac-+ tions" found in any journal it process. I.e instead of specifying this+ operations in command line you can put them in a journal file.++ $ rewrite-rules.journal++ Make contents look like this:++ = ^income+ (liabilities:tax) *.33++ = expenses:gifts+ budget:gifts *-1+ assets:budget *1++ Note that '=' (equality symbol) that is used instead of date in trans-+ actions you usually write. It indicates the query by which you want to+ match the posting to add new ones.++ $ hledger rewrite -- -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal++ This is something similar to the commands pipeline:++ $ hledger rewrite -- -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \+ | hledger rewrite -- -f - expenses:gifts --add-posting 'budget:gifts *-1' \+ --add-posting 'assets:budget *1' \+ > rewritten-tidy-output.journal++ It is important to understand that relative order of such entries in+ journal is important. You can re-use result of previously added post-+ ings.++ Diff output format+ To use this tool for batch modification of your journal files you may+ find useful output in form of unified diff.++ $ hledger rewrite -- --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'++ Output might look like:++ --- /tmp/examples/sample.journal+ +++ /tmp/examples/sample.journal+ @@ -18,3 +18,4 @@+ 2008/01/01 income+ - assets:bank:checking $1+ + assets:bank:checking $1+ income:salary+ + (liabilities:tax) 0+ @@ -22,3 +23,4 @@+ 2008/06/01 gift+ - assets:bank:checking $1+ + assets:bank:checking $1+ income:gifts+ + (liabilities:tax) 0++ If you'll pass this through patch tool you'll get transactions contain-+ ing the posting that matches your query be updated. Note that multiple+ files might be update according to list of input files specified via+ --file options and include directives inside of these files.++ Be careful. Whole transaction being re-formatted in a style of output+ from hledger print.++ See also:++ https://github.com/simonmichael/hledger/issues/99++ rewrite vs. print --auto+ This command predates print --auto, and currently does much the same+ thing, but with these differences:++ o with multiple files, rewrite lets rules in any file affect all other+ files. print --auto uses standard directive scoping; rules affect+ only child files.++ o rewrite's query limits which transactions can be rewritten; all are+ printed. print --auto's query limits which transactions are printed.++ o rewrite applies rules specified on command line or in the journal.+ print --auto applies rules specified in the journal.++ roi+ roi+ Shows the time-weighted (TWR) and money-weighted (IRR) rate of return+ on your investments.++ This command assumes that you have account(s) that hold nothing but+ your investments and whenever you record current appraisal/valuation of+ these investments you offset unrealized profit and loss into account(s)+ that, again, hold nothing but unrealized profit and loss.++ Any transactions affecting balance of investment account(s) and not+ originating from unrealized profit and loss account(s) are assumed to+ be your investments or withdrawals.++ At a minimum, you need to supply a query (which could be just an ac-+ count name) to select your investments with --inv, and another query to+ identify your profit and loss transactions with --pnl.++ This command will compute and display the internalized rate of return+ (IRR) and time-weighted rate of return (TWR) for your investments for+ the time period requested. Both rates of return are annualized before+ display, regardless of the length of reporting interval.++ Note, in some cases this report can fail, for these reasons:++ o Error (NotBracketed): No solution for Internal Rate of Return (IRR).+ Possible causes: IRR is huge (>1000000%), balance of investment be-+ comes negative at some point in time.++ o Error (SearchFailed): Failed to find solution for Internal Rate of+ Return (IRR). Either search does not converge to a solution, or con-+ verges too slowly.++ Examples:++ o Using roi to report unrealised gains: https://github.com/simon-+ michael/hledger/blob/master/examples/roi-unrealised.ledger++ More background:++ "ROI" stands for "return on investment". Traditionally this was com-+ puted as a difference between current value of investment and its ini-+ tial value, expressed in percentage of the initial value.++ However, this approach is only practical in simple cases, where invest-+ ments receives no in-flows or out-flows of money, and where rate of+ growth is fixed over time. For more complex scenarios you need differ-+ ent ways to compute rate of return, and this command implements two of+ them: IRR and TWR.++ Internal rate of return, or "IRR" (also called "money-weighted rate of+ return") takes into account effects of in-flows and out-flows.+ Naively, if you are withdrawing from your investment, your future gains+ would be smaller (in absolute numbers), and will be a smaller percent-+ age of your initial investment, and if you are adding to your invest-+ ment, you will receive bigger absolute gains (but probably at the same+ rate of return). IRR is a way to compute rate of return for each pe-+ riod between in-flow or out-flow of money, and then combine them in a+ way that gives you an annual rate of return that investment is expected+ to generate.++ As mentioned before, in-flows and out-flows would be any cash that you+ personally put in or withdraw, and for the "roi" command, these are+ transactions that involve account(s) matching --inv argument and NOT+ involve account(s) matching --pnl argument.++ Presumably, you will also record changes in the value of your invest-+ ment, and balance them against "profit and loss" (or "unrealized+ gains") account. Note that in order for IRR to compute the precise ef-+ fect of your in-flows and out-flows on the rate of return, you will+ need to record the value of your investement on or close to the days+ when in- or out-flows occur.++ Implementation of IRR in hledger should match the XIRR formula in Ex-+ cel.++ Second way to compute rate of return that roi command implements is+ called "time-weighted rate of return" or "TWR". Like IRR, it will also+ break the history of your investment into periods between in-flows and+ out-flows to compute rate of return per each period and then a compound+ rate of return. However, internal workings of TWR are quite different.++ In technical terms, IRR uses the same approach as computation of net+ present value, and tries to find a discount rate that makes net present+ value of all the cash flows of your investment to add up to zero. This+ could be hard to wrap your head around, especially if you haven't done+ discounted cash flow analysis before.++ TWR represents your investment as an imaginary "unit fund" where in-+ flows/ out-flows lead to buying or selling "units" of your investment+ and changes in its value change the value of "investment unit". Change+ in "unit price" over the reporting period gives you rate of return of+ your investment.++ References: * Explanation of rate of return * Explanation of IRR * Ex-+ planation of TWR * Examples of computing IRR and TWR and discussion of+ the limitations of both metrics++ More examples:++ Lets say that we found an investment in Snake Oil that is proising to+ give us 10% annually:++ 2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++ 2019-12-24 Recording the growth of Snake Oil+ investment:snake oil = $110+ equity:unrealized gains++ For now, basic computation of the rate of return, as well as IRR and+ TWR, gives us the expected 10%:++ $ hledger roi -Y --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+-----++--------+--------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+=====++========+========++ | 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 110 | 10 || 10.00% | 10.00% |+ +---++------------+------------++---------------+----------+-------------+-----++--------+--------+++ However, lets say that shorty after investing in the Snake Oil we+ started to have second thoughs, so we prompty withdrew $90, leaving+ only $10 in. Before Christmas, though, we started to get the "fear of+ mission out", so we put the $90 back in. So for most of the year, our+ investment was just $10 dollars, and it gave us just $1 in growth:++ 2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++ 2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil++ 2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++ 2019-12-31 Recording the growth of Snake Oil+ investment:snake oil = $101+ equity:unrealized gains++ Now IRR and TWR are drastically different:++ $ hledger roi -Y --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+-----++-------+-------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+=====++=======+=======++ | 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101 | 1 || 9.32% | 1.00% |+ +---++------------+------------++---------------+----------+-------------+-----++-------+-------+++ Here, IRR tells us that we made close to 10% on the $10 dollars that we+ had in the account most of the time. And TWR is ... just 1%? Why?++ Based on the transactions in our journal, TWR "think" that we are buy-+ ing back $90 worst of Snake Oil at the same price that it had at the+ beginning of they year, and then after that our $100 investment gets $1+ increase in value, or 1% of $100. Let's take a closer look at what is+ happening here by asking for quarterly reports instead of annual:++ $ hledger roi -Q --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+-----++--------+-------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+=====++========+=======++ | 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10 | 0 || 0.00% | 0.00% |+ | 2 || 2019-04-01 | 2019-06-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+ | 3 || 2019-07-01 | 2019-09-30 || 10 | 0 | 10 | 0 || 0.00% | 0.00% |+ | 4 || 2019-10-01 | 2019-12-31 || 10 | 90 | 101 | 1 || 37.80% | 4.03% |+ +---++------------+------------++---------------+----------+-------------+-----++--------+-------+++ Now both IRR and TWR are thrown off by the fact that all of the growth+ for our investment happens in Q4 2019. This happes because IRR compu-+ tation is still yielding 9.32% and TWR is still 1%, but this time these+ are rates for three month period instead of twelve, so in order to get+ an annual rate they should be multiplied by four!++ Let's try to keep a better record of how Snake Oil grew in value:++ 2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++ 2019-01-02 Buyers remorse+ assets:cash $90+ investment:snake oil++ 2019-02-28 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ 2019-06-30 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ 2019-09-30 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ 2019-12-30 Fear of missing out+ assets:cash -$90+ investment:snake oil++ 2019-12-31 Recording the growth of Snake Oil+ investment:snake oil+ equity:unrealized gains -$0.25++ Would our quartery report look better now? Almost:++ $ hledger roi -Q --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+------++--------+--------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+======++========+========++ | 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+ | 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+ | 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+ | 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 1.00% |+ +---++------------+------------++---------------+----------+-------------+------++--------+--------+++ Something is still wrong with TWR computation for Q4, and if you have+ been paying attention you know what it is already: big $90 buy-back is+ recorded prior to the only transaction that captures the change of+ value of Snake Oil that happened in this time period. Lets combine+ transactions from 30th and 31st of Dec into one:++ 2019-12-30 Fear of missing out and growth of Snake Oil+ assets:cash -$90+ investment:snake oil+ equity:unrealized gains -$0.25++ Now growth of investment properly affects its price at the time of buy-+ back:++ $ hledger roi -Q --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+------++--------+--------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+======++========+========++ | 1 || 2019-01-01 | 2019-03-31 || 0 | 10 | 10.25 | 0.25 || 9.53% | 10.53% |+ | 2 || 2019-04-01 | 2019-06-30 || 10.25 | 0 | 10.50 | 0.25 || 10.15% | 10.15% |+ | 3 || 2019-07-01 | 2019-09-30 || 10.50 | 0 | 10.75 | 0.25 || 9.79% | 9.78% |+ | 4 || 2019-10-01 | 2019-12-31 || 10.75 | 90 | 101.00 | 0.25 || 8.05% | 9.57% |+ +---++------------+------------++---------------+----------+-------------+------++--------+--------+++ And for annual report, TWR now reports the exact profitability of our+ investment:++ $ hledger roi -Y --inv investment --pnl "unrealized"+ +---++------------+------------++---------------+----------+-------------+------++-------+--------++ | || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR |+ +===++============+============++===============+==========+=============+======++=======+========++ | 1 || 2019-01-01 | 2019-12-31 || 0 | 100 | 101.00 | 1.00 || 9.32% | 10.00% |+ +---++------------+------------++---------------+----------+-------------+------++-------+--------+++ stats+ stats+ Show some journal statistics.++ The stats command displays summary information for the whole journal,+ or a matched part of it. With a reporting interval, it shows a report+ for each report period.++ Example:++ $ hledger stats+ Main journal file : /src/hledger/examples/sample.journal+ Included journal files :+ Transactions span : 2008-01-01 to 2009-01-01 (366 days)+ Last transaction : 2008-12-31 (2333 days ago)+ Transactions : 5 (0.0 per day)+ Transactions last 30 days: 0 (0.0 per day)+ Transactions last 7 days : 0 (0.0 per day)+ Payees/descriptions : 5+ Accounts : 8 (depth 3)+ Commodities : 1 ($)+ Market prices : 12 ($)++ This command also supports output destination and output format selec-+ tion.++ tags+ tags+ List the unique tag names used in the journal. With a TAGREGEX argu-+ ment, only tag names matching the regular expression (case insensitive)+ are shown. With QUERY arguments, only transactions matching the query+ are considered.++ With the --values flag, the tags' unique values are listed instead.++ With --parsed flag, all tags or values are shown in the order they are+ parsed from the input data, including duplicates.++ With -E/--empty, any blank/empty values will also be shown, otherwise+ they are omitted.++ test+ test+ Run built-in unit tests.++ This command runs the unit tests built in to hledger and hledger-lib,+ printing the results on stdout. If any test fails, the exit code will+ be non-zero.++ This is mainly used by hledger developers, but you can also use it to+ sanity-check the installed hledger executable on your platform. All+ tests are expected to pass - if you ever see a failure, please report+ as a bug!++ This command also accepts tasty test runner options, written after a --+ (double hyphen). Eg to run only the tests in Hledger.Data.Amount, with+ ANSI colour codes disabled:++ $ hledger test -- -pData.Amount --color=never++ For help on these, see https://github.com/feuerbach/tasty#options (--+ --help currently doesn't show them).++ Add-on commands+ hledger also searches for external add-on commands, and will include+ these in the commands list. These are programs or scripts in your PATH+ whose name starts with hledger- and ends with a recognised file exten-+ sion (currently: no extension, bat,com,exe, hs,lhs,pl,py,rb,rkt,sh).++ Add-ons can be invoked like any hledger command, but there are a few+ things to be aware of. Eg if the hledger-web add-on is installed,++ o hledger -h web shows hledger's help, while hledger web -h shows+ hledger-web's help.++ o Flags specific to the add-on must have a preceding -- to hide them+ from hledger. So hledger web --serve --port 9000 will be rejected;+ you must use hledger web -- --serve --port 9000.++ o You can always run add-ons directly if preferred: hledger-web --serve+ --port 9000.++ Add-ons are a relatively easy way to add local features or experiment+ with new ideas. They can be written in any language, but haskell+ scripts have a big advantage: they can use the same hledger (and+ haskell) library functions that built-in commands do, for command-line+ options, journal parsing, reporting, etc.++ Two important add-ons are the hledger-ui and hledger-web user inter-+ faces. These are maintained and released along with hledger:++ ui+ hledger-ui provides an efficient terminal interface.++ web+ hledger-web provides a simple web interface.++ Third party add-ons, maintained separately from hledger, include:++ iadd+ hledger-iadd is a more interactive, terminal UI replacement for the add+ command.++ interest+ hledger-interest generates interest transactions for an account accord-+ ing to various schemes.++ A few more experimental or old add-ons can be found in hledger's bin/+ directory. These are typically prototypes and not guaranteed to work.++ENVIRONMENT+ LEDGER_FILE The journal file path when not specified with -f. Default:+ ~/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.jour-+ nal).++ A typical value is ~/DIR/YYYY.journal, where DIR is a version-con-+ trolled finance directory and YYYY is the current year. Or ~/DIR/cur-+ rent.journal, where current.journal is a symbolic link to YYYY.journal.++ On Mac computers, you can set this and other environment variables in a+ more thorough way that also affects applications started from the GUI+ (say, an Emacs dock icon). Eg on MacOS Catalina I have a ~/.MacOSX/en-+ vironment.plist file containing++ {+ "LEDGER_FILE" : "~/finance/current.journal"+ }++ To see the effect you may need to killall Dock, or reboot.++ COLUMNS The screen width used by the register command. Default: the+ full terminal width.++ NO_COLOR If this variable exists with any value, hledger will not use+ ANSI color codes in terminal output. This overrides the+ --color/--colour option.++FILES+ Reads data from one or more files in hledger journal, timeclock, time-+ dot, or CSV format specified with -f, or $LEDGER_FILE, or+ $HOME/.hledger.journal (on windows, perhaps+ C:/Users/USER/.hledger.journal).++LIMITATIONS+ The need to precede addon command options with -- when invoked from+ hledger is awkward.++ When input data contains non-ascii characters, a suitable system locale+ must be configured (or there will be an unhelpful error). Eg on POSIX,+ set LANG to something other than C.++ In a Microsoft Windows CMD window, non-ascii characters and colours are+ not supported.++ On Windows, non-ascii characters may not display correctly when running+ a hledger built in CMD in MSYS/CYGWIN, or vice-versa.++ In a Cygwin/MSYS/Mintty window, the tab key is not supported in hledger+ add.++ Not all of Ledger's journal file syntax is supported. See file format+ differences.++ On large data files, hledger is slower and uses more memory than+ Ledger.++TROUBLESHOOTING+ Here are some issues you might encounter when you run hledger (and re-+ member you can also seek help from the IRC channel, mail list or bug+ tracker):++ Successfully installed, but "No command 'hledger' found"+ stack and cabal install binaries into a special directory, which should+ be added to your PATH environment variable. Eg on unix-like systems,+ that is ~/.local/bin and ~/.cabal/bin respectively.++ I set a custom LEDGER_FILE, but hledger is still using the default file+ LEDGER_FILE should be a real environment variable, not just a shell+ variable. The command env | grep LEDGER_FILE should show it. You may+ need to use export. Here's an explanation.++ Getting errors like "Illegal byte sequence" or "Invalid or incomplete+ multibyte or wide character" or "commitAndReleaseBuffer: invalid argu-+ ment (invalid character)"+ Programs compiled with GHC (hledger, haskell build tools, etc.) need to+ have a UTF-8-aware locale configured in the environment, otherwise they+ will fail with these kinds of errors when they encounter non-ascii+ characters.++ To fix it, set the LANG environment variable to some locale which sup-+ ports UTF-8. The locale you choose must be installed on your system.++ Here's an example of setting LANG temporarily, on Ubuntu GNU/Linux:++ $ file my.journal+ my.journal: UTF-8 Unicode text # the file is UTF8-encoded+ $ echo $LANG+ C # LANG is set to the default locale, which does not support UTF8+ $ locale -a # which locales are installed ?+ C+ en_US.utf8 # here's a UTF8-aware one we can use+ POSIX+ $ LANG=en_US.utf8 hledger -f my.journal print # ensure it is used for this command++ If available, C.UTF-8 will also work. If your preferred locale isn't+ listed by locale -a, you might need to install it. Eg on Ubuntu/De-+ bian:++ $ apt-get install language-pack-fr+ $ locale -a+ C+ en_US.utf8+ fr_BE.utf8+ fr_CA.utf8+ fr_CH.utf8+ fr_FR.utf8+ fr_LU.utf8+ POSIX+ $ LANG=fr_FR.utf8 hledger -f my.journal print++ Here's how you could set it permanently, if you use a bash shell:++ $ echo "export LANG=en_US.utf8" >>~/.bash_profile+ $ bash --login++ Exact spelling and capitalisation may be important. Note the differ-+ ence on MacOS (UTF-8, not utf8). Some platforms (eg ubuntu) allow+ variant spellings, but others (eg macos) require it to be exact:++ $ locale -a | grep -iE en_us.*utf+ en_US.UTF-8+ $ LANG=en_US.UTF-8 hledger -f my.journal print++++REPORTING BUGS+ Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel+ or hledger mail list)+++AUTHORS+ Simon Michael <simon@joyful.com> and contributors+++COPYRIGHT+ Copyright (C) 2007-2019 Simon Michael.+ Released under GNU GPL v3 or later.+++SEE ALSO+ hledger(1), hledger-ui(1), hledger-web(1), hledger-api(1),+ hledger_csv(5), hledger_journal(5), hledger_timeclock(5), hledger_time-+ dot(5), ledger(1)++ http://hledger.org++++hledger 1.20 November 2020 hledger(1)