|News||R programming language||R Bookshelf||Recommended Links||Debugging||R help system||R Debugging||An Introduction to R|
|R Packages||CRAN package repository||Quantmod package||TTR package||Zoo package||Quandl package||ggplot2 package|
|Software Fashion||Conway Law||KISS Principle||Tips||Quotes||R history||Humor||Etc|
The TTR package (author Joshua Ulrich) is a comprehensible collection of technical analysis indicators for R such as
Users will probably be most interested in the following functions:
The following sites were used to code/document this package:
data(ttrc) # Bollinger Bands bbands <- BBands( ttrc[,c("High","Low","Close")] ) # Directional Movement Index adx <- ADX(ttrc[,c("High","Low","Close")]) # Moving Averages ema <- EMA(ttrc[,"Close"], n=20) sma <- SMA(ttrc[,"Close"], n=20) # MACD macd <- MACD( ttrc[,"Close"] ) # RSI rsi <- RSI(ttrc[,"Close"]) # Stochastics stochOsc <- stoch(ttrc[,c("High","Low","Close")]) ### Note: you must have a working internet connection ### for the examples below to work! # Fetch U.S. symbols from the internet nyseSymbols <- stockSymbols("NYSE") # Fetch Yahoo! Finance data from the internet ibm <- getYahooData("IBM", 19990404, 20050607)
For a series x(t) and a given TTR, computes the return series r(t) = ln( x(t+1) / x(t) ) and the conditional return series, r(t)*s(t), where s(t) is the position indicated by the TTR i.e. s(t) = 1 for long, -1 for short, 0 for neutral
cReturns(x, ttr = "macd4", params = 0, burn = 0, short = FALSE, condition = NULL, TC = 0.001)
||The data set|
||The TTR to be used. Can be a character string for built-in TTRs, or a user defined function whose output is a position series s(t). See 'defaults' for a list of built-in TTRs.|
||Used to compute the TTR. Will be passed to a user defined function. Hence a user defined function should have at least 2 inputs, the data set and a vector or list of parameters|
||When computing the position function s(t), values for t < burn will be forced to 0, i.e. no position held during the 'burn' period|
||Logical. If false the position function s(t) will be forced to 0 when it would otherwise be -1, i.e. no short selling|
||An extra opportunity to restrict the TTR so that position is forced to 0 under some condition. Must be a binary string of the same length as the data 'x'. See 'position' for more details.|
||Trading cost, as a percentage. Used to compute an adjusted average return.|
||The conditional returns series|
||The mean one-period return, adjusted for trading costs|
||The conditional returns only during periods when long|
||The conditional returns only during periods when short|
||The conditional returns only during periods when neutral|
EXTREMELY IMPORTANT NOTE: The functions in this package evaluate past performance only. No warranty is made that the results of these tests should, or even can, be used to inform business decisions or make predictions of future events.
The author does not make any claim that any results will predict future performance. No such prediction is made, directly or implied, by the outputs of these function, and any attempt to use these function for such prediction is done solely at the risk of the end user.
David St John
William Brock, Josef Lakonishok, and Blake LeBaron. Simple technical trading rules and the stochastic properties of stock returns. The Journal of Finance, 47(5):1731-1764, 1992.
## Is the mean conditional return higher than the mean unconditional return? data(spData) mean(diff(log(spData))) cr <- cReturns(spData) mean(cr[])
TTR package has two dependencies -- zoo and xts
> install.packages("TTR") also installing the dependencies 'zoo', 'xts' trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.2/zoo_1.7-12.zip' Content type 'application/zip' length 896581 bytes (875 KB) downloaded 875 KB trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.2/xts_0.9-7.zip' Content type 'application/zip' length 660747 bytes (645 KB) downloaded 645 KB trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.2/TTR_0.22-0.zip' Content type 'application/zip' length 282375 bytes (275 KB) downloaded 275 KB package 'zoo' successfully unpacked and MD5 sums checked package 'xts' successfully unpacked and MD5 sums checked package 'TTR' successfully unpacked and MD5 sums checked The downloaded binary packages are in C:\Users\nnb\AppData\Local\Temp\RtmpMP8xNY\downloaded_packages
1. To calculate Technical Analysis with R we will be using a free open-source library called "TTR" (Technical Trading Rules). This step includes instructions for installing TTR library, assuming you already have installed R on your computer. This steps only needs to be performed once per R installation on a computer.
To install the library on your computer:
1) Start R environment on your computer, then in the menu select: Packages & Data -> Package Installer
2) In Package Installer type "TTR" in the Package Search field, and click "Get List" button.
3) Select package "TTR" and click "Install Selected".
Loading Historical Data (Input)
For demo purposes we will use daily historical prices for SPY ETF from September 2013 through May 2014. Click here to download the data file. This input file for this example was generated using IB Historical Data Downloader.
2. We are going to start off by opening R shell and loading "TTR" library, which is a free R extension that contains functions for calculating some of the most common indicators.
3. The next step is to import our data file with historical prices into R environment. We will load data from sample CSV file into R environment and store it a "data frame", which an R variable type for storing data in table format in memory.
> data = read.csv(file="spy_historical_data.txt")
To display first few rows of the "data" table:
This by default shows first 6 rows of data along with column names (table header). To see how many rows you have in the "data" table:
This shows we have 187 data records in our SPY data file, for 187 trading days between Sep 3, 2013 May 31, 2014.
We can also list table column names using "colnames" functions as follows:
4. Let's now calculate 20-day Simple Moving Average (SMA) of the CLOSE price column using TTR library's R function "SMA":
> sma20 < - SMA(data[c('CLOSE')],n=20)
Now, let's see first 50 values of the "sma20" array:
> head(sma20, n=50)
Here we used function SMA from TTR library we loaded above, telling it to calculate 20-day average (value of parameter "n"), of the "CLOSE" column from data frame "data". The function returns an array of SMA values and stores it in a new variable called "sma20".
You can bring up the help with a detailed description of the function and it's parameters using ? followed by the function name, as below. It is always a good idea to read help pages for the functions you are using, since they will list all optional parameters that you can use to tweak the output. Also, many functions have variations or related functions, which could be helpful in various circumstances and will be listed on the help page.
5. Calculating Exponential Moving Average is similarly easy, just use a different function, this time EMA(). Notice that we calculate EMA for 14-period length
6. To calculate Bollinger Bands indicator we use the BBands function. There is a number of optional parameters that it takes, so we'll provide several examples.
In the example below we call BBands passing it data frame 'data' with a query that specifies that we want to use values from 'CLOSE' column, just as we've been doing above to SMA and EMA calculations above.
Second parameter 'sd' takes the number of standard deviations for upper and lower bands. Since we don't pass value for 'n' BBands uses 20-period moving average by default.
The output contains several columns: 'dn' for "lower" band, 'mavg' for the moving average, 'up' for the "upper" band, and pctB, which quantifies a security's price relative to the upper and lower Bollinger Band, a detailed description of it can be found here.
- %B equals 1 when price is at the upper band
- %B equals 0 when price is at the lower band
- %B is above 1 when price is above the upper band
- %B is below 0 when price is below the lower band
- %B is above .50 when price is above the middle band (20-day SMA)
- %B is below .50 when price is below the middle band (20-day SMA)
> bb20 = BBands(data[c('CLOSE')], sd=2.0)
6.1 Now we'd like to create a new data frame containing all input data from the 'data' frame, plus Bollinger Bands data we just calculated.
> dataPlusBB = data.frame(data,bb20)
The data.frame() function takes any number of data frames and joins them row-wise into a new data frame, so that elements from corresponding rows are "joined" together in the result.
6.2 Bollinger Bands plot:
> lines(dataPlusBB$CLOSE, col = 'red')
> lines(dataPlusBB$up, col = 'purple')
> lines(dataPlusBB$dn, col = 'brown')
> lines(dataPlusBB$mavg, col = 'blue')
6.3 Alternatively, we can specify explicitly what type of moving average should be used as the basis for Bollinger Bands using function parameter 'maType', which simply take a moving average function name. Refer to ?SMA help page to see different types of moving averages supported in TTR library. For example, if you'd like to calculate an EMA Bollinger Bands, you can pass EMA to maType. Notice that in this example we are overriding default length parameter for moving average, using 14-period average this time.
> bbEMA = BBands(data[c('CLOSE')], sd=2.0, n=14, maType=EMA)
RSI Relative Strength Indicator
7. RSI. To calculate RSI we use the RSI() function. You can use ?RSI command in R shell to get details for the function parameters. Basically, it's very similar to the functions we used above to generate moving averages. It has two required parameters: time series (such as 'CLOSE' column from our 'data' data frame, and 'n' integer value for the "length" of the RSI indicator.
> rsi14 = RSI(data[c('CLOSE')], n=14)
Here the first parameter to RSI function is: data[c('CLOSE')], which is a statement that says "take column named 'CLOSE' from the 'data' table, and return it as a list of values, and the second parameter is n=14, where the parameter name is 'n', and the value 14 indicates that we want to calculate 14-day RSI values on the close prices.
8. The MACD function takes several arguments:
- input data series (such as 'CLOSE' price)
- number of periods for "fast" moving average
- number of periods for "slow" moving average
- number of periods for the "signal" line
You can also optionally specify moving average function you want to use for MACD moving averages. See a screenshot of the help page below (you can also use ?MACD command in R shell to open the help page yourself):
Let's calculate a standard (12,26,9) MACD indicator using this function. We'll be using standard simple moving averages, so, we'll specify SMA function in 'maType' parameter:
> macd = MACD(data[c('CLOSE')], nFast=12, nSlow=26, nSig=9, maType=SMA)
Join All Data Together
9. Now, we join all of the indicators calculated above with the original input data into a single data frame:
> allData = data.frame(data,sma20,ema14,bb20,rsi14,macd)
The data.frame() function takes any number of data frames and joins them row-wise, so that elements from corresponding rows are "glued" together in the resulting data.frame 'allData'.
Write to text file
And, finally, we write contents of 'allData' data frame to a comma-separated values file. We use write.table() function, which contains a large number of optional parameters. A detailed help page is available using command "?write.table" in R shell.
> write.table(allData, file="spy_with_indicators.csv", na="", sep=",", row.names = FALSE)
When we call write.table() function we pass the following arguments:
- allData this is simply a reference to the data frame containing data to be written to the output file.
- file = " " this is the path and name of the file we are creating.
- na = "" makes sure that cells in the data frame that contain R value "NA" will contain empty values in the output file. Some cells have NA for rows where there were not enough data to generate a corresponding indicator value (for example first 19 rows for 20-day SMA).
- sep = "," sets column separator to comma (hence comma-separated values file). To create a tab-separated file (really a preferred format for serious software systems) use: sep = "\t".
- row.names = FALSE it is important to set this value, otherwise first column in the output file will contain row numbers.
The resulting file is available here. Right-click and select "Save Linked File As " Downloaded file can be opened in Excel or text editor.
10. There are more functions and features available in the "TTR" library. You can find out more by bringing up TTR's help page:
R provides a convenient and versatile environment for data analysis and calculations. In addition to thousands of free open-source statistical, mathematical libraries and algorithms, R contains a great number of functions and libraries for reading and writing data to/from files, databases, URLs, Web Services, etc That, combined with the conciseness of the language, is a powerful combination that can help traders save precious time. Traders can significantly cut down the time required to prototype and backtest trading strategies using R. There are also methods to integrate R with mainstream programming languages such as Java and C++.
Whether you are a seasoned C++ or Java programmer or an analyst if you are serious about scientific and data-centric approach to trading R can be an extremely powerful and useful tool in your toolbox.
---- Technical Analysis in Excel: Part II MACD and RSI
Trading Geeks provides consulting in trading strategy and software development for independent traders and hedge funds. Please inquire for more information or a free quote for your project via Contact Us form on the right.
Posted in Data Analysis, Trading Tools
5 comments on "Technical Analysis with R"
Google matched content
Google matched content
|TTR-package||Functions to create Technical Trading Rules (TTR)|
|%D||Stochastic Oscillator / Stochastic Momentum Index|
|%K||Stochastic Oscillator / Stochastic Momentum Index|
|adjRatios||Split and dividend adjustment ratios|
|adjust||Split and dividend adjustment ratios|
|ADX||Welles Wilder's Directional Movement Index|
|ATR||True Range / Average True Range|
|CCI||Commodity Channel Index|
|chaikinAD||Chaikin Accumulation / Distribution|
|changes||Rate of Change / Momentum|
|CLV||Close Location Value|
|CMF||Chaikin Money Flow|
|CMO||Chande Momentum Oscillator|
|DI||Welles Wilder's Directional Movement Index|
|DPO||De-Trended Price Oscillator|
|DVI||DV Intermediate Oscillator|
|DX||Welles Wilder's Directional Movement Index|
|EMV||Arms' Ease of Movement Value|
|getYahooData||Fetch Internet Data|
|GMMA||Guppy Multiple Moving Averages|
|Guppy||Guppy Multiple Moving Averages|
|guppy||Guppy Multiple Moving Averages|
|KST||Know Sure Thing|
|MFI||Money Flow Index|
|momentum||Rate of Change / Momentum|
|moneyFlow||Money Flow Index|
|OBV||On Balance Volume (OBV)|
|PBands||Construct (optionally further smoothed and centered ) volatility bands around prices|
|PercentRank||Percent Rank over a Moving Window|
|percentRank||Percent Rank over a Moving Window|
|priceBands||Construct (optionally further smoothed and centered ) volatility bands around prices|
|ROC||Rate of Change / Momentum|
|rollFun||Analysis of Running/Rolling/Moving Windows|
|rollSFM||Analysis of Running/Rolling/Moving Windows|
|RSI||Relative Strength Index|
|runCor||Analysis of Running/Rolling/Moving Windows|
|runCov||Analysis of Running/Rolling/Moving Windows|
|runFun||Analysis of Running/Rolling/Moving Windows|
|runMAD||Analysis of Running/Rolling/Moving Windows|
|runMax||Analysis of Running/Rolling/Moving Windows|
|runMean||Analysis of Running/Rolling/Moving Windows|
|runMedian||Analysis of Running/Rolling/Moving Windows|
|runMin||Analysis of Running/Rolling/Moving Windows|
|runPercentRank||Percent Rank over a Moving Window|
|runSD||Analysis of Running/Rolling/Moving Windows|
|runSum||Analysis of Running/Rolling/Moving Windows|
|runVar||Analysis of Running/Rolling/Moving Windows|
|SMI||Stochastic Oscillator / Stochastic Momentum Index|
|stoch||Stochastic Oscillator / Stochastic Momentum Index|
|stochastic||Stochastic Oscillator / Stochastic Momentum Index|
|stochastics||Stochastic Oscillator / Stochastic Momentum Index|
|stockSymbols||Fetch Internet Data|
|TDI||Trend Detection Index|
|TR||True Range / Average True Range|
|TRIX||Triple Smoothed Exponential Oscillator|
|TTR||Functions to create Technical Trading Rules (TTR)|
|ttrc||Technical Trading Rule Composite data|
|VHF||Vertical Horizontal Filter|
|WebData||Fetch Internet Data|
|wilderSum||Analysis of Running/Rolling/Moving Windows|
|williamsAD||Williams Accumulation / Distribution|