I'm trying to find out the final weighted mean after buys and sells of my stocks.
So I am looking for a weighted average, to be adjusted by the buys and sells.
This is an example of my data. I have more than one stock but I can apply to the others using group_by.
ledger <-data.table(
ID = c(rep("b",3), rep("x",2)),
Prc = c(10,20,15, 35,40),
Qty= c(300,-50,100, 50,-10),
Op =c("Purchase", "Sale", "Purchase", "Purchase", "Sale")
)
ledger<-ledger %>%group_by(ID)%>%
mutate(Stock = cumsum(Qty))
ledger<-as.data.table(ledger)
View(ledger)
As I looked for my answer I found this code:
ledger[, Stock := cumsum(Qty)] # compute Stock value
ledger[, `:=` ( id = .I, AvgPrice = NA_real_ ) ] # add id and AvgPrice columns
ledger[ 1, AvgPrice := Prc ] # compute AvgPrice for first row
# work with remaining rows and find the AvgPrice
ledger[ ledger[, .I[-1]], AvgPrice := {
if( Op == "Sale" ){
ledger[ .I-1, AvgPrice ]
} else {
round( ( ( Qty * Prc ) + ledger[ .I-1, AvgPrice * Stock ] ) /
( Qty + ledger[ .I-1, Stock]) ,
digits = 2 )
}
}, by = id ]
ledger[, id := NULL ] # remove id column
That works very well. But I need to group_by my ID. So it wont make the average all toghether.
thanks for your contribution!!