简体   繁体   中英

portfolio optimization tseries R

i want to do a simple backtest with the package tseries in R. Let me give you a small example

There is a timeseries of in sample data and a timeseries of out of sample data, which contains 2 stocks and 3 returns.

in sample data:

isd<-as.timeSeries(matrix(c(0.02,0.01,0.03,0.021,0.031,0.014),nrow=3,ncol=2))

out of sample data:

oosd<-as.timeSeries(matrix(c(0.015,0.029,0.036,0.027,0.042,0.023),nrow=3,ncol=2))

Now i compute a loop which take the in sample data and add a new row to this data from the out of sample data in every step of the loop. Then it optimizes my portfolio every time with the new timeseries.

for(i in 1:3){
x<-rbind(isd,oosd[1:i,])
print(portfolio.optim(x))}

I get the following Output with $pw=optimal weights, $px=returns of the portfolio on every day, $ps=mean return of the portfolio in the complete periode, $ps=standard deviation of the portfolio on the whole periode

in sample data plus data of first day out of sample data

$pw
[1] 0.5 0.5

$px
[1] 0.0205 0.0205 0.0220 0.0210

$pm
[1] 0.021

$ps
[1] 0.0007071068

in sample data plus 2 days of out of sample data

$pw
[1] 0.5 0.5

$px
[1] 0.0205 0.0205 0.0220 0.0210 0.0355

$pm
[1] 0.0239

$ps
[1] 0.006513448

in sample data plus 3 days of out of sample data

$pw
[1] 0.5 0.5

$px
[1] 0.0205 0.0205 0.0220 0.0210 0.0355 0.0295

$pm
[1] 0.02483333

$ps
[1] 0.006258328

So now my Question. Is it possible to extract the last number of $px in every loop step and store it in an empty vector.

If i do it this way, the whole portfolio optimizations get safed in an vector

a<-NULL
for(i in 1:3){
x<-rbind(isd,oosd[1:i,])
a<-c(a,portfolio.optim(x))}

I want to do that backtesting on a timeseries with 257 in sample data and 253 out of sample data so this extraction is kind of necessary

I hope you can help me with my problem

greetings

You can access last of px as a$px[length(a$px)] . It is not a good practice to use rbind within a loop, things can get very slow with bigger data sets, if you cannot avoid looping, preallocate a vector, and then populate it. I would do away with the loop altogether..

require(timeSeries)
isd<-as.timeSeries(matrix(c(0.02,0.01,0.03,0.021,0.031,0.014),nrow=3,ncol=2))
oosd<-as.timeSeries(matrix(c(0.015,0.029,0.036,0.027,0.042,0.023),nrow=3,ncol=2))
mydata <- rbind(isd,oosd)
sapply(4:dim(mydata)[1], function(ind, mydata) portfolio.optim(mydata[1:ind,])$px[ind],   mydata=mydata)

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