diff --git a/hledger/Hledger/Cli/Commands/Roi.hs b/hledger/Hledger/Cli/Commands/Roi.hs index 6a9c62115..374b3d712 100644 --- a/hledger/Hledger/Cli/Commands/Roi.hs +++ b/hledger/Hledger/Cli/Commands/Roi.hs @@ -162,7 +162,9 @@ timeWeightedReturn showCashFlow prettyTables investmentsQuery trans mixedAmountV -- PnL and CashFlow, we would not be able to apply pnl change to 0 unit, -- which would lead to an error. We make sure that we have at least one -- cashflow entry at the front, and we know that there would be at most - -- one for the given date, by construction. + -- one for the given date, by construction. Empty CashFlows added + -- because of a begin date before the first transaction are not seen as + -- a valid cashflow entry at the front. zeroUnitsNeedsCashflowAtTheFront $ sort $ datedCashflows ++ datedPnls @@ -170,9 +172,14 @@ timeWeightedReturn showCashFlow prettyTables investmentsQuery trans mixedAmountV zeroUnitsNeedsCashflowAtTheFront changes = if initialUnits > 0 then changes else - let (leadingPnls, rest) = span (isLeft . snd) changes - (firstCashflow, rest') = splitAt 1 rest - in firstCashflow ++ leadingPnls ++ rest' + let (leadingEmptyCashFlows, rest) = span isEmptyCashflow changes + (leadingPnls, rest') = span (isLeft . snd) rest + (firstCashflow, rest'') = splitAt 1 rest' + in leadingEmptyCashFlows ++ firstCashflow ++ leadingPnls ++ rest'' + + isEmptyCashflow (_date, amt) = case amt of + Right amt -> mixedAmountIsZero amt + Left _ -> False datedPnls = map (second Left) $ aggregateByDate pnl diff --git a/hledger/test/roi.test b/hledger/test/roi.test index d360f06d0..11175efa5 100644 --- a/hledger/test/roi.test +++ b/hledger/test/roi.test @@ -345,3 +345,24 @@ hledger -f - roi --inv saving --pnl dividend +---++------------+------------++---------------+----------+-------------+---------++-------+-------+ >>>=0 + +# 14. Should support begin date before first transaction where first transaction has pnl +hledger -f - roi --inv stocks --pnl expenses --value=then,€ -Y +<<< +P 2022-07-31 A € 1 + +2022-08-01 Purchase + checking € -101 + stocks 100 A @ € 1 + expenses € 1 + +P 2022-08-02 A € 2 + +>>> ++---++------------+------------++---------------+----------+-------------+------++---------+--------+ +| || Begin | End || Value (begin) | Cashflow | Value (end) | PnL || IRR | TWR | ++===++============+============++===============+==========+=============+======++=========+========+ +| 1 || 2022-01-01 | 2022-12-31 || 0 | € 101 | € 200 | € 99 || 410.31% | 98.02% | ++---++------------+------------++---------------+----------+-------------+------++---------+--------+ + +>>>=0