简体   繁体   中英

in R compute portfolio daily return from a trade matrix

Dear stackoverflowers,

TRADES is a 2000 rows trades P&L matrix, head.matrix(TRADES) gives:

Date P&L

20170101 90
20170101 100
20170102 -50
20170102 35
20170102 180

I need to compute the daily portfolio P&L and store it to a new matrix. The problem is that the number of trades for each day is not constant.

I can subset the trades regarding their dates and store all the same date trades into a new matrix with for instance for 1st of January 2017: 20170101 <- TRADES[grep("20140101", TRADES$Date), ]

Then I can sum to get the daily P&L and store it to my daily returns matrix with: DailyReturns$20170101 <- sum(20170101$P&L)

But I don't know how to make a loop to repeat this operation for all the trades, could someone please help me on this? Joe

Assuming you have a data.frame or you can convert your matrix to a data.frame :

head(df)
#      Date  PL
#1 20170101  90
#2 20170101 100
#3 20170102 -50
#4 20170102  35
#5 20170102 130

aggregate(PL~Date, data=df,sum)
#      Date  PL
#1 20170101 190
#2 20170102 115

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM