Skip to content

Commit

Permalink
expose queryStmt / target balance fee
Browse files Browse the repository at this point in the history
  • Loading branch information
yellowbean committed Aug 3, 2023
1 parent ed6410b commit 2a64d95
Show file tree
Hide file tree
Showing 9 changed files with 163 additions and 88 deletions.
2 changes: 1 addition & 1 deletion app/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ import qualified InterestRate as IR
import qualified Stmt
import qualified Triggers as TRG
import qualified Revolving as RV
import qualified Lib as Lib
import qualified Lib
import qualified Util as U


Expand Down
3 changes: 0 additions & 3 deletions src/Accounts.hs
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,6 @@ instance QueryByComment Account where
queryStmt (Account _ _ _ _ (Just (Statement txns))) tc
= filter (\x -> getTxnComment x == tc) txns

queryTxnAmt a tc
= sum $ map getTxnAmt $ queryStmt a tc

$(deriveJSON defaultOptions ''InterestInfo)
$(deriveJSON defaultOptions ''ReserveAmount)
$(deriveJSON defaultOptions ''Account)
4 changes: 2 additions & 2 deletions src/Deal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
{-# LANGUAGE GADTs #-}

module Deal (run2,runPool2,getInits,runDeal,ExpectReturn(..)
,calcDueFee,applicableAdjust,performAction,queryDeal
,applicableAdjust,performAction,queryDeal
,setFutureCF,populateDealDates
,calcTargetAmount,updateLiqProvider
,projAssetUnion,priceAssetUnion,accrueLiqProvider
Expand Down Expand Up @@ -449,7 +449,7 @@ priceBonds t (AP.RunZSpread curve bond_prices)
runDeal :: P.Asset a => TestDeal a -> ExpectReturn -> Maybe AP.ApplyAssumptionType-> Maybe AP.BondPricingInput
-> (TestDeal a,Maybe CF.CashFlowFrame, Maybe [ResultComponent],Maybe (Map.Map String L.PriceResult))
runDeal t _ assumps bpi =
(finalDeal, Just pcf, Just ((getRunResult finalDeal)++logs), bndPricing) -- `debug` ("Run Deal"++show(name t) ++" Actions# >> "++ show (length ads)++"\n last log"++ show logs)
(finalDeal, Just pcf, Just ((getRunResult finalDeal)++logs), bndPricing) -- `debug` ("Run Deal"++show(name t))
where
(ads,pcf,rcurves,calls,revolvingAssump) = getInits t assumps -- `debug` ("runDeal init line")
(finalDeal,logs) = run2 (removePoolCf t) pcf (Just ads) (Just rcurves) calls revolvingAssump [] `debug` ("start status"++show (status t) )-- `debug` ("run2 rAssump>>"++show revolvingAssump++"1st Action"++ show (head ads)++"PCF size"++show (CF.sizeCashFlowFrame pcf))
Expand Down
6 changes: 6 additions & 0 deletions src/Deal/DealAction.hs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,12 @@ calcDueFee t calcDay f@(F.Fee fn (F.NumFee p s amt) fs fd (Just _fdDay) fa lpd _
baseCount = queryDealInt t (patchDateToStats calcDay s) calcDay
newFeeDueAmt = fromRational $ mulBInt amt $ baseCount * periodGap -- `debug` ("amt"++show amt++">>"++show baseCount++">>"++show periodGap)

calcDueFee t calcDay f@(F.Fee fn (F.TargetBalanceFee dsDue dsPaid) fs fd (Just _fdDay) fa lpd _)
= f { F.feeDue = dueAmt, F.feeDueDate = Just calcDay}
where
dsDueD = patchDateToStats d dsDue

Check failure on line 217 in src/Deal/DealAction.hs

View workflow job for this annotation

GitHub Actions / build

Variable not in scope: d :: Date
dsPaidD = patchDateToStats d dsPaid

Check failure on line 218 in src/Deal/DealAction.hs

View workflow job for this annotation

GitHub Actions / build

Variable not in scope: d :: Date
dueAmt = max 0 $ (queryDeal t dsDueD) - (queryDeal t dsPaidD)

updateLiqProvider :: P.Asset a => TestDeal a -> Date -> CE.LiqFacility -> CE.LiqFacility
updateLiqProvider t d liq@(CE.LiqFacility _ liqType (Just curBal) curCredit _ _ _ mRate mPRate stmt) -- refresh available balance
Expand Down
40 changes: 40 additions & 0 deletions src/Deal/DealQuery.hs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ patchDateToStats d t
Factor _ds r -> Factor (patchDateToStats d _ds) r
UseCustomData n -> CustomData n d
CurrentPoolBorrowerNum -> FutureCurrentPoolBorrowerNum d
FeeTxnAmt ns mCmt -> FeeTxnAmtBy d ns mCmt
BondTxnAmt ns mCmt -> BondTxnAmtBy d ns mCmt
AccTxnAmt ns mCmt -> AccTxnAmtBy d ns mCmt
_ -> t


Expand Down Expand Up @@ -265,6 +268,43 @@ queryDeal t s =
filter (\x -> d == getDate x) txns
in
sum $ map ex stmts

FeeTxnAmtBy d fns mCmt ->
let
fees = Map.elems $ getFeeByName t (Just fns)
in
case mCmt of
Just cmt -> sum [ queryTxnAmtAsOf fee d cmt | fee <- fees ]
Nothing ->
let
_txn = concat [ getTxns (F.feeStmt fee) | fee <- fees ]
in
sumTxn (beforeOnDate _txn d)

BondTxnAmtBy d bns mCmt ->
let
bnds = Map.elems $ getBondByName t (Just bns)
in
case mCmt of
Just cmt -> sum [ queryTxnAmtAsOf bnd d cmt | bnd <- bnds ]
Nothing ->
let
_txn = concat [ getTxns (L.bndStmt bnd) | bnd <- bnds ]
in
sumTxn (beforeOnDate _txn d)

AccTxnAmtBy d ans mCmt ->
let
accs = Map.elems $ getAccountByName t (Just ans)
in
case mCmt of
Just cmt -> sum [ queryTxnAmtAsOf acc d cmt | acc <- accs ]
Nothing ->
let
_txn = concat [ getTxns (A.accStmt acc) | acc <- accs ]
in
sumTxn (beforeOnDate _txn d)


BondBalanceGapAt d bName ->
let
Expand Down
6 changes: 6 additions & 0 deletions src/Expense.hs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import GHC.Generics
import Data.Fixed
import Types
import Util
import qualified Stmt as S

import Debug.Trace
debug = flip trace
Expand All @@ -33,6 +34,7 @@ data FeeType = AnnualRateFee DealStats FormulaRate
| FixFee Balance
| RecurFee DatePattern Balance
| NumFee DatePattern DealStats Amount
| TargetBalanceFee DealStats DealStats
| FeeFlow Ts
deriving (Show,Eq, Generic)

Expand Down Expand Up @@ -81,6 +83,10 @@ buildFeeAccrueAction (fee:fees) ed r =
_
-> buildFeeAccrueAction fees ed r

instance S.QueryByComment Fee where
queryStmt Fee{feeStmt = Nothing} tc = []
queryStmt Fee{feeStmt = Just (S.Statement txns)} tc
= filter (\x -> S.getTxnComment x == tc) txns


$(deriveJSON defaultOptions ''FeeType)
Expand Down
8 changes: 6 additions & 2 deletions src/Liability.hs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ priceBond d rc b@(Bond bn _ (OriginalInfo obal od _ _) _ bal cr _ _ _ lastIntPay
Nothing -> (S.getTxnBalance fstTxn) + (S.getTxnPrincipal fstTxn) -- `debug` (show(getTxnBalance fstTxn))
where
fstTxn = head txns
Just _txn -> S.getTxnBalance _txn -- `debug` ("presentValue"++show presentValue++"Bond->"++bn)
Just _txn -> S.getTxnBalance _txn -- `debug` ("presentValue"++show presentValue++"Bond->"++bn)
accruedInt = case _t of
Nothing -> (fromIntegral (max 0 (T.diffDays d leftPayDay))/365) * (mulBI leftBal cr)
Just _ -> 0 -- `debug` ("all txn"++show(_t))-- `debug` ("l day, right"++show(leftPayDay)++show(d)++show(T.diffDays leftPayDay d))
Expand Down Expand Up @@ -190,7 +190,7 @@ priceBond d rc b@(Bond bn _ (OriginalInfo obal od _ _) _ bal cr _ _ _ lastIntPay
in
b/presentValue -- `debug` "PRICING -D" -- `debug` ("B->"++show b++"PV"++show presentValue)
in
PriceResult presentValue (fromRational (100*(toRational presentValue)/(toRational obal))) (realToFrac wal) (realToFrac duration) (realToFrac convexity) accruedInt -- `debug` ("Convexity->"++ show convexity)
PriceResult presentValue (fromRational (100*(toRational presentValue)/(toRational obal))) (realToFrac wal) (realToFrac duration) (realToFrac convexity) accruedInt `debug` ("Obal->"++ show obal++"Rate>>"++ show (bndRate b))
where
futureCf = filter (\x -> (S.getDate x) > d) txns

Expand Down Expand Up @@ -291,6 +291,10 @@ buildRateResetDates b sd ed
(Floater _ _ dp _ _ _) -> genSerialDatesTill2 EE sd dp ed
_ -> []

instance S.QueryByComment Bond where
queryStmt Bond{bndStmt = Nothing} tc = []
queryStmt Bond{bndStmt = Just (S.Statement txns)} tc
= filter (\x -> S.getTxnComment x == tc) txns

$(deriveJSON defaultOptions ''InterestInfo)
$(deriveJSON defaultOptions ''OriginalInfo)
Expand Down
88 changes: 12 additions & 76 deletions src/Stmt.hs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module Stmt
,extractTxns,groupTxns,getTxns,getTxnComment,getTxnAmt,toDate,getTxnPrincipal,getTxnAsOf,getTxnBalance
,appendStmt,combineTxn,sliceStmt,getTxnBegBalance,getDate,getDates
,sliceTxns,TxnComment(..),QueryByComment(..)
,weightAvgBalanceByDates,weightAvgBalance
,weightAvgBalanceByDates,weightAvgBalance, sumTxn
,getFlow,FlowDirection(..), aggByTxnComment, Direction(..)
)
where
Expand All @@ -34,80 +34,6 @@ import qualified Data.Map as M
import Debug.Trace
debug = flip trace

data Direction = Credit
| Debit
deriving (Show,Ord, Eq, Generic)

data TxnComment = PayInt [BondName]
| PayYield BondName
| PayPrin [BondName]
| PayFee FeeName
| SeqPayFee [FeeName]
| PayFeeYield FeeName
| Transfer AccName AccName
| TransferBy AccName AccName Limit
| PoolInflow PoolSource
| LiquidationProceeds
| LiquidationSupport String
| LiquidationDraw
| LiquidationRepay
| LiquidationSupportInt Balance Balance
| BankInt
| Empty
| Tag String
| UsingDS DealStats
| UsingFormula FormulaType
| SwapAccure
| SwapInSettle
| SwapOutSettle
| PurchaseAsset
| TxnDirection Direction
| TxnComments [TxnComment]
deriving (Eq, Show, Ord , Generic)

instance ToJSON TxnComment where
toJSON (PayInt bns ) = String $ T.pack $ "<PayInt:"++ concat bns ++ ">"
toJSON (PayYield bn ) = String $ T.pack $ "<PayYield:"++ bn ++">"
toJSON (PayPrin bns ) = String $ T.pack $ "<PayPrin:"++ concat bns ++ ">"
toJSON (PayFee fn ) = String $ T.pack $ "<PayFee:" ++ fn ++ ">"
toJSON (SeqPayFee fns) = String $ T.pack $ "<SeqPayFee:"++ concat fns++">"
toJSON (PayFeeYield fn) = String $ T.pack $ "<PayFeeYield:"++ fn++">"
toJSON (Transfer an1 an2) = String $ T.pack $ "<Transfer:"++ an1 ++","++ an2++">"
toJSON (TransferBy an1 an2 limit) = String $ T.pack $ "<TransferBy:"++ an1 ++","++ an2++","++show limit++">"
toJSON (PoolInflow ps) = String $ T.pack $ "<PoolInflow:"++ show ps++">"
toJSON LiquidationProceeds = String $ T.pack $ "<Liquidation>"
toJSON (UsingDS ds) = String $ T.pack $ "<DS:"++ show ds++">"
toJSON (UsingFormula fm) = String $ T.pack $ "<Formula:"++ show fm++">"
toJSON BankInt = String $ T.pack $ "<BankInterest:>"
toJSON Empty = String $ T.pack $ ""
toJSON (TxnComments tcms) = Array $ V.fromList $ map toJSON tcms
toJSON (LiquidationSupport source) = String $ T.pack $ "<Support:"++source++">"
toJSON (LiquidationSupportInt b1 b2) = String $ T.pack $ "<SupportExp:(Int:"++ show b1 ++ ",Fee:" ++ show b2 ++")>"
toJSON LiquidationDraw = String $ T.pack $ "<Draw:>"
toJSON LiquidationRepay = String $ T.pack $ "<Repay:>"
toJSON SwapAccure = String $ T.pack $ "<Accure:>"
toJSON SwapInSettle = String $ T.pack $ "<SettleIn:>"
toJSON SwapOutSettle = String $ T.pack $ "<SettleOut:>"
toJSON PurchaseAsset = String $ T.pack $ "<PurchaseAsset:>"
toJSON (TxnDirection dr) = String $ T.pack $ "<TxnDirection:"++show dr++">"

instance FromJSON TxnComment where
parseJSON = withText "Empty" parseTxn

parseTxn :: T.Text -> Parser TxnComment
parseTxn "" = return Empty
parseTxn "<BankInt>" = return BankInt
parseTxn t = case tagName of
"Transfer" -> let
sv = T.splitOn (T.pack ",") $ T.pack contents
in
return $ Transfer (T.unpack (head sv)) (T.unpack (sv!!1))
where
pat = "<(\\S+):(\\S+)>"::String
sr = (T.unpack t =~ pat)::[[String]]
tagName = head sr!!1::String
contents = head sr!!2::String

type DueInt = Maybe Balance
type DuePremium = Maybe Balance

Expand Down Expand Up @@ -286,8 +212,18 @@ instance TimeSeries Txn where

class QueryByComment a where
queryStmt :: a -> TxnComment -> [Txn]
queryStmtAsOf :: a -> Date -> TxnComment -> [Txn]
queryStmtAsOf a d tc = [ txn | txn <- queryStmt a tc, getDate txn <= d]
queryTxnAmt :: a -> TxnComment -> Balance

queryTxnAmt a tc = sum $ map getTxnAmt $ queryStmt a tc
queryTxnAmtAsOf :: a -> Date -> TxnComment -> Balance
queryTxnAmtAsOf a d tc = sum $ getTxnAmt <$> queryStmtAsOf a d tc
-- queryTxn :: [Txn] -> TxnComment -> [Txn]
-- queryTxn txns comment = [ txn | txn <- txns, getTxnComment txn == comment]
--
-- queryTxnAmt :: [Txn] -> TxnComment -> Balance
-- queryTxnAmt txns comment
-- = sum $ geTxnAmt <$> queryTxn txns comment

$(deriveJSON defaultOptions ''Txn)
$(deriveJSON defaultOptions ''Statement)
Expand Down
Loading

0 comments on commit 2a64d95

Please sign in to comment.