Skip to content

Commit

Permalink
roi: share some of the value-on-date computation, speed improvement
Browse files Browse the repository at this point in the history
  • Loading branch information
adept committed Dec 12, 2024
1 parent 6a071e0 commit 9934eca
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions hledger/Hledger/Cli/Commands/Roi.hs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ roi CliOpts{rawopts_=rawopts, reportspec_=rspec@ReportSpec{_rsReportOpts=ReportO

let (fullPeriod, spans) = reportSpan filteredj rspec

let priceDirectiveDates = dbg3 "priceDirectiveDates" $ map pddate $ jpricedirectives j
let priceDirectiveDates = dbg3 "priceDirectiveDates" $ nub $ map pddate $ jpricedirectives j

let processSpan (DateSpan Nothing _) = error "Undefined start of the period - will be unable to compute the rates of return"
processSpan (DateSpan _ Nothing) = error "Undefined end of the period - will be unable to compute the rates of return"
Expand All @@ -120,7 +120,7 @@ roi CliOpts{rawopts_=rawopts, reportspec_=rspec@ReportSpec{_rsReportOpts=ReportO
total trans (And [investmentsQuery
, Date (DateSpan Nothing (Just end))])

priceDates = dbg3 "priceDates" $ nub $ filter (spanContainsDate spn) priceDirectiveDates
priceDates = dbg3 "priceDates" $ filter (spanContainsDate spn) priceDirectiveDates
cashFlow = dbg3 "cashFlow" $
((map (,nullmixedamt) priceDates)++) $
cashFlowApplyCostValue $
Expand Down Expand Up @@ -225,20 +225,24 @@ timeWeightedReturn styles showCashFlow prettyTables investmentsQuery trans mixed
$ map (second maNegate)
$ datedAmounts

let investmentPostings = concatMap (filter (matchesPosting investmentsQuery) . realPostings) trans

let totalInvestmentPostingsTill date = sumPostings $ filter (matchesPosting (Date (DateSpan Nothing (Just $ Exact date)))) investmentPostings

let units =
dbg3 "units" $
tailDef (error' "Roi.hs units was null, please report a bug") $
scanl
(\(_, _, unitCost, unitBalance) (date, amt) ->
let valueOnDate = unMix $ mixedAmountValue end date $ total trans (And [investmentsQuery, Date (DateSpan Nothing (Just $ Exact date))])
let valueOnDate = unMix $ mixedAmountValue end date $ totalInvestmentPostingsTill date
in
case amt of
Right amt' ->
-- we are buying or selling
let unitsBoughtOrSold = unMix amt' / unitCost
unitBalance' = unitBalance + unitsBoughtOrSold
unitCost' =
if unitsBoughtOrSold == 0 && valueOnDate/=0
if unitsBoughtOrSold == 0 && valueOnDate /= 0
then valueOnDate/unitBalance' -- just a price update without units bought or sold
else unitCost
in (valueOnDate, unitsBoughtOrSold, unitCost', unitBalance')
Expand Down

0 comments on commit 9934eca

Please sign in to comment.