I have tried to set up a R-code to calculate returns of each column. My problem is that the code should consider multiple investments of different time periods in each asset (column).
I have managed to extract the relevant prices of each day in which each investment was owned (rows) as an xts-object. NAs indicate that a given stock was not owned on the given date. Therefore, I have a table as shown below (as a xts object). Also, please note that the weekend is not included in the index column:
Stock 1 Stock 2 Stock 3 Stock 4 Stock 4
2019-10-18 100 NA NA 750 NA
2019-10-21 105 NA NA 1000 6
2019-10-22 110 NA NA NA 7
2019-10-23 NA NA NA 750 8
2019-10-24 10 NA NA 500 8
2019-10-25 7.5 NA NA NA 8
2019-10-28 5 NA NA 500 8
2019-10-29 NA NA 200 250 9
To interpret the table an example follows: Stock 1 was owned in the period from 2019-10-18 to 2019-10-22 where it was sold. On 2019-10-23 Stock 1 was not owned, whereas it was bought again on 2019-10-24 and sold again on 2019-10-28, and therefore a NA on 2019-10-29. The numbers in the column of Stock 1 reflect the stock prices for the given days.
The output I search to obtain is a vector summarizing each independent investment - which is not based upon the investment size:
Stock 1 Stock 2 Stock 3 Stock 4 Stock 5
Cumulative Return -40% NA 0% -50% 50%
Notice that each investment make use of the first and last row of each investment period to calculate the cumulative return. As an example -40% is calculated as: 110/100-1 + 5/10-1
.
If multiple investments are made in an asset (column), it will always be of non-overlapping periods as in the example above.
Thanks in advance!