{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ParallelListComp  #-}
{-# LANGUAGE TemplateHaskell   #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE ViewPatterns #-}
{-|

The @roi@ command prints internal rate of return and time-weighted rate of return for an investment.

-}

module Hledger.Cli.Commands.Roi (
  roimode
  , roi
) where

import Control.Monad
import Data.Time.Calendar
import Text.Printf
import Data.Bifunctor (second)
import Data.List
import Data.Maybe (fromMaybe)
import Data.Decimal
import Data.Map qualified as M
import Data.Set qualified as S
import Data.Text qualified as T
import Data.Text.Lazy qualified as TL
import System.Console.CmdArgs.Explicit as CmdArgs
import System.IO (hFlush, stdout)

import Text.Tabular.AsciiWide as Tab

import Hledger
import Hledger.Cli.CliOptions
import Hledger.Cli.Utils (warnIfLargeMultiPeriodReport, withTitle, writeOutput)
import Hledger.Cli.Xirr


roimode :: Mode RawOpts
roimode = [Char]
-> [Flag RawOpts]
-> [([Char], [Flag RawOpts])]
-> [Flag RawOpts]
-> ([Arg RawOpts], Maybe (Arg RawOpts))
-> Mode RawOpts
hledgerCommandMode
  $(embedFileRelative "Hledger/Cli/Commands/Roi.txt")
  [[[Char]] -> (RawOpts -> RawOpts) -> [Char] -> Flag RawOpts
forall a. [[Char]] -> (a -> a) -> [Char] -> Flag a
flagNone [[Char]
"cashflow"] ([Char] -> RawOpts -> RawOpts
setboolopt [Char]
"cashflow") [Char]
"show all amounts that were used to compute returns"
  ,[[Char]] -> Update RawOpts -> [Char] -> [Char] -> Flag RawOpts
forall a. [[Char]] -> Update a -> [Char] -> [Char] -> Flag a
flagReq [[Char]
"investment"] (\[Char]
s RawOpts
opts -> RawOpts -> Either [Char] RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either [Char] RawOpts)
-> RawOpts -> Either [Char] RawOpts
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> RawOpts -> RawOpts
setopt [Char]
"investment" [Char]
s RawOpts
opts) [Char]
"QUERY"
    [Char]
"query to select your investment transactions"
  ,[[Char]] -> Update RawOpts -> [Char] -> [Char] -> Flag RawOpts
forall a. [[Char]] -> Update a -> [Char] -> [Char] -> Flag a
flagReq [[Char]
"profit-loss",[Char]
"pnl"] (\[Char]
s RawOpts
opts -> RawOpts -> Either [Char] RawOpts
forall a b. b -> Either a b
Right (RawOpts -> Either [Char] RawOpts)
-> RawOpts -> Either [Char] RawOpts
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> RawOpts -> RawOpts
setopt [Char]
"pnl" [Char]
s RawOpts
opts) [Char]
"QUERY"
    [Char]
"query to select profit-and-loss or appreciation/valuation transactions (optional)"
  ]
  [([Char], [Flag RawOpts])]
cligeneralflagsgroups1
  [Flag RawOpts]
hiddenflags
  ([], Arg RawOpts -> Maybe (Arg RawOpts)
forall a. a -> Maybe a
Just (Arg RawOpts -> Maybe (Arg RawOpts))
-> Arg RawOpts -> Maybe (Arg RawOpts)
forall a b. (a -> b) -> a -> b
$ [Char] -> Arg RawOpts
argsFlag [Char]
"[QUERY]")

-- One reporting span,
data OneSpan = OneSpan
  Day -- start date, inclusive
  Day   -- end date, exclusive
  MixedAmount -- value of investment at the beginning of day on spanBegin_
  MixedAmount -- value of investment at the end of day on spanEnd_
  [(Day,MixedAmount)] -- all deposits and withdrawals (but not changes of value) in the DateSpan [spanBegin_,spanEnd_)
  [(Day,MixedAmount)] -- all PnL changes of the value of investment in the DateSpan [spanBegin_,spanEnd_)
 deriving (Int -> OneSpan -> [Char] -> [Char]
[OneSpan] -> [Char] -> [Char]
OneSpan -> [Char]
(Int -> OneSpan -> [Char] -> [Char])
-> (OneSpan -> [Char])
-> ([OneSpan] -> [Char] -> [Char])
-> Show OneSpan
forall a.
(Int -> a -> [Char] -> [Char])
-> (a -> [Char]) -> ([a] -> [Char] -> [Char]) -> Show a
$cshowsPrec :: Int -> OneSpan -> [Char] -> [Char]
showsPrec :: Int -> OneSpan -> [Char] -> [Char]
$cshow :: OneSpan -> [Char]
show :: OneSpan -> [Char]
$cshowList :: [OneSpan] -> [Char] -> [Char]
showList :: [OneSpan] -> [Char] -> [Char]
Show)

roi ::  CliOpts -> Journal -> IO ()
roi :: CliOpts -> Journal -> IO ()
roi opts :: CliOpts
opts@CliOpts{rawopts_ :: CliOpts -> RawOpts
rawopts_=RawOpts
rawopts, reportspec_ :: CliOpts -> ReportSpec
reportspec_=rspec :: ReportSpec
rspec@ReportSpec{_rsReportOpts :: ReportSpec -> ReportOpts
_rsReportOpts=ropts :: ReportOpts
ropts@ReportOpts{Bool
Int
[CommoditySymbol]
[Status]
SortSpec
Maybe Int
Maybe CommoditySymbol
Maybe NormalSign
Maybe ConversionOp
Maybe ValuationType
Interval
Period
DepthSpec
AccountListMode
BalanceAccumulation
BalanceCalculation
Layout
PeriodTitles
Translations
StringFormat
period_ :: Period
interval_ :: Interval
statuses_ :: [Status]
conversionop_ :: Maybe ConversionOp
value_ :: Maybe ValuationType
infer_prices_ :: Bool
depth_ :: DepthSpec
fold_depth_ :: Maybe Int
no_elide_ :: Bool
date2_ :: Bool
empty_ :: Bool
full_names_ :: Bool
real_ :: Bool
format_ :: StringFormat
balance_base_url_ :: Maybe CommoditySymbol
pretty_ :: Bool
querystring_ :: [CommoditySymbol]
average_ :: Bool
related_ :: Bool
sortspec_ :: SortSpec
txn_dates_ :: Bool
balancecalc_ :: BalanceCalculation
balanceaccum_ :: BalanceAccumulation
budgetpat_ :: Maybe CommoditySymbol
accountlistmode_ :: AccountListMode
drop_ :: Int
declared_ :: Bool
row_total_ :: Bool
no_total_ :: Bool
summary_only_ :: Bool
show_costs_ :: Bool
sort_amount_ :: Bool
percent_ :: Bool
invert_ :: Bool
normalbalance_ :: Maybe NormalSign
color_ :: Bool
transpose_ :: Bool
layout_ :: Layout
period_titles_ :: PeriodTitles
title_ :: Maybe CommoditySymbol
subreport_titles_ :: Maybe CommoditySymbol
translations_ :: Translations
accountlistmode_ :: ReportOpts -> AccountListMode
average_ :: ReportOpts -> Bool
balance_base_url_ :: ReportOpts -> Maybe CommoditySymbol
balanceaccum_ :: ReportOpts -> BalanceAccumulation
balancecalc_ :: ReportOpts -> BalanceCalculation
budgetpat_ :: ReportOpts -> Maybe CommoditySymbol
color_ :: ReportOpts -> Bool
conversionop_ :: ReportOpts -> Maybe ConversionOp
date2_ :: ReportOpts -> Bool
declared_ :: ReportOpts -> Bool
depth_ :: ReportOpts -> DepthSpec
drop_ :: ReportOpts -> Int
empty_ :: ReportOpts -> Bool
fold_depth_ :: ReportOpts -> Maybe Int
format_ :: ReportOpts -> StringFormat
full_names_ :: ReportOpts -> Bool
infer_prices_ :: ReportOpts -> Bool
interval_ :: ReportOpts -> Interval
invert_ :: ReportOpts -> Bool
layout_ :: ReportOpts -> Layout
no_elide_ :: ReportOpts -> Bool
no_total_ :: ReportOpts -> Bool
normalbalance_ :: ReportOpts -> Maybe NormalSign
percent_ :: ReportOpts -> Bool
period_ :: ReportOpts -> Period
period_titles_ :: ReportOpts -> PeriodTitles
pretty_ :: ReportOpts -> Bool
querystring_ :: ReportOpts -> [CommoditySymbol]
real_ :: ReportOpts -> Bool
related_ :: ReportOpts -> Bool
row_total_ :: ReportOpts -> Bool
show_costs_ :: ReportOpts -> Bool
sort_amount_ :: ReportOpts -> Bool
sortspec_ :: ReportOpts -> SortSpec
statuses_ :: ReportOpts -> [Status]
subreport_titles_ :: ReportOpts -> Maybe CommoditySymbol
summary_only_ :: ReportOpts -> Bool
title_ :: ReportOpts -> Maybe CommoditySymbol
translations_ :: ReportOpts -> Translations
transpose_ :: ReportOpts -> Bool
txn_dates_ :: ReportOpts -> Bool
value_ :: ReportOpts -> Maybe ValuationType
..}}} Journal
j = do
  ReportSpec -> Journal -> IO ()
warnIfLargeMultiPeriodReport ReportSpec
rspec Journal
j
  -- We may be converting posting amounts to value, per hledger_options.m4.md "Effect of --value on reports".
  let
    -- lbl = lbl_ "roi"
    today :: Day
today = ReportSpec -> Day
_rsDay ReportSpec
rspec
    priceOracle :: PriceOracle
priceOracle = Bool -> Journal -> PriceOracle
journalPriceOracle Bool
infer_prices_ Journal
j
    styles :: Map CommoditySymbol AmountStyle
styles = Rounding -> Journal -> Map CommoditySymbol AmountStyle
journalCommodityStylesWith Rounding
HardRounding Journal
j
    mixedAmountValue :: Day -> Day -> MixedAmount -> MixedAmount
mixedAmountValue Day
periodlast Day
date =
        -- These calculations can generate very precise decimals. To avoid showing too many digits:
        -- If we have no style for the valuation commodity, generate one that will limit the precision ?
        -- But it's not easy to find out the valuation commodity (or commodities) here if it's implicit,
        -- as that information is buried in the price graph.
        -- Instead, do what we don't like to do: hard code a max precision, overriding commodity styles.
        Word8 -> MixedAmount -> MixedAmount
mixedAmountSetPrecisionMax Word8
defaultMaxDisplayPrecision
      (MixedAmount -> MixedAmount)
-> (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (MixedAmount -> MixedAmount)
-> (ValuationType -> MixedAmount -> MixedAmount)
-> Maybe ValuationType
-> MixedAmount
-> MixedAmount
forall b a. b -> (a -> b) -> Maybe a -> b
maybe MixedAmount -> MixedAmount
forall a. a -> a
id (PriceOracle
-> Map CommoditySymbol AmountStyle
-> Day
-> Day
-> Day
-> ValuationType
-> MixedAmount
-> MixedAmount
mixedAmountApplyValuation PriceOracle
priceOracle Map CommoditySymbol AmountStyle
styles Day
periodlast Day
today Day
date) Maybe ValuationType
value_
      (MixedAmount -> MixedAmount)
-> (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (MixedAmount -> MixedAmount)
-> (ConversionOp -> MixedAmount -> MixedAmount)
-> Maybe ConversionOp
-> MixedAmount
-> MixedAmount
forall b a. b -> (a -> b) -> Maybe a -> b
maybe MixedAmount -> MixedAmount
forall a. a -> a
id (Map CommoditySymbol AmountStyle
-> ConversionOp -> MixedAmount -> MixedAmount
mixedAmountToCost Map CommoditySymbol AmountStyle
styles) Maybe ConversionOp
conversionop_

  let
    wd :: WhichDate
wd = ReportOpts -> WhichDate
whichDate ReportOpts
ropts
    showCashFlow :: Bool
showCashFlow = [Char] -> RawOpts -> Bool
boolopt [Char]
"cashflow" RawOpts
rawopts
    prettyTables :: Bool
prettyTables = Bool
pretty_
    makeQuery :: [Char] -> m Query
makeQuery [Char]
flag = do
        q <- ([Char] -> m Query)
-> ((Query, [QueryOpt]) -> m Query)
-> Either [Char] (Query, [QueryOpt])
-> m Query
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [Char] -> m Query
forall a. [Char] -> a
usageError (Query -> m Query
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return (Query -> m Query)
-> ((Query, [QueryOpt]) -> Query) -> (Query, [QueryOpt]) -> m Query
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Query, [QueryOpt]) -> Query
forall a b. (a, b) -> a
fst) (Either [Char] (Query, [QueryOpt]) -> m Query)
-> ([Char] -> Either [Char] (Query, [QueryOpt]))
-> [Char]
-> m Query
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Day -> CommoditySymbol -> Either [Char] (Query, [QueryOpt])
parseQuery Day
today (CommoditySymbol -> Either [Char] (Query, [QueryOpt]))
-> ([Char] -> CommoditySymbol)
-> [Char]
-> Either [Char] (Query, [QueryOpt])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> CommoditySymbol
T.pack ([Char] -> m Query) -> [Char] -> m Query
forall a b. (a -> b) -> a -> b
$ [Char] -> RawOpts -> [Char]
stringopt [Char]
flag RawOpts
rawopts
        return . simplifyQuery $ And [queryFromFlags ropts{period_=PeriodAll}, q]
    cantCompute :: [Char] -> b
cantCompute [Char]
msg = [Char] -> b
forall a. [Char] -> a
error' ([Char] -> b) -> [Char] -> b
forall a b. (a -> b) -> a -> b
$ [Char]
msg [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" - will be unable to compute the rates of return"

  investmentsQuery <- [Char] -> IO Query
forall {m :: * -> *}. Monad m => [Char] -> m Query
makeQuery [Char]
"investment"
  pnlQuery         <- case maybestringopt "pnl" rawopts of
                         Maybe [Char]
Nothing -> Query -> IO Query
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Query
None
                         Just [Char]
_  -> [Char] -> IO Query
forall {m :: * -> *}. Monad m => [Char] -> m Query
makeQuery [Char]
"pnl"

  when (pnlQuery == Any) $
    cantCompute "Need some transactions classed as investment and not pnl, but the pnl query matches any transaction"

  let
    filteredj = Query -> Journal -> Journal
filterJournalTransactions Query
investmentsQuery Journal
j
    trans = [Char] -> [Transaction] -> [Transaction]
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"investments" ([Transaction] -> [Transaction]) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> a -> b
$ Journal -> [Transaction]
jtxns Journal
filteredj

    postingDay   = WhichDate -> Posting -> Day
postingDateOrDate2 WhichDate
wd
    isInvestment = Query -> Posting -> Bool
matchesPosting Query
investmentsQuery
    isPnl Posting
p      = Bool -> Bool
not (Posting -> Bool
isInvestment Posting
p) Bool -> Bool -> Bool
&& Query -> Posting -> Bool
matchesPosting Query
pnlQuery Posting
p

    -- The investment's holdings at the end of each day which changes them, accumulated once.
    -- With -B, each posting is converted to cost before summing, since summing can merge
    -- amounts with different cost bases (eg lots), losing them.
    holdingsByDay = [(Day, MixedAmount)] -> Map Day MixedAmount
forall k a. Eq k => [(k, a)] -> Map k a
M.fromAscList ([(Day, MixedAmount)] -> Map Day MixedAmount)
-> (Map Day MixedAmount -> [(Day, MixedAmount)])
-> Map Day MixedAmount
-> Map Day MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a. Int -> [a] -> [a]
drop Int
1 ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> (Map Day MixedAmount -> [(Day, MixedAmount)])
-> Map Day MixedAmount
-> [(Day, MixedAmount)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Day, MixedAmount) -> (Day, MixedAmount) -> (Day, MixedAmount))
-> (Day, MixedAmount)
-> [(Day, MixedAmount)]
-> [(Day, MixedAmount)]
forall b a. (b -> a -> b) -> b -> [a] -> [b]
scanl (\(Day
_, MixedAmount
acc) (Day
d, MixedAmount
a) -> (Day
d, MixedAmount
acc MixedAmount -> MixedAmount -> MixedAmount
`maPlus` MixedAmount
a)) (Day
nulldate, MixedAmount
nullmixedamt) ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> (Map Day MixedAmount -> [(Day, MixedAmount)])
-> Map Day MixedAmount
-> [(Day, MixedAmount)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Day MixedAmount -> [(Day, MixedAmount)]
forall k a. Map k a -> [(k, a)]
M.toAscList (Map Day MixedAmount -> Map Day MixedAmount)
-> Map Day MixedAmount -> Map Day MixedAmount
forall a b. (a -> b) -> a -> b
$
      (MixedAmount -> MixedAmount -> MixedAmount)
-> [(Day, MixedAmount)] -> Map Day MixedAmount
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith MixedAmount -> MixedAmount -> MixedAmount
maPlus [ (Posting -> Day
postingDay Posting
p, (MixedAmount -> MixedAmount)
-> (ConversionOp -> MixedAmount -> MixedAmount)
-> Maybe ConversionOp
-> MixedAmount
-> MixedAmount
forall b a. b -> (a -> b) -> Maybe a -> b
maybe MixedAmount -> MixedAmount
forall a. a -> a
id (Map CommoditySymbol AmountStyle
-> ConversionOp -> MixedAmount -> MixedAmount
mixedAmountToCost Map CommoditySymbol AmountStyle
styles) Maybe ConversionOp
conversionop_ (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p)
                            | Transaction
t <- [Transaction]
trans, Posting
p <- Transaction -> [Posting]
realPostings Transaction
t, Posting -> Bool
isInvestment Posting
p ]
    -- the investment's holdings at the end of this day
    holdingsAt Day
d = MixedAmount
-> ((Day, MixedAmount) -> MixedAmount)
-> Maybe (Day, MixedAmount)
-> MixedAmount
forall b a. b -> (a -> b) -> Maybe a -> b
maybe MixedAmount
nullmixedamt (Day, MixedAmount) -> MixedAmount
forall a b. (a, b) -> b
snd (Maybe (Day, MixedAmount) -> MixedAmount)
-> Maybe (Day, MixedAmount) -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Day -> Map Day MixedAmount -> Maybe (Day, MixedAmount)
forall k v. Ord k => k -> Map k v -> Maybe (k, v)
M.lookupLE Day
d Map Day MixedAmount
holdingsByDay

    -- The unit prices of the investment's own purchases and sales, by commodity and date (the last one recorded on a
    -- date wins, as with --infer-market-prices), for valuing holdings which have no market price.
    -- (fromListWith passes the later entry first, and union keeps its first argument's entries.)
    tradePrices = (Map Day Amount -> Map Day Amount -> Map Day Amount)
-> [(CommoditySymbol, Map Day Amount)]
-> Map CommoditySymbol (Map Day Amount)
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Map Day Amount -> Map Day Amount -> Map Day Amount
forall k a. Ord k => Map k a -> Map k a -> Map k a
M.union
      [ (PriceDirective -> CommoditySymbol
pdcommodity PriceDirective
pd, Day -> Amount -> Map Day Amount
forall k a. k -> a -> Map k a
M.singleton (Posting -> Day
postingDay Posting
p) (PriceDirective -> Amount
pdamount PriceDirective
pd))
      | Transaction
t <- [Transaction]
trans, Posting
p <- Transaction -> [Posting]
realPostings Transaction
t, Posting -> Bool
isInvestment Posting
p, Amount
a <- MixedAmount -> [Amount]
amounts (Posting -> MixedAmount
pamount Posting
p)
      , Just PriceDirective
pd <- [Day -> Amount -> Maybe PriceDirective
amountPriceDirectiveFromCost (Posting -> Day
postingDay Posting
p) Amount
a] ]
    -- the price of the investment's latest purchase or sale of this commodity, on or before this date
    latestTradePrice CommoditySymbol
c Day
d = CommoditySymbol
-> Map CommoditySymbol (Map Day Amount) -> Maybe (Map Day Amount)
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup CommoditySymbol
c Map CommoditySymbol (Map Day Amount)
tradePrices Maybe (Map Day Amount)
-> (Map Day Amount -> Maybe Amount) -> Maybe Amount
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ((Day, Amount) -> Amount) -> Maybe (Day, Amount) -> Maybe Amount
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Day, Amount) -> Amount
forall a b. (a, b) -> b
snd (Maybe (Day, Amount) -> Maybe Amount)
-> (Map Day Amount -> Maybe (Day, Amount))
-> Map Day Amount
-> Maybe Amount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Day -> Map Day Amount -> Maybe (Day, Amount)
forall k v. Ord k => k -> Map k v -> Maybe (k, v)
M.lookupLE Day
d

    -- The investment's cash flows from b to lastDay, measured from its own side: for each transaction and each date of
    -- its investment postings, the cost of those postings, less the transaction's profit and loss (counted on the first
    -- of those dates), valued with valueOn. So other postings in the same transaction (eg fees, or gains and losses on
    -- other holdings) don't count, and flows are dated like the changes they make to the investment.
    -- Deposits are negative and withdrawals positive, like the postings of the money that pays for them.
    investmentCashFlows Day -> MixedAmount -> MixedAmount
valueOn Day
b Day
lastDay =
      [ Day
-> CommoditySymbol
-> MixedAmount
-> MixedAmount
-> MixedAmount
-> InvestmentFlow
InvestmentFlow Day
d (Transaction -> CommoditySymbol
tdescription Transaction
t) MixedAmount
cost MixedAmount
gain (MixedAmount -> MixedAmount
maNegate (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ MixedAmount
cost MixedAmount -> MixedAmount -> MixedAmount
`maMinus` MixedAmount
gain)
      | Transaction
t <- [Transaction]
trans
      , let ps :: [Posting]
ps     = Transaction -> [Posting]
realPostings Transaction
t
            byDay :: Map Day [Posting]
byDay  = ([Posting] -> [Posting] -> [Posting])
-> [(Day, [Posting])] -> Map Day [Posting]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith (([Posting] -> [Posting] -> [Posting])
-> [Posting] -> [Posting] -> [Posting]
forall a b c. (a -> b -> c) -> b -> a -> c
flip [Posting] -> [Posting] -> [Posting]
forall a. [a] -> [a] -> [a]
(++)) [ (Posting -> Day
postingDay Posting
p, [Posting
p]) | Posting
p <- [Posting]
ps, Posting -> Bool
isInvestment Posting
p ]
            pnlAmt :: MixedAmount
pnlAmt = [Posting] -> MixedAmount
sumPostings ((Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter Posting -> Bool
isPnl [Posting]
ps)
      , (Int
i, (Day
d, [Posting]
invps)) <- [Int] -> [(Day, [Posting])] -> [(Int, (Day, [Posting]))]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] (Map Day [Posting] -> [(Day, [Posting])]
forall k a. Map k a -> [(k, a)]
M.toAscList Map Day [Posting]
byDay)
      , Day
d Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
>= Day
b, Day
d Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
<= Day
lastDay
      , let cost :: MixedAmount
cost = Day -> MixedAmount -> MixedAmount
valueOn Day
d (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle
-> ConversionOp -> MixedAmount -> MixedAmount
mixedAmountToCost Map CommoditySymbol AmountStyle
styles ConversionOp
ToCost (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ [Posting] -> MixedAmount
sumPostings [Posting]
invps
            gain :: MixedAmount
gain = if Int
i Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 then MixedAmount -> MixedAmount
maNegate (Day -> MixedAmount -> MixedAmount
valueOn Day
d MixedAmount
pnlAmt) else MixedAmount
nullmixedamt
      , MixedAmount -> Bool
maIsNonZero (MixedAmount
cost MixedAmount -> MixedAmount -> MixedAmount
`maMinus` MixedAmount
gain) ]

  when (null trans) $
    error' "No relevant transactions found. Check your investments query"

  let (fullPeriodDateSpan, mspans) = reportSpan filteredj rspec

  let err = [Char] -> b
forall a. [Char] -> a
cantCompute [Char]
"Undefined start or end of the period"
      spans = [(Day, Day)]
-> (DayPartition -> [(Day, Day)])
-> Maybe DayPartition
-> [(Day, Day)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [(Day, Day)]
forall {b}. b
err (((Day, Day) -> (Day, Day)) -> [(Day, Day)] -> [(Day, Day)]
forall a b. (a -> b) -> [a] -> [b]
map ((Day -> Day) -> (Day, Day) -> (Day, Day)
forall b c a. (b -> c) -> (a, b) -> (a, c)
forall (p :: * -> * -> *) b c a.
Bifunctor p =>
(b -> c) -> p a b -> p a c
second (Integer -> Day -> Day
addDays Integer
1)) ([(Day, Day)] -> [(Day, Day)])
-> (DayPartition -> [(Day, Day)]) -> DayPartition -> [(Day, Day)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DayPartition -> [(Day, Day)]
dayPartitionToList) Maybe DayPartition
mspans
      fullPeriod = case DateSpan
fullPeriodDateSpan of
        DateSpan (Just EFDay
b) (Just EFDay
e) -> (EFDay -> Day
fromEFDay EFDay
b, EFDay -> Day
fromEFDay EFDay
e)
        DateSpan
_ -> (Day, Day)
forall {b}. b
err

  let processSpan (Day
b, Day
e) = do
        -- Spans are [begin,end), and end is 1 day after the actual end date we are interested in
        let
          -- the last day of the span, which --value=end and the value at the end of the span are valued on
          lastDay :: Day
lastDay = Integer -> Day -> Day
addDays (-Integer
1) Day
e

          cashFlowApplyCostValue :: [(Day, MixedAmount)] -> [(Day, MixedAmount)]
cashFlowApplyCostValue = ((Day, MixedAmount) -> (Day, MixedAmount))
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a b. (a -> b) -> [a] -> [b]
map (\(Day
d,MixedAmount
amt) -> (Day
d,Day -> Day -> MixedAmount -> MixedAmount
mixedAmountValue Day
lastDay Day
d MixedAmount
amt))

          -- With valuation, the investment's value should end up in the same commodity as the cash flows and PnL, which
          -- are valued the same way (that need not be the one given to --value, if nothing converts to it).
          -- Without cash flows or PnL, it should be in the one given to --value.
          expectedCommodity :: Maybe CommoditySymbol
expectedCommodity = case Maybe ValuationType
value_ of
            Maybe ValuationType
Nothing -> Maybe CommoditySymbol
forall a. Maybe a
Nothing
            Just ValuationType
vt -> case Set CommoditySymbol -> [CommoditySymbol]
forall a. Set a -> [a]
S.toList ([Set CommoditySymbol] -> Set CommoditySymbol
forall (f :: * -> *) a. (Foldable f, Ord a) => f (Set a) -> Set a
S.unions ([Set CommoditySymbol] -> Set CommoditySymbol)
-> [Set CommoditySymbol] -> Set CommoditySymbol
forall a b. (a -> b) -> a -> b
$ ((Day, MixedAmount) -> Set CommoditySymbol)
-> [(Day, MixedAmount)] -> [Set CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (MixedAmount -> Set CommoditySymbol
maCommodities (MixedAmount -> Set CommoditySymbol)
-> ((Day, MixedAmount) -> MixedAmount)
-> (Day, MixedAmount)
-> Set CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Day, MixedAmount) -> MixedAmount
forall a b. (a, b) -> b
snd) ([(Day, MixedAmount)]
otherFlows [(Day, MixedAmount)]
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a. [a] -> [a] -> [a]
++ [(Day, MixedAmount)]
pnl)) of
              [CommoditySymbol
c] -> CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just CommoditySymbol
c
              []  -> ValuationType -> Maybe CommoditySymbol
valuationTypeValuationCommodity ValuationType
vt
              [CommoditySymbol]
_   -> Maybe CommoditySymbol
forall a. Maybe a
Nothing
          -- Value an amount of the investment on a date. Positions fully closed by then are dropped first. A commodity
          -- with no market price known on or before that date is valued at the price of the investment's latest purchase
          -- or sale of it (as --infer-market-prices would, but only from the investment's own transactions, and only when
          -- no market price is known). Its net cost would be wrong after a sale at a different price, and could even be
          -- negative.
          valueOn :: Day -> MixedAmount -> MixedAmount
valueOn Day
date MixedAmount
amt0 =
            let amt :: MixedAmount
amt      = MixedAmount -> MixedAmount
dropClosedPositions MixedAmount
amt0
                valued :: MixedAmount
valued   = Day -> Day -> MixedAmount -> MixedAmount
mixedAmountValue Day
lastDay Day
date MixedAmount
amt
                unpriced :: Set CommoditySymbol
unpriced = [CommoditySymbol] -> Set CommoditySymbol
forall a. Ord a => [a] -> Set a
S.fromList [ Amount -> CommoditySymbol
acommodity Amount
a | Just CommoditySymbol
c <- [Maybe CommoditySymbol
expectedCommodity], Amount
a <- MixedAmount -> [Amount]
amounts MixedAmount
valued
                                                     , Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
c, Bool -> Bool
not (Amount -> Bool
amountIsZero Amount
a) ]
                isUnpriced :: Amount -> Bool
isUnpriced = (CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.member` Set CommoditySymbol
unpriced) (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity
                valued' :: MixedAmount
valued'
                  | Set CommoditySymbol -> Bool
forall a. Set a -> Bool
S.null Set CommoditySymbol
unpriced = MixedAmount
valued
                  | Bool
otherwise = Day -> Day -> MixedAmount -> MixedAmount
mixedAmountValue Day
lastDay Day
date (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ [Amount] -> MixedAmount
forall (t :: * -> *). Foldable t => t Amount -> MixedAmount
mixed
                      [ if Amount -> Bool
isUnpriced Amount
a then Amount -> (Amount -> Amount) -> Maybe Amount -> Amount
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Amount
a (\Amount
pr -> Amount
pr{aquantity = aquantity pr * aquantity a}) (CommoditySymbol -> Day -> Maybe Amount
latestTradePrice (Amount -> CommoditySymbol
acommodity Amount
a) Day
date) else Amount
a
                      | Amount
a <- MixedAmount -> [Amount]
amounts MixedAmount
amt ]
            in Maybe CommoditySymbol
-> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount
checkValued (Maybe ValuationType
value_ Maybe ValuationType
-> (ValuationType -> Maybe CommoditySymbol)
-> Maybe CommoditySymbol
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ValuationType -> Maybe CommoditySymbol
valuationTypeValuationCommodity) Maybe CommoditySymbol
expectedCommodity Day
date MixedAmount
valued'

          -- the value at the start of the span is the value at the end of the previous day, so that it equals the value
          -- at the end of the previous span (except with --value=end, which values each span at its own end)
          valueBefore :: MixedAmount
valueBefore = [Char] -> MixedAmount -> MixedAmount
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"valueBefore" (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Day -> MixedAmount -> MixedAmount
valueOn (Integer -> Day -> Day
addDays (-Integer
1) Day
b) (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Day -> MixedAmount
holdingsAt (Integer -> Day -> Day
addDays (-Integer
1) Day
b)

          valueAfter :: MixedAmount
valueAfter  = [Char] -> MixedAmount -> MixedAmount
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"valueAfter" (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Day -> MixedAmount -> MixedAmount
valueOn Day
lastDay (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Day -> MixedAmount
holdingsAt Day
lastDay

          flowDetails :: [InvestmentFlow]
flowDetails = (Day -> MixedAmount -> MixedAmount)
-> Day -> Day -> [InvestmentFlow]
investmentCashFlows Day -> MixedAmount -> MixedAmount
valueOn Day
b Day
lastDay
          cashFlow :: [(Day, MixedAmount)]
cashFlow = [Char] -> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"cashFlow" ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a b. (a -> b) -> a -> b
$ [ (InvestmentFlow -> Day
ifDate InvestmentFlow
f, InvestmentFlow -> MixedAmount
ifFlow InvestmentFlow
f) | InvestmentFlow
f <- [InvestmentFlow]
flowDetails ]

          -- The other postings of the investment transactions, which are where the money comes from or goes to.
          -- Only used to tell which commodity the money is in, after valuation.
          otherFlows :: [(Day, MixedAmount)]
otherFlows = [Char] -> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"otherFlows" ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a b. (a -> b) -> a -> b
$
            [(Day, MixedAmount)] -> [(Day, MixedAmount)]
cashFlowApplyCostValue ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a b. (a -> b) -> a -> b
$ [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall {b}. [(Day, b)] -> [(Day, b)]
inSpan ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a b. (a -> b) -> a -> b
$
            WhichDate -> [Transaction] -> Query -> [(Day, MixedAmount)]
calculateCashFlow WhichDate
wd [Transaction]
trans ([Query] -> Query
And [Query -> Query
Not Query
investmentsQuery, Query -> Query
Not Query
pnlQuery])

          pnl :: [(Day, MixedAmount)]
pnl = [Char] -> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"pnl" ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a b. (a -> b) -> a -> b
$
            [(Day, MixedAmount)] -> [(Day, MixedAmount)]
cashFlowApplyCostValue ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a b. (a -> b) -> a -> b
$ [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall {b}. [(Day, b)] -> [(Day, b)]
inSpan ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a b. (a -> b) -> a -> b
$
            WhichDate -> [Transaction] -> Query -> [(Day, MixedAmount)]
calculateCashFlow WhichDate
wd [Transaction]
trans ([Query] -> Query
And [Query -> Query
Not Query
investmentsQuery, Query
pnlQuery])

          -- postings dated (like the cash flows and holdings) within the span
          inSpan :: [(Day, b)] -> [(Day, b)]
inSpan = ((Day, b) -> Bool) -> [(Day, b)] -> [(Day, b)]
forall a. (a -> Bool) -> [a] -> [a]
filter (\(Day
d, b
_) -> Day
d Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
>= Day
b Bool -> Bool -> Bool
&& Day
d Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
<= Day
lastDay)

          spanCommodities :: Set CommoditySymbol
spanCommodities = [Char] -> Set CommoditySymbol -> Set CommoditySymbol
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"spanCommodities" (Set CommoditySymbol -> Set CommoditySymbol)
-> Set CommoditySymbol -> Set CommoditySymbol
forall a b. (a -> b) -> a -> b
$
            [Set CommoditySymbol] -> Set CommoditySymbol
forall (f :: * -> *) a. (Foldable f, Ord a) => f (Set a) -> Set a
S.unions ([Set CommoditySymbol] -> Set CommoditySymbol)
-> [Set CommoditySymbol] -> Set CommoditySymbol
forall a b. (a -> b) -> a -> b
$ (MixedAmount -> Set CommoditySymbol
maCommodities MixedAmount
valueBefore) Set CommoditySymbol
-> [Set CommoditySymbol] -> [Set CommoditySymbol]
forall a. a -> [a] -> [a]
: (MixedAmount -> Set CommoditySymbol
maCommodities MixedAmount
valueAfter) Set CommoditySymbol
-> [Set CommoditySymbol] -> [Set CommoditySymbol]
forall a. a -> [a] -> [a]
: ((Day, MixedAmount) -> Set CommoditySymbol)
-> [(Day, MixedAmount)] -> [Set CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (MixedAmount -> Set CommoditySymbol
maCommodities(MixedAmount -> Set CommoditySymbol)
-> ((Day, MixedAmount) -> MixedAmount)
-> (Day, MixedAmount)
-> Set CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(Day, MixedAmount) -> MixedAmount
forall a b. (a, b) -> b
snd) ([(Day, MixedAmount)]
cashFlow [(Day, MixedAmount)]
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a. [a] -> [a] -> [a]
++ [(Day, MixedAmount)]
pnl)

          thisSpan :: OneSpan
thisSpan = [Char] -> OneSpan -> OneSpan
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"processing span" (OneSpan -> OneSpan) -> OneSpan -> OneSpan
forall a b. (a -> b) -> a -> b
$
                     Day
-> Day
-> MixedAmount
-> MixedAmount
-> [(Day, MixedAmount)]
-> [(Day, MixedAmount)]
-> OneSpan
OneSpan Day
b Day
e MixedAmount
valueBefore MixedAmount
valueAfter [(Day, MixedAmount)]
cashFlow [(Day, MixedAmount)]
pnl

        Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Set CommoditySymbol -> Int
forall a. Set a -> Int
S.size Set CommoditySymbol
spanCommodities Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
1) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
          [Char] -> m ()
forall a. [Char] -> a
multiCommodityError ([Char] -> m ()) -> [Char] -> m ()
forall a b. (a -> b) -> a -> b
$ [Char]
"Period " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ (Day, Day) -> [Char]
forall a. Show a => a -> [Char]
show (Day
b,Day
e) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" has multiple commodities: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ (CommoditySymbol -> [Char]
T.unpack (CommoditySymbol -> [Char]) -> CommoditySymbol -> [Char]
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> [CommoditySymbol] -> CommoditySymbol
T.intercalate CommoditySymbol
", " ([CommoditySymbol] -> CommoditySymbol)
-> [CommoditySymbol] -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ (CommoditySymbol -> CommoditySymbol)
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map CommoditySymbol -> CommoditySymbol
showCommoditySymbol (Set CommoditySymbol -> [CommoditySymbol]
forall a. Set a -> [a]
S.toList Set CommoditySymbol
spanCommodities))

        let -- show a quantity of the span's (single) commodity, styled
            showAmt :: Decimal -> CommoditySymbol
showAmt Decimal
q = [Char] -> CommoditySymbol
T.pack ([Char] -> CommoditySymbol) -> [Char] -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Bool -> MixedAmount -> [Char]
showMixedAmountOneLineWithoutCost Bool
False (MixedAmount -> [Char]) -> MixedAmount -> [Char]
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts Map CommoditySymbol AmountStyle
styles (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$
              Amount -> MixedAmount
mixedAmount Amount
nullamt{acommodity = fromMaybe "" (S.lookupMin spanCommodities), aquantity = q}
        (irrdetails, eirr) <- Map CommoditySymbol AmountStyle
-> Bool
-> Bool
-> [InvestmentFlow]
-> OneSpan
-> m (Text, Either [Char] Double)
forall {m :: * -> *}.
Monad m =>
Map CommoditySymbol AmountStyle
-> Bool
-> Bool
-> [InvestmentFlow]
-> OneSpan
-> m (Text, Either [Char] Double)
internalRateOfReturn Map CommoditySymbol AmountStyle
styles Bool
showCashFlow Bool
prettyTables [InvestmentFlow]
flowDetails OneSpan
thisSpan
        (twrdetails, etwr) <- timeWeightedReturn showCashFlow prettyTables showAmt holdingsAt valueOn thisSpan
        let cashFlowAmt = MixedAmount -> MixedAmount
maNegate (MixedAmount -> MixedAmount)
-> ([MixedAmount] -> MixedAmount) -> [MixedAmount] -> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [MixedAmount] -> MixedAmount
forall (t :: * -> *). Foldable t => t MixedAmount -> MixedAmount
maSum ([MixedAmount] -> MixedAmount) -> [MixedAmount] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ ((Day, MixedAmount) -> MixedAmount)
-> [(Day, MixedAmount)] -> [MixedAmount]
forall a b. (a -> b) -> [a] -> [b]
map (Day, MixedAmount) -> MixedAmount
forall a b. (a, b) -> b
snd [(Day, MixedAmount)]
cashFlow
        let smallIsZero a
x = if a -> a
forall a. Num a => a -> a
abs a
x a -> a -> Bool
forall a. Ord a => a -> a -> Bool
< a
0.01 then a
0.0 else a
x
        let showPct = (a -> CommoditySymbol)
-> (Double -> CommoditySymbol)
-> Either a Double
-> CommoditySymbol
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (CommoditySymbol -> a -> CommoditySymbol
forall a b. a -> b -> a
const CommoditySymbol
"error") ([Char] -> CommoditySymbol
T.pack ([Char] -> CommoditySymbol)
-> (Double -> [Char]) -> Double -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> Double -> [Char]
forall r. PrintfType r => [Char] -> r
printf [Char]
"%0.2f%%" (Double -> [Char]) -> (Double -> Double) -> Double -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Double -> Double
forall {a}. (Ord a, Fractional a) => a -> a
smallIsZero)
        let spanLabel = CommoditySymbol -> [Char]
T.unpack (CommoditySymbol -> [Char]) -> CommoditySymbol -> [Char]
forall a b. (a -> b) -> a -> b
$ Day -> CommoditySymbol
showDate Day
b CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
" - " CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> Day -> CommoditySymbol
showDate Day
lastDay
        let errors = [ [Char]
spanLabel [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
", " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
what [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
":\n" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char] -> [[Char]] -> [Char]
forall a. [a] -> [[a]] -> [a]
intercalate [Char]
"\n" (([Char] -> [Char]) -> [[Char]] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map ([Char]
"  " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++) ([Char] -> [[Char]]
lines [Char]
msg))
                     | ([Char]
what, Left [Char]
msg) <- [([Char]
"IRR", () () -> Either [Char] Double -> Either [Char] ()
forall a b. a -> Either [Char] b -> Either [Char] a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Either [Char] Double
eirr), ([Char]
"TWR", () () -> Either [Char] (Double, Double) -> Either [Char] ()
forall a b. a -> Either [Char] b -> Either [Char] a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Either [Char] (Double, Double)
etwr)] ]
        let spanrow = [ Day -> CommoditySymbol
showDate Day
b
               , Day -> CommoditySymbol
showDate (Integer -> Day -> Day
addDays (-Integer
1) Day
e)
               , [Char] -> CommoditySymbol
T.pack ([Char] -> CommoditySymbol) -> [Char] -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Bool -> MixedAmount -> [Char]
showMixedAmountOneLineWithoutCost Bool
False (MixedAmount -> [Char]) -> MixedAmount -> [Char]
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts Map CommoditySymbol AmountStyle
styles (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ MixedAmount
valueBefore
               , [Char] -> CommoditySymbol
T.pack ([Char] -> CommoditySymbol) -> [Char] -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Bool -> MixedAmount -> [Char]
showMixedAmountOneLineWithoutCost Bool
False (MixedAmount -> [Char]) -> MixedAmount -> [Char]
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts Map CommoditySymbol AmountStyle
styles (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ MixedAmount
cashFlowAmt
               -- , T.pack $ showMixedAmount $
               --   -- dbg0With (lbl "cashflow after styling".showMixedAmountOneLine) $
               --   mapMixedAmount (amountSetFullPrecisionUpTo (Just defaultMaxDisplayPrecision)) $
               --   styleAmounts (styles
               --                 -- & dbg0With (lbl "styles".show))
               --   cashFlowAmt
               --   -- & dbg0With (lbl "cashflow before styling".showMixedAmountOneLine)
               , [Char] -> CommoditySymbol
T.pack ([Char] -> CommoditySymbol) -> [Char] -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Bool -> MixedAmount -> [Char]
showMixedAmountOneLineWithoutCost Bool
False (MixedAmount -> [Char]) -> MixedAmount -> [Char]
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts Map CommoditySymbol AmountStyle
styles (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ MixedAmount
valueAfter
               , [Char] -> CommoditySymbol
T.pack ([Char] -> CommoditySymbol) -> [Char] -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Bool -> MixedAmount -> [Char]
showMixedAmountOneLineWithoutCost Bool
False (MixedAmount -> [Char]) -> MixedAmount -> [Char]
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts Map CommoditySymbol AmountStyle
styles (MixedAmount -> MixedAmount) -> MixedAmount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ (MixedAmount
valueAfter MixedAmount -> MixedAmount -> MixedAmount
`maMinus` (MixedAmount
valueBefore MixedAmount -> MixedAmount -> MixedAmount
`maPlus` MixedAmount
cashFlowAmt))
               , Either [Char] Double -> CommoditySymbol
forall {a}. Either a Double -> CommoditySymbol
showPct Either [Char] Double
eirr
               , Either [Char] Double -> CommoditySymbol
forall {a}. Either a Double -> CommoditySymbol
showPct ((Double, Double) -> Double
forall a b. (a, b) -> a
fst ((Double, Double) -> Double)
-> Either [Char] (Double, Double) -> Either [Char] Double
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either [Char] (Double, Double)
etwr)
               , Either [Char] Double -> CommoditySymbol
forall {a}. Either a Double -> CommoditySymbol
showPct ((Double, Double) -> Double
forall a b. (a, b) -> b
snd ((Double, Double) -> Double)
-> Either [Char] (Double, Double) -> Either [Char] Double
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either [Char] (Double, Double)
etwr) ]
        return (irrdetails <> twrdetails, spanrow, errors)

  (perioddetails, periodRows, periodErrors) <- unzip3 <$> forM spans processSpan
  (totaldetails, totalRow, totalErrors) <- case periodRows of
    [[CommoditySymbol]
singleRow] -> (Text, [CommoditySymbol], [[Char]])
-> IO (Text, [CommoditySymbol], [[Char]])
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text
"", [CommoditySymbol]
singleRow, [])
    [[CommoditySymbol]]
_           -> (Day, Day) -> IO (Text, [CommoditySymbol], [[Char]])
forall {m :: * -> *}.
Monad m =>
(Day, Day) -> m (Text, [CommoditySymbol], [[Char]])
processSpan (Day, Day)
fullPeriod

  let rowTitles = Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.NoLine ((Integer -> Header CommoditySymbol)
-> [Integer] -> [Header CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map (CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header (CommoditySymbol -> Header CommoditySymbol)
-> (Integer -> CommoditySymbol)
-> Integer
-> Header CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> CommoditySymbol
T.pack ([Char] -> CommoditySymbol)
-> (Integer -> [Char]) -> Integer -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> [Char]
forall a. Show a => a -> [Char]
show) (Int -> [Integer] -> [Integer]
forall a. Int -> [a] -> [a]
take ([[CommoditySymbol]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[CommoditySymbol]]
periodRows) [Integer
1..]))

  let isSingleSpan = [(Day, Day)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Day, Day)]
spans Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1
      details = [Text] -> Text
forall a. Monoid a => [a] -> a
mconcat [Text]
perioddetails Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
totaldetails

      rows = if Bool
isSingleSpan then [[CommoditySymbol]]
periodRows else [[CommoditySymbol]]
periodRows [[CommoditySymbol]] -> [[CommoditySymbol]] -> [[CommoditySymbol]]
forall a. [a] -> [a] -> [a]
++ [[CommoditySymbol]
totalRow]
      -- a rate of return that can't be computed shows as "error" in its cell; the reasons are given after the report
      errors = [[[Char]]] -> [[Char]]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[[Char]]]
periodErrors [[Char]] -> [[Char]] -> [[Char]]
forall a. [a] -> [a] -> [a]
++ [[Char]]
totalErrors

  let table = Header CommoditySymbol
-> Header CommoditySymbol
-> [[CommoditySymbol]]
-> Table CommoditySymbol CommoditySymbol CommoditySymbol
forall rh ch a. Header rh -> Header ch -> [[a]] -> Table rh ch a
Table
              (if Bool
isSingleSpan
                then Header CommoditySymbol
rowTitles
                else Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.SingleLine  [ Header CommoditySymbol
rowTitles, Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.NoLine [ CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"Total" ]]
              )
              (Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.DoubleLine
               [ Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.SingleLine [CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"Begin", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"End"]
               , Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.SingleLine [CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"Value (begin)", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"Cashflow", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"Value (end)", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"PnL"]
               , Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.SingleLine [CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"IRR"]
               , Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.SingleLine [CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"TWR/period", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"TWR/year"]])
              [[CommoditySymbol]]
rows

  writeOutput opts $ TL.unpack $ withTitle ropts $
    details <> Tab.render prettyTables id id id table <> "\n"

  -- The report did complete, and a rate with no answer is a permanent fact about the journal, so this is a warning.
  unless (null errors) $ do
    hFlush stdout
    warnIO $ intercalate "\n" $ "Some rates of return could not be computed (they are shown as error):" : errors

-- | Time-weighted rate of return, computed from the investment's value at the end of each day.
--
-- Only end-of-day values are used, which are always well defined: the day's closing balance, valued with the prices in
-- effect that day, whatever the order of transactions and prices within the day. Between days with cash flows, the
-- return is the ratio of values. A day with cash flows is split in two: first the day's price changes, applied to the
-- holdings carried over from the previous day; then the flows, as if made at the day's closing prices, with deposits
-- counted at the start and withdrawals at the end of that part (any difference between the trade prices and the
-- closing prices is part of its return). A stretch with nothing invested earns nothing, and contributes a factor of 1.
-- All returns are chained.
--
-- Cash flows are measured from the investment's side (see investmentCashFlows), so that they always agree with the
-- changes in its value.
timeWeightedReturn :: Bool
-> Bool
-> (Decimal -> CommoditySymbol)
-> (Day -> a)
-> (Day -> a -> MixedAmount)
-> OneSpan
-> m (Text, Either [Char] (Double, Double))
timeWeightedReturn Bool
showCashFlow Bool
prettyTables Decimal -> CommoditySymbol
showAmt Day -> a
holdingsAt Day -> a -> MixedAmount
valueOn (OneSpan Day
begin Day
end MixedAmount
_valueBeforeAmt MixedAmount
_valueAfterAmt [(Day, MixedAmount)]
cashflows [(Day, MixedAmount)]
_pnls) = do
  let
    lastDay :: Day
lastDay      = Integer -> Day -> Day
addDays (-Integer
1) Day
end
    valueAt :: Day -> Decimal
valueAt Day
d    = MixedAmount -> Decimal
unMix (MixedAmount -> Decimal) -> MixedAmount -> Decimal
forall a b. (a -> b) -> a -> b
$ Day -> a -> MixedAmount
valueOn Day
d (a -> MixedAmount) -> a -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Day -> a
holdingsAt Day
d

    -- deposits and withdrawals on each day of the period (each transaction's flows are netted, deposits are positive)
    flowsByDay :: Map Day (Decimal, Decimal)
flowsByDay = ((Decimal, Decimal) -> (Decimal, Decimal) -> (Decimal, Decimal))
-> [(Day, (Decimal, Decimal))] -> Map Day (Decimal, Decimal)
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith (\(Decimal
i1, Decimal
o1) (Decimal
i2, Decimal
o2) -> (Decimal
i1 Decimal -> Decimal -> Decimal
forall a. Num a => a -> a -> a
+ Decimal
i2, Decimal
o1 Decimal -> Decimal -> Decimal
forall a. Num a => a -> a -> a
+ Decimal
o2))
      [ (Day
d, (Decimal -> Decimal -> Decimal
forall a. Ord a => a -> a -> a
max Decimal
0 Decimal
f, Decimal -> Decimal -> Decimal
forall a. Ord a => a -> a -> a
min Decimal
0 Decimal
f)) | (Day
d, MixedAmount
ma) <- [(Day, MixedAmount)]
cashflows, let f :: Decimal
f = Decimal -> Decimal
forall a. Num a => a -> a
negate (MixedAmount -> Decimal
unMix MixedAmount
ma) ]

    -- Each row is a part of the period: (begin, end, what it is, value at begin, deposits, withdrawals, value at end).
    -- Every row's return is (value at end - withdrawals) / (value at begin + deposits) - 1 (withdrawals are negative),
    -- or 0 when nothing was invested at the start; the time-weighted return chains them.
    -- Stretches without cash flows get one row. A day with cash flows gets a row for its price changes (when there are
    -- any), from the previous day's closing value to the holdings carried over at this day's prices, and a row for its
    -- cash flows, from there to its closing value.
    go :: (Day, Decimal)
-> [(Day, (e, f))] -> [(Day, Day, c, Decimal, e, f, Decimal)]
go (Day
prevDay, Decimal
prevValue) [] =
      [ (Integer -> Day -> Day
addDays Integer
1 Day
prevDay, Day
lastDay, c
"no cash flows", Decimal
prevValue, e
0, f
0, Day -> Decimal
valueAt Day
lastDay) | Day
prevDay Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
< Day
lastDay ]
    go (Day
prevDay, Decimal
prevValue) ((Day
d, (e
deposits, f
withdrawals)) : [(Day, (e, f))]
rest) =
      let startValue :: Decimal
startValue = Day -> Decimal
valueAt (Integer -> Day -> Day
addDays (-Integer
1) Day
d)
          movedValue :: Decimal
movedValue = MixedAmount -> Decimal
unMix (MixedAmount -> Decimal) -> MixedAmount -> Decimal
forall a b. (a -> b) -> a -> b
$ Day -> a -> MixedAmount
valueOn Day
d (a -> MixedAmount) -> a -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Day -> a
holdingsAt (Integer -> Day -> Day
addDays (-Integer
1) Day
d)
          endValue :: Decimal
endValue   = Day -> Decimal
valueAt Day
d
      in [ (Integer -> Day -> Day
addDays Integer
1 Day
prevDay, Integer -> Day -> Day
addDays (-Integer
1) Day
d, c
"no cash flows", Decimal
prevValue, e
0, f
0, Decimal
startValue) | Integer -> Day -> Day
addDays Integer
1 Day
prevDay Day -> Day -> Bool
forall a. Ord a => a -> a -> Bool
<= Integer -> Day -> Day
addDays (-Integer
1) Day
d ]
         [(Day, Day, c, Decimal, e, f, Decimal)]
-> [(Day, Day, c, Decimal, e, f, Decimal)]
-> [(Day, Day, c, Decimal, e, f, Decimal)]
forall a. [a] -> [a] -> [a]
++ [ (Day
d, Day
d, c
"prices", Decimal
startValue, e
0, f
0, Decimal
movedValue) | Decimal
movedValue Decimal -> Decimal -> Bool
forall a. Eq a => a -> a -> Bool
/= Decimal
startValue ]
         [(Day, Day, c, Decimal, e, f, Decimal)]
-> [(Day, Day, c, Decimal, e, f, Decimal)]
-> [(Day, Day, c, Decimal, e, f, Decimal)]
forall a. [a] -> [a] -> [a]
++ (Day
d, Day
d, c
"cash flows", Decimal
movedValue, e
deposits, f
withdrawals, Decimal
endValue)
         (Day, Day, c, Decimal, e, f, Decimal)
-> [(Day, Day, c, Decimal, e, f, Decimal)]
-> [(Day, Day, c, Decimal, e, f, Decimal)]
forall a. a -> [a] -> [a]
:  (Day, Decimal)
-> [(Day, (e, f))] -> [(Day, Day, c, Decimal, e, f, Decimal)]
go (Day
d, Decimal
endValue) [(Day, (e, f))]
rest

    rowReturn :: (Day, Day, CommoditySymbol, Decimal, Decimal, a, a)
-> Either [Char] Double
rowReturn (Day
b, Day
e, CommoditySymbol
part, Decimal
v0, Decimal
dep, a
wdr, a
v1)
      | Decimal
base Decimal -> Decimal -> Bool
forall a. Eq a => a -> a -> Bool
== Decimal
0 = Double -> Either [Char] Double
forall a b. b -> Either a b
Right Double
0  -- nothing invested at the start
      | Decimal
base Decimal -> Decimal -> Bool
forall a. Ord a => a -> a -> Bool
< Decimal
0  = [Char] -> Either [Char] Double
forall a b. a -> Either a b
Left ([Char] -> Either [Char] Double) -> [Char] -> Either [Char] Double
forall a b. (a -> b) -> a -> b
$ [Char]
"Cannot compute the time-weighted return for "
                    [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
T.unpack (if Day
b Day -> Day -> Bool
forall a. Eq a => a -> a -> Bool
== Day
e then Day -> CommoditySymbol
showDate Day
b else Day -> CommoditySymbol
showDate Day
b CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> CommoditySymbol
" to " CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> Day -> CommoditySymbol
showDate Day
e) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" (" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
T.unpack CommoditySymbol
part [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"): "
                    [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"the investment's value at the start (" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
T.unpack (Decimal -> CommoditySymbol
showAmt Decimal
v0) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
") plus deposits ("
                    [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
T.unpack (Decimal -> CommoditySymbol
showAmt Decimal
dep) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
") is negative."
      | Bool
otherwise = Double -> Either [Char] Double
forall a b. b -> Either a b
Right (a -> Double
forall a b. (Real a, Fractional b) => a -> b
realToFrac a
final Double -> Double -> Double
forall a. Fractional a => a -> a -> a
/ Decimal -> Double
forall a b. (Real a, Fractional b) => a -> b
realToFrac Decimal
base Double -> Double -> Double
forall a. Num a => a -> a -> a
- Double
1 :: Double)
      where base :: Decimal
base = Decimal
v0 Decimal -> Decimal -> Decimal
forall a. Num a => a -> a -> a
+ Decimal
dep; final :: a
final = a
v1 a -> a -> a
forall a. Num a => a -> a -> a
- a
wdr

    rows :: [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal, Decimal)]
rows    = [Char]
-> [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal,
     Decimal)]
-> [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal,
     Decimal)]
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"twr rows" ([(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal, Decimal)]
 -> [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal,
      Decimal)])
-> [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal,
     Decimal)]
-> [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal,
     Decimal)]
forall a b. (a -> b) -> a -> b
$ (Day, Decimal)
-> [(Day, (Decimal, Decimal))]
-> [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal,
     Decimal)]
forall {c} {e} {f}.
(IsString c, Num e, Num f) =>
(Day, Decimal)
-> [(Day, (e, f))] -> [(Day, Day, c, Decimal, e, f, Decimal)]
go (Integer -> Day -> Day
addDays (-Integer
1) Day
begin, Day -> Decimal
valueAt (Integer -> Day -> Day
addDays (-Integer
1) Day
begin)) (Map Day (Decimal, Decimal) -> [(Day, (Decimal, Decimal))]
forall k a. Map k a -> [(k, a)]
M.toAscList Map Day (Decimal, Decimal)
flowsByDay)
    returns :: [Either [Char] Double]
returns = ((Day, Day, CommoditySymbol, Decimal, Decimal, Decimal, Decimal)
 -> Either [Char] Double)
-> [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal,
     Decimal)]
-> [Either [Char] Double]
forall a b. (a -> b) -> [a] -> [b]
map (Day, Day, CommoditySymbol, Decimal, Decimal, Decimal, Decimal)
-> Either [Char] Double
forall {a}.
Real a =>
(Day, Day, CommoditySymbol, Decimal, Decimal, a, a)
-> Either [Char] Double
rowReturn [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal, Decimal)]
rows
    -- once a row's return can't be computed, neither can the cumulative returns from there on
    cumulative :: [Either [Char] Double]
cumulative = Int -> [Either [Char] Double] -> [Either [Char] Double]
forall a. Int -> [a] -> [a]
drop Int
1 ([Either [Char] Double] -> [Either [Char] Double])
-> [Either [Char] Double] -> [Either [Char] Double]
forall a b. (a -> b) -> a -> b
$ (Either [Char] Double
 -> Either [Char] Double -> Either [Char] Double)
-> Either [Char] Double
-> [Either [Char] Double]
-> [Either [Char] Double]
forall b a. (b -> a -> b) -> b -> [a] -> [b]
scanl (\Either [Char] Double
acc Either [Char] Double
r -> (\Double
a Double
x -> (Double
1 Double -> Double -> Double
forall a. Num a => a -> a -> a
+ Double
a) Double -> Double -> Double
forall a. Num a => a -> a -> a
* (Double
1 Double -> Double -> Double
forall a. Num a => a -> a -> a
+ Double
x) Double -> Double -> Double
forall a. Num a => a -> a -> a
- Double
1) (Double -> Double -> Double)
-> Either [Char] Double -> Either [Char] (Double -> Double)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either [Char] Double
acc Either [Char] (Double -> Double)
-> Either [Char] Double -> Either [Char] Double
forall a b.
Either [Char] (a -> b) -> Either [Char] a -> Either [Char] b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Either [Char] Double
r) (Double -> Either [Char] Double
forall a b. b -> Either a b
Right Double
0) [Either [Char] Double]
returns
    etwr :: Either [Char] Double
etwr    = [Char] -> Either [Char] Double -> Either [Char] Double
forall a. Show a => [Char] -> a -> a
dbg3 [Char]
"twr" (Either [Char] Double -> Either [Char] Double)
-> Either [Char] Double -> Either [Char] Double
forall a b. (a -> b) -> a -> b
$ if [Either [Char] Double] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Either [Char] Double]
cumulative then Double -> Either [Char] Double
forall a b. b -> Either a b
Right Double
0 else [Either [Char] Double] -> Either [Char] Double
forall a. HasCallStack => [a] -> a
last [Either [Char] Double]
cumulative

    years :: Double
years = Integer -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Day -> Day -> Integer
diffDays Day
end Day
begin) Double -> Double -> Double
forall a. Fractional a => a -> a -> a
/ Double
365.25 :: Double
    result :: Either [Char] (Double, Double)
result = ((Double -> (Double, Double))
 -> Either [Char] Double -> Either [Char] (Double, Double))
-> Either [Char] Double
-> (Double -> (Double, Double))
-> Either [Char] (Double, Double)
forall a b c. (a -> b -> c) -> b -> a -> c
flip (Double -> (Double, Double))
-> Either [Char] Double -> Either [Char] (Double, Double)
forall a b. (a -> b) -> Either [Char] a -> Either [Char] b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Either [Char] Double
etwr ((Double -> (Double, Double)) -> Either [Char] (Double, Double))
-> (Double -> (Double, Double)) -> Either [Char] (Double, Double)
forall a b. (a -> b) -> a -> b
$ \Double
twr ->
      let periodTWR :: Decimal
periodTWR     = Word8 -> Decimal -> Decimal
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
2 (Decimal
100 Decimal -> Decimal -> Decimal
forall a. Num a => a -> a -> a
* Double -> Decimal
forall a b. (Real a, Fractional b) => a -> b
realToFrac Double
twr :: Decimal)
          annualizedTWR :: Double
annualizedTWR = Double
100 Double -> Double -> Double
forall a. Num a => a -> a -> a
* ((Double
1 Double -> Double -> Double
forall a. Num a => a -> a -> a
+ Double
twr) Double -> Double -> Double
forall a. Floating a => a -> a -> a
** (Double
1 Double -> Double -> Double
forall a. Fractional a => a -> a -> a
/ Double
years) Double -> Double -> Double
forall a. Num a => a -> a -> a
- Double
1) :: Double
      in (Decimal -> Double
forall a b. (Real a, Fractional b) => a -> b
realToFrac Decimal
periodTWR :: Double, Double
annualizedTWR)

    showPercent :: Either a Double -> CommoditySymbol
showPercent = (a -> CommoditySymbol)
-> (Double -> CommoditySymbol)
-> Either a Double
-> CommoditySymbol
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (CommoditySymbol -> a -> CommoditySymbol
forall a b. a -> b -> a
const CommoditySymbol
"error") ((Double -> CommoditySymbol) -> Either a Double -> CommoditySymbol)
-> (Double -> CommoditySymbol)
-> Either a Double
-> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ \Double
r -> [Char] -> CommoditySymbol
T.pack (Decimal -> [Char]
showDecimal (Word8 -> Decimal -> Decimal
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
2 (Double -> Decimal
forall a b. (Real a, Fractional b) => a -> b
realToFrac Double
r Decimal -> Decimal -> Decimal
forall a. Num a => a -> a -> a
* Decimal
100 :: Decimal)))
    details :: Text
details = if Bool -> Bool
not Bool
showCashFlow then Text
"" else
      [Char] -> Text
TL.pack ([Char] -> CommoditySymbol -> CommoditySymbol -> [Char]
forall r. PrintfType r => [Char] -> r
printf [Char]
"\nTWR returns for period %s - %s\n" (Day -> CommoditySymbol
showDate Day
begin) (Day -> CommoditySymbol
showDate Day
lastDay))
      Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Bool
-> ([Char] -> CommoditySymbol)
-> (CommoditySymbol -> CommoditySymbol)
-> (CommoditySymbol -> CommoditySymbol)
-> Table [Char] CommoditySymbol CommoditySymbol
-> Text
forall a rh ch.
Show a =>
Bool
-> (rh -> CommoditySymbol)
-> (ch -> CommoditySymbol)
-> (a -> CommoditySymbol)
-> Table rh ch a
-> Text
Tab.render Bool
prettyTables [Char] -> CommoditySymbol
T.pack CommoditySymbol -> CommoditySymbol
forall a. a -> a
id CommoditySymbol -> CommoditySymbol
forall a. a -> a
id
        (Header [Char]
-> Header CommoditySymbol
-> [[CommoditySymbol]]
-> Table [Char] CommoditySymbol CommoditySymbol
forall rh ch a. Header rh -> Header ch -> [[a]] -> Table rh ch a
Table
         (Properties -> [Header [Char]] -> Header [Char]
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.NoLine [[Char] -> Header [Char]
forall h. h -> Header h
Header (Int -> [Char]
forall a. Show a => a -> [Char]
show Int
n) | Int
n <- [Int
1..[(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal, Decimal)]
-> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal, Decimal)]
rows]])
         (Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
DoubleLine
           [ Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.SingleLine [CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Tab.Header CommoditySymbol
"Begin", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Tab.Header CommoditySymbol
"End", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Tab.Header CommoditySymbol
"Part"]
           , Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.SingleLine [CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Tab.Header CommoditySymbol
"Value (begin)", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Tab.Header CommoditySymbol
"Deposits", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Tab.Header CommoditySymbol
"Withdrawals", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Tab.Header CommoditySymbol
"Value (end)"]
           , Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.SingleLine [CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Tab.Header CommoditySymbol
"Return, %", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Tab.Header CommoditySymbol
"Cumulative, %"]])
         [ [ Day -> CommoditySymbol
showDate Day
b, Day -> CommoditySymbol
showDate Day
e, CommoditySymbol
part
           , Decimal -> CommoditySymbol
showAmt Decimal
v0, Decimal -> CommoditySymbol
showAmt Decimal
dep, Decimal -> CommoditySymbol
showAmt Decimal
wdr, Decimal -> CommoditySymbol
showAmt Decimal
v1
           , Either [Char] Double -> CommoditySymbol
forall {a}. Either a Double -> CommoditySymbol
showPercent Either [Char] Double
r, Either [Char] Double -> CommoditySymbol
forall {a}. Either a Double -> CommoditySymbol
showPercent Either [Char] Double
c ]
         | ((Day
b, Day
e, CommoditySymbol
part, Decimal
v0, Decimal
dep, Decimal
wdr, Decimal
v1), Either [Char] Double
r, Either [Char] Double
c) <- [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal, Decimal)]
-> [Either [Char] Double]
-> [Either [Char] Double]
-> [((Day, Day, CommoditySymbol, Decimal, Decimal, Decimal,
      Decimal),
     Either [Char] Double, Either [Char] Double)]
forall a b c. [a] -> [b] -> [c] -> [(a, b, c)]
zip3 [(Day, Day, CommoditySymbol, Decimal, Decimal, Decimal, Decimal)]
rows [Either [Char] Double]
returns [Either [Char] Double]
cumulative ])
      Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"Each row's return is (Value (end) - Withdrawals) / (Value (begin) + Deposits) - 1; they are chained.\n"
      Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> case Either [Char] (Double, Double)
result of
           Right (Double
periodTWR, Double
annualizedTWR) ->
             [Char] -> Text
TL.pack ([Char] -> Double -> Double -> Double -> [Char]
forall r. PrintfType r => [Char] -> r
printf [Char]
"Total period TWR: %.2f%%.\nPeriod: %.2f years.\nAnnualized TWR: %.2f%%\n\n"
               Double
periodTWR Double
years Double
annualizedTWR)
           Left [Char]
_ -> Text
"\n"

  (Text, Either [Char] (Double, Double))
-> m (Text, Either [Char] (Double, Double))
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text
details, Either [Char] (Double, Double)
result)

internalRateOfReturn :: Map CommoditySymbol AmountStyle
-> Bool
-> Bool
-> [InvestmentFlow]
-> OneSpan
-> m (Text, Either [Char] Double)
internalRateOfReturn Map CommoditySymbol AmountStyle
styles Bool
showCashFlow Bool
prettyTables [InvestmentFlow]
flowDetails (OneSpan Day
begin Day
end MixedAmount
valueBefore MixedAmount
valueAfter [(Day, MixedAmount)]
cashFlow [(Day, MixedAmount)]
_pnl) = do
  let prefix :: (Day, MixedAmount)
prefix = (Day
begin, MixedAmount -> MixedAmount
maNegate MixedAmount
valueBefore)

      postfix :: (Day, MixedAmount)
postfix = (Day
end, MixedAmount
valueAfter)

      totalCF :: [(Day, MixedAmount)]
totalCF = ((Day, MixedAmount) -> Bool)
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a. (a -> Bool) -> [a] -> [a]
filter (MixedAmount -> Bool
maIsNonZero (MixedAmount -> Bool)
-> ((Day, MixedAmount) -> MixedAmount)
-> (Day, MixedAmount)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Day, MixedAmount) -> MixedAmount
forall a b. (a, b) -> b
snd) ([(Day, MixedAmount)] -> [(Day, MixedAmount)])
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a b. (a -> b) -> a -> b
$ (Day, MixedAmount)
prefix (Day, MixedAmount) -> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a. a -> [a] -> [a]
: (((Day, MixedAmount) -> Day)
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Day, MixedAmount) -> Day
forall a b. (a, b) -> a
fst [(Day, MixedAmount)]
cashFlow) [(Day, MixedAmount)]
-> [(Day, MixedAmount)] -> [(Day, MixedAmount)]
forall a. [a] -> [a] -> [a]
++ [(Day, MixedAmount)
postfix]

      showMA :: MixedAmount -> CommoditySymbol
showMA = [Char] -> CommoditySymbol
T.pack ([Char] -> CommoditySymbol)
-> (MixedAmount -> [Char]) -> MixedAmount -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> MixedAmount -> [Char]
showMixedAmountOneLineWithoutCost Bool
False (MixedAmount -> [Char])
-> (MixedAmount -> MixedAmount) -> MixedAmount -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map CommoditySymbol AmountStyle -> MixedAmount -> MixedAmount
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts Map CommoditySymbol AmountStyle
styles
      -- one row per cash flow, with the transaction it comes from, between the values at the start and the end
      -- (dated like the IRR uses them: the value at the end of the last day, on the day after it)
      rows :: [(Day, CommoditySymbol, CommoditySymbol, CommoditySymbol,
  MixedAmount)]
rows =
           [ (Day
begin, CommoditySymbol
"value at the start", CommoditySymbol
"", CommoditySymbol
"", MixedAmount -> MixedAmount
maNegate MixedAmount
valueBefore) | MixedAmount -> Bool
maIsNonZero MixedAmount
valueBefore ]
        [(Day, CommoditySymbol, CommoditySymbol, CommoditySymbol,
  MixedAmount)]
-> [(Day, CommoditySymbol, CommoditySymbol, CommoditySymbol,
     MixedAmount)]
-> [(Day, CommoditySymbol, CommoditySymbol, CommoditySymbol,
     MixedAmount)]
forall a. [a] -> [a] -> [a]
++ [ (InvestmentFlow -> Day
ifDate InvestmentFlow
f, InvestmentFlow -> CommoditySymbol
ifDescription InvestmentFlow
f, MixedAmount -> CommoditySymbol
showMA (InvestmentFlow -> MixedAmount
ifCost InvestmentFlow
f), MixedAmount -> CommoditySymbol
showMA (InvestmentFlow -> MixedAmount
ifPnl InvestmentFlow
f), InvestmentFlow -> MixedAmount
ifFlow InvestmentFlow
f) | InvestmentFlow
f <- (InvestmentFlow -> Day) -> [InvestmentFlow] -> [InvestmentFlow]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn InvestmentFlow -> Day
ifDate [InvestmentFlow]
flowDetails ]
        [(Day, CommoditySymbol, CommoditySymbol, CommoditySymbol,
  MixedAmount)]
-> [(Day, CommoditySymbol, CommoditySymbol, CommoditySymbol,
     MixedAmount)]
-> [(Day, CommoditySymbol, CommoditySymbol, CommoditySymbol,
     MixedAmount)]
forall a. [a] -> [a] -> [a]
++ [ (Day
end, CommoditySymbol
"value at the end of " CommoditySymbol -> CommoditySymbol -> CommoditySymbol
forall a. Semigroup a => a -> a -> a
<> Day -> CommoditySymbol
showDate (Integer -> Day -> Day
addDays (-Integer
1) Day
end), CommoditySymbol
"", CommoditySymbol
"", MixedAmount
valueAfter) | MixedAmount -> Bool
maIsNonZero MixedAmount
valueAfter ]
      details :: Text
details = if Bool -> Bool
not Bool
showCashFlow then Text
"" else
        [Char] -> Text
TL.pack ([Char] -> CommoditySymbol -> CommoditySymbol -> [Char]
forall r. PrintfType r => [Char] -> r
printf [Char]
"\nIRR cash flows for %s - %s\n" (Day -> CommoditySymbol
showDate Day
begin) (Day -> CommoditySymbol
showDate (Integer -> Day -> Day
addDays (-Integer
1) Day
end)))
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Bool
-> (CommoditySymbol -> CommoditySymbol)
-> (CommoditySymbol -> CommoditySymbol)
-> (CommoditySymbol -> CommoditySymbol)
-> Table CommoditySymbol CommoditySymbol CommoditySymbol
-> Text
forall a rh ch.
Show a =>
Bool
-> (rh -> CommoditySymbol)
-> (ch -> CommoditySymbol)
-> (a -> CommoditySymbol)
-> Table rh ch a
-> Text
Tab.render Bool
prettyTables CommoditySymbol -> CommoditySymbol
forall a. a -> a
id CommoditySymbol -> CommoditySymbol
forall a. a -> a
id CommoditySymbol -> CommoditySymbol
forall a. a -> a
id
          (Header CommoditySymbol
-> Header CommoditySymbol
-> [[CommoditySymbol]]
-> Table CommoditySymbol CommoditySymbol CommoditySymbol
forall rh ch a. Header rh -> Header ch -> [[a]] -> Table rh ch a
Table
           (Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.NoLine [ CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header (Day -> CommoditySymbol
showDate Day
d) | (Day
d, CommoditySymbol
_, CommoditySymbol
_, CommoditySymbol
_, MixedAmount
_) <- [(Day, CommoditySymbol, CommoditySymbol, CommoditySymbol,
  MixedAmount)]
rows ])
           (Properties -> [Header CommoditySymbol] -> Header CommoditySymbol
forall h. Properties -> [Header h] -> Header h
Tab.Group Properties
Tab.SingleLine [CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"Description", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"Investment, at cost", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"Profit/loss", CommoditySymbol -> Header CommoditySymbol
forall h. h -> Header h
Header CommoditySymbol
"Amount"])
           [ [CommoditySymbol
desc, CommoditySymbol
cost, CommoditySymbol
pnl, MixedAmount -> CommoditySymbol
showMA MixedAmount
amt] | (Day
_, CommoditySymbol
desc, CommoditySymbol
cost, CommoditySymbol
pnl, MixedAmount
amt) <- [(Day, CommoditySymbol, CommoditySymbol, CommoditySymbol,
  MixedAmount)]
rows ])
        Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"Amounts are from your point of view: what you put in is negative, what you take out (or still have) positive.\n\n"

  (Text, Either [Char] Double) -> m (Text, Either [Char] Double)
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return (Text
details, (IrrError -> Either [Char] Double)
-> (Double -> Either [Char] Double)
-> Either IrrError Double
-> Either [Char] Double
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ([Char] -> Either [Char] Double
forall a b. a -> Either a b
Left ([Char] -> Either [Char] Double)
-> (IrrError -> [Char]) -> IrrError -> Either [Char] Double
forall b c a. (b -> c) -> (a -> b) -> a -> c
. IrrError -> [Char]
irrErrorMessage) Double -> Either [Char] Double
forall a b. b -> Either a b
Right (Either IrrError Double -> Either [Char] Double)
-> Either IrrError Double -> Either [Char] Double
forall a b. (a -> b) -> a -> b
$ Day -> [(Day, Decimal)] -> Either IrrError Double
xirr Day
end [ (Day
d, MixedAmount -> Decimal
unMix MixedAmount
a) | (Day
d, MixedAmount
a) <- [(Day, MixedAmount)]
totalCF ])

irrErrorMessage :: IrrError -> String
irrErrorMessage :: IrrError -> [Char]
irrErrorMessage IrrError
e = [Char]
"Equation for Internal Rate of Return (IRR) can not be solved.\n" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ case IrrError
e of
  IrrError
IrrNothingPutIn ->
    [Char]
"  Money only came out of the investment in this period (or is still in it at the end), and none was put in\n\
    \  (counting its value at the start as put in), so the IRR is infinite."
  IrrAllOnOneDay Day
d ->
    [Char]
"  All of this period's cash flows (including the values at its start and end) fall on " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
T.unpack (Day -> CommoditySymbol
showDate Day
d) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
",\n\
    \  so no time passes for the gain or loss to happen in."
  IrrError
IrrNotBracketed ->
    [Char]
"  Possible causes: IRR is huge (>1000000%), balance of investment becomes negative at some point in time."
  IrrError
IrrSearchFailed ->
    [Char]
"  Either search does not converge to a solution, or converges too slowly."

type CashFlow = [(Day, MixedAmount)]

calculateCashFlow :: WhichDate -> [Transaction] -> Query -> CashFlow
calculateCashFlow :: WhichDate -> [Transaction] -> Query -> [(Day, MixedAmount)]
calculateCashFlow WhichDate
wd [Transaction]
trans Query
query =
  [ (WhichDate -> Posting -> Day
postingDateOrDate2 WhichDate
wd Posting
p, Posting -> MixedAmount
pamount Posting
p) | Posting
p <- (Transaction -> [Posting]) -> [Transaction] -> [Posting]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ((Posting -> Bool) -> [Posting] -> [Posting]
forall a. (a -> Bool) -> [a] -> [a]
filter (Query -> Posting -> Bool
matchesPosting Query
query) ([Posting] -> [Posting])
-> (Transaction -> [Posting]) -> Transaction -> [Posting]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
realPostings) [Transaction]
trans, MixedAmount -> Bool
maIsNonZero (Posting -> MixedAmount
pamount Posting
p) ]

unMix :: MixedAmount -> Quantity
unMix :: MixedAmount -> Decimal
unMix MixedAmount
a =
  case (MixedAmount -> Maybe Amount
unifyMixedAmount MixedAmount
a) of
    Just Amount
a' -> Amount -> Decimal
aquantity Amount
a'
    Maybe Amount
Nothing -> [Char] -> Decimal
forall a. [Char] -> a
multiCommodityError ([Char] -> Decimal) -> [Char] -> Decimal
forall a b. (a -> b) -> a -> b
$ [Char]
"Amounts could not be converted to a single commodity: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [[Char]] -> [Char]
forall a. Show a => a -> [Char]
show ((Amount -> [Char]) -> [Amount] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> [Char]
showAmount ([Amount] -> [[Char]]) -> [Amount] -> [[Char]]
forall a b. (a -> b) -> a -> b
$ MixedAmount -> [Amount]
amounts MixedAmount
a)

-- | One cash flow of the investment, with the parts it is computed from (shown by --cashflow).
data InvestmentFlow = InvestmentFlow
  { InvestmentFlow -> Day
ifDate        :: Day
  , InvestmentFlow -> CommoditySymbol
ifDescription :: T.Text
  , InvestmentFlow -> MixedAmount
ifCost        :: MixedAmount  -- ^ the cost of the transaction's investment postings on that date
  , InvestmentFlow -> MixedAmount
ifPnl         :: MixedAmount  -- ^ the transaction's profit and loss (gains positive)
  , InvestmentFlow -> MixedAmount
ifFlow        :: MixedAmount  -- ^ the cash flow: deposits negative, withdrawals positive
  }

-- | Drop the amounts of commodities whose quantities add up to zero (positions fully closed). Summing postings can keep
-- these as separate amounts with different costs, which don't cancel out when valued at cost.
dropClosedPositions :: MixedAmount -> MixedAmount
dropClosedPositions :: MixedAmount -> MixedAmount
dropClosedPositions MixedAmount
ma = (Amount -> Bool) -> MixedAmount -> MixedAmount
filterMixedAmount ((CommoditySymbol -> Set CommoditySymbol -> Bool
forall a. Ord a => a -> Set a -> Bool
`S.notMember` Set CommoditySymbol
closed) (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity) MixedAmount
ma
  where closed :: Set CommoditySymbol
closed = Map CommoditySymbol Decimal -> Set CommoditySymbol
forall k a. Map k a -> Set k
M.keysSet (Map CommoditySymbol Decimal -> Set CommoditySymbol)
-> (Map CommoditySymbol Decimal -> Map CommoditySymbol Decimal)
-> Map CommoditySymbol Decimal
-> Set CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Decimal -> Bool)
-> Map CommoditySymbol Decimal -> Map CommoditySymbol Decimal
forall a k. (a -> Bool) -> Map k a -> Map k a
M.filter (Decimal -> Decimal -> Bool
forall a. Eq a => a -> a -> Bool
== Decimal
0) (Map CommoditySymbol Decimal -> Set CommoditySymbol)
-> Map CommoditySymbol Decimal -> Set CommoditySymbol
forall a b. (a -> b) -> a -> b
$ (Decimal -> Decimal -> Decimal)
-> [(CommoditySymbol, Decimal)] -> Map CommoditySymbol Decimal
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
M.fromListWith Decimal -> Decimal -> Decimal
forall a. Num a => a -> a -> a
(+) [ (Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Decimal
aquantity Amount
a) | Amount
a <- MixedAmount -> [Amount]
amounts MixedAmount
ma ]

-- | After valuation, an amount of the investment should be in the expected commodity, if we know it. If some of it is
-- still in another commodity, there was no market price for that commodity on that date. Say so, rather than mistake
-- its quantity for a value or report a confusing mix of commodities later.
-- The expected commodity can differ from the one requested with --value, when nothing converts to that; mention it then.
checkValued :: Maybe CommoditySymbol -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount
checkValued :: Maybe CommoditySymbol
-> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount
checkValued Maybe CommoditySymbol
_ Maybe CommoditySymbol
Nothing Day
_ MixedAmount
amt = MixedAmount
amt
checkValued Maybe CommoditySymbol
requested (Just CommoditySymbol
c) Day
date MixedAmount
amt =
  case [CommoditySymbol] -> [CommoditySymbol]
forall a. Eq a => [a] -> [a]
nub [ Amount -> CommoditySymbol
acommodity Amount
a | Amount
a <- MixedAmount -> [Amount]
amounts MixedAmount
amt, Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
c, Bool -> Bool
not (Amount -> Bool
amountIsZero Amount
a) ] of
    []       -> MixedAmount
amt
    [CommoditySymbol]
unpriced -> [Char] -> MixedAmount
forall a. [Char] -> a
error' ([Char] -> MixedAmount) -> [Char] -> MixedAmount
forall a b. (a -> b) -> a -> b
$ [Char]
"Could not value the investment on " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
T.unpack (Day -> CommoditySymbol
showDate Day
date) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": "
                [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"no market price in " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
showc CommoditySymbol
c [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" is known for "
                [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char] -> [[Char]] -> [Char]
forall a. [a] -> [[a]] -> [a]
intercalate [Char]
", " ((CommoditySymbol -> [Char]) -> [CommoditySymbol] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map CommoditySymbol -> [Char]
showc [CommoditySymbol]
unpriced) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" on or before that date."
                [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ (case Maybe CommoditySymbol
requested of
                      Just CommoditySymbol
r | CommoditySymbol
r CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= CommoditySymbol
c -> [Char]
"\n" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
showc CommoditySymbol
r [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" was requested with --value, but the cash flows and PnL"
                                         [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" are in " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
showc CommoditySymbol
c [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
", as no market price converts them to " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> [Char]
showc CommoditySymbol
r [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"."
                      Maybe CommoditySymbol
_ -> [Char]
"")
                [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"\nAdd a P directive, or use --infer-market-prices to also use the prices recorded in transactions."
  where showc :: CommoditySymbol -> [Char]
showc = CommoditySymbol -> [Char]
T.unpack (CommoditySymbol -> [Char])
-> (CommoditySymbol -> CommoditySymbol)
-> CommoditySymbol
-> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommoditySymbol -> CommoditySymbol
showCommoditySymbol

multiCommodityError :: [Char] -> b
multiCommodityError [Char]
msg = [Char] -> b
forall a. [Char] -> a
error' ([Char] -> b) -> [Char] -> b
forall a b. (a -> b) -> a -> b
$ [Char]
msg [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++
    [Char]
"\nConsider using --value to force all costs to be in a single commodity." [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++
    [Char]
"\nFor example, \"--value=end,<commodity> --infer-market-prices\", where commodity is the one that you want to value the investment in."

-- Show Decimal rounded to two decimal places, unless it has less places already. This ensures that "2" won't be shown as "2.00"
showDecimal :: Decimal -> String
showDecimal :: Decimal -> [Char]
showDecimal Decimal
d = if Decimal
d Decimal -> Decimal -> Bool
forall a. Eq a => a -> a -> Bool
== Decimal
rounded then Decimal -> [Char]
forall a. Show a => a -> [Char]
show Decimal
d else Decimal -> [Char]
forall a. Show a => a -> [Char]
show Decimal
rounded
  where
    rounded :: Decimal
rounded = Word8 -> Decimal -> Decimal
forall i. Integral i => Word8 -> DecimalRaw i -> DecimalRaw i
roundTo Word8
2 Decimal
d