Search code examples
rdatetimesplitxts

How to Split a XTS Data Frame by Date Index?


I have created a data frame by combining various technical indicators that are XTS object.

alldata_SBI <- data.frame(Ad(SBIN.NS),SMA50_SBI,SMA200_SBI,EMA50_SBI,EMA200_SBI,BB_SBI,
                          Momentum_SBI,MACD_SBI,RSI_SBI, ROC_SBI, WPR_SBI)
colnames(alldata_SBI) <- c("ADJ.CLOSE","SMA50","SMA200","EMA50","EMA200","BB.DN","BB.MAVG","BB.UP","BB.PCTB",
                           "MOMENTUM","MACD","MACD.SIGNAL","RSI","ROC", "WPR")

I see that the Data Frame has a Date Index.

Data Frame Output

I noticed that this Date Index is automatically created may be because I combined XTS objects, so index would have come along.

Now, I want to split this data frame into 2 different training and testing set as below

train <- from 2015-01-01 to 2018-12-31

test < from 2019-01-01 to 2019-12-31

How can I achieve this ?


Solution

  • This is much easier if you leave your data in an xts object, not a data.frame.

    Assuming your data is still in an xts object:

    alldata_sbi <- merge(Ad(SBIN.NS),SMA50_SBI,SMA200_SBI,EMA50_SBI,EMA200_SBI,BB_SBI,
                         Momentum_SBI,MACD_SBI,RSI_SBI, ROC_SBI, WPR_SBI)
    
    train <- alldata_sbi["2015-01-01/2018-12-31"]
    test <- alldata_sbi["2019-01-01/2019-12-31"]
    
    # alternatively, you only need to specify the smallest period you need
    train <- alldata_sbi["2015/2018"]  # all obs in 2015-2018
    test <- alldata_sbi["2019"]        # all obs in 2019
    

    Now you can convert train and test to data.frames, if you need to.