R financial time series tips everyone should know about

[This article was first published on The R Trader » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

There are many R time series tutorials floating around on the web this post is not designed to be one of them. Instead I want to introduce a list of the most useful tricks I came across when dealing with financial time series in R. Some of the functions presented here are incredibly powerful but unfortunately buried in the documentation hence my desire to create a dedicated post. I only address daily or lower frequency times series. Dealing with higher frequency data requires specific tools: data.table or highfrequency packages are some of them.

xts: The xts package is the must have when it comes to times series in R. The example below loads the package and creates a daily time series of 400 days normaly distributed returns

library(xts)
myTs <- xts(rnorm(400)/100,order.by=seq(Sys.Date()-399,Sys.Date(),"days"))

merge.xts (package xts): This is incredibly powerful when it comes to binding two or more times series together whether they have the same length or not. The join argument does the magic! it determines how the binding is done

myOtherTs <- xts(rnorm(200)/100,order.by=seq(Sys.Date()-199,Sys.Date(),"days"))

# dates intersection
tsInter <- merge.xts(myTs,myOtherTs,join="inner")
# dates union and blanks filled with NAs
tsUnion <- merge.xts(myTs,myOtherTs,join="outer")

apply.yearly/apply.monthly (package xts): Apply a specified function to each distinct period in a given time series object. The example below calculates monthly and yearly returns of the second series in the tsInter object. Note that I use  the sum of returns (no compounding)

monthlyRtn <- apply.monthly(tsInter[,2], sum)
yearlyRtn <- apply.yearly(tsInter[,2], sum)

endpoints (package xts): Extract index values of a given xts object corresponding to the last observations given a period specified by on. The example gives the last day of the month returns for each series in the tsInter object using endpoint to select the date.

newTs <- allMyTs[endpoints(tsInter, on="months"),]

na.locf (package zoo): Generic function for replacing each NA with the most recent non-NA prior to it. Extremely useful when dealing with a time series with a few “holes” and when this time series is subsequently used as input for an R functions that does not accept arguments with NAs. In the example I create a time series of random prices then artificially includes a few NAs in it and replace them with the most recent value.

n <- 100
k <- 5
N <- k*n
prices <- cumsum(rnorm(N))
theSample <- sample(c(1:length(prices)),10)
prices[theSample] <- NA
prices <- na.locf(prices)

charts.PerformanceSummary (package PerformanceAnalytics): For a set of returns, create a wealth index chart, bars for per-period performance, and underwater chart for drawdown. This is incredibly useful as it displays on a single window all the relevant information for a quick visual inspection of a trading strategy. The example below turns the prices series into an xts object then displays a window with the 3 charts described above.

prices <- xts(prices,order.by=seq(Sys.Date()-(length(prices)-1),Sys.Date(),"days"))
charts.PerformanceSummary(Return.calculate(prices, method="discrete"))

The list above is by no means exhaustive but once you master the functions describe in this post it makes the manipulation of financial time series a lot easier, the code shorter and the readability of the code better.

As usual any comments welcome

To leave a comment for the author, please follow the link and comment on their blog: The R Trader » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)