joshuaulrich / ttr Goto Github PK
View Code? Open in Web Editor NEWTechnical analysis and other functions to construct technical trading rules with R
License: GNU General Public License v2.0
Technical analysis and other functions to construct technical trading rules with R
License: GNU General Public License v2.0
Relationship between Stochastic Oscillator and KDJ index
Stochastic Oscillator / Stochastic Momentum Index
Dear Joshua,
It is quite interesting there is no KDJ indicator in TTR. Is there any possibility to add this KDJ lines to our new TTR version.
https://docs.anychart.com/Stock_Charts/Technical_Indicators/KDJ
Thanks.
Running stoch() throws an error if the equity doesn't change in price coming from the inclusion of Inf in the calculation.
equity<-getSymbols("QTWN")
stochastic<-stoch(QTWN[,2:4],nFastK = 10,nFastD = 3)
Error in runSum(x, n) : NA/NaN/Inf in foreign function call (arg 1)
traceback()
5: runSum(x, n)
4: runMean(x, n)
3: SMA(c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.0123579821717995,
-0.474019764105834, -0.474019764105834, -0.474019764105834, -0.474019764105834,
-0.474019764105834, -0.474019764105834, -0.474019764105834, -0.474019764105834,
-0.474019764105834, -Inf, -Inf, -Inf, -Inf, -1.956, -1.956, -1.956,
-1.956, -1.956, -1.956, -1.956, -1.956, -1.956, -Inf, -Inf, -0.982666666666669,
-0.982666666666669, -0.982666666666669, -0.982666666666669, -0.982666666666669,
-0.982666666666669, -0.982666666666669, -0.982666666666669, -0.982666666666669,
-0.375290313225058, -0.375290313225058, -0.375290313225058, -0.375290313225058,
-0.387309488177193, -0.199608454382243, -0.158781208233093, -0.158781208233093,
-0.158781208233093, -0.202523184452779, -0.28688746679546, -0.28688746679546,
-0.28688746679546, -0.28688746679546, -0.761539102564105, -Inf,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -Inf, -0.0582093831450938, -0.0582093831450938, -0.0582093831450938,
-0.0582093831450938, 0.534271952575028, 0.613656449165402, 0.613656449165402,
0.613656449165402, 0.629747752971875, 0.444299390774587, 0.444299390774587,
0.444299390774587, 0.444299390774587, -0.702666666666668, 0.254946862634259,
0.254946862634259, 0.254946862634259, 0.540458867161159, 0.523601483479433,
0.250505731625085, 0.328051247471341, 0.328051247471341, 0.554164965426406,
0.219145905420991, -0.500703234880453, 0.549902768834514, 0.23564916918429,
0.23564916918429, 0.23564916918429, 0.211976846307386, 0.205314814814815,
0.205314814814815, 0.205314814814815, 0.205314814814815, 0.178185678601168,
-13.3958125000005, -13.3958125000005, -13.3958125000005, -0.724590163934427,
-0.724590163934427, -0.724590163934427, -0.724590163934427, -0.691802732240438,
-0.413576793452097, -0.413576793452097, -0.413576793452097, -0.168031295137218,
-0.034605932203391, -0.00635663841807757, -0.00635663841807757,
-0.783191384180796, -0.825564971751417, -0.472457627118648, -0.516363636363637,
-0.516363636363637, -0.516363636363637, -0.516363636363637, -0.540334855403349,
-0.540334855403349, -1.11459968602826, -1.11459968602826, -Inf,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
-Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf, -Inf,
0.755725190839694, 0.755725190839694, 0.755725190839694, 0.774961554710605,
0.718631178707225, 0.718631178707225, 0.718631178707225, 0.718631178707225,
0.718631178707225, -0.81967213114754, -1.11652542372882, -1.11652542372882,
-2.60649819494588, -20.0555555555568, -Inf, -0.564468020304564,
-0.564468020304564, -1.27512791878172, -0.871065375302667, -0.871065375302667,
-0.871065375302667, -0.871065375302667, -0.871065375302667, -0.871065375302667,
-0.871065375302667, -0.871065375302667, -1.52436440677967, -7.37948717948744,
-Inf, -Inf, -Inf, -0.632762312633836, -0.632762312633836, -0.632762312633836,
-1.52337398373983, -1.52337398373983, -1.52337398373983, -1.52337398373983,
-1.52337398373983, -1.52337398373983, 0.516198044009779, 0.516198044009779,
0.256418398533008, 0.256418398533008, 0.256418398533008, 0.256418398533008,
0.256418398533008, 0.256418398533008, 0.256418398533008, -1.79013646788991,
-1.79013646788991, -Inf, -Inf, -Inf, -Inf, -Inf, -2.02763289473682,
-2.02763289473682, -2.02763289473682, -0.00317121116043121, -0.00317121116043121,
-0.00317121116043121, -0.00317121116043121, -0.00317121116043121,
-0.00317121116043121, -0.387444514901709, -0.387444514901709,
-0.387444514901709, -2.46202531645567, -2.46202531645567, -0.816613268608415,
-0.816613268608415, -0.327724919093851, -0.32793905070119, 4.63392028487137e-07,
5.43478259497414e-07, 5.43478259497414e-07, 0.119103335318642
), n = 3)
2: do.call(maType, c(list(fastK), list(n = nFastD, ...)))
1: stoch(QTWN[, 2:4], nFastK = 10, nFastD = 3)
TTR version 0.23-2
Please see the example below. Is it a bug or something intentional?
> WMA(c(8, 8, rep(0, 10)), 3, c(6, 1, rep(0, 10)))
[1] NA NA 8 8 NaN NaN NaN NaN NaN NaN NaN NaN
> WMA(c(0.8, 0.8, rep(0, 10)), 3, c(0.6, 0.1, rep(0, 10)))
[1] NA NA 0.8 0.8 -2.0 -2.0 -2.0 -2.0 -2.0 -2.0 -2.0 -2.0
Session info -----------------------------------------------
setting value
version R version 3.2.2 (2015-08-14)
system x86_64, linux-gnu
ui RStudio (0.99.486)
language (EN)
collate en_US.UTF-8
tz <NA>
date 2015-10-13
Packages --------------------------------------------------
package * version date source
devtools 1.9.1 2015-09-11 CRAN (R 3.2.2)
digest 0.6.8 2014-12-31 CRAN (R 3.1.2)
lattice 0.20-33 2015-07-14 CRAN (R 3.2.1)
memoise 0.2.1 2014-04-22 CRAN (R 3.2.0)
rstudioapi 0.3.1 2015-04-07 CRAN (R 3.2.0)
TTR * 0.23-0 2015-07-10 CRAN (R 3.2.2)
xts 0.9-7 2014-01-02 CRAN (R 3.2.0)
zoo 1.7-12 2015-03-16 CRAN (R 3.1.3)
Hi, I found there are two errors in TTR:
EMV function returns two columns with names: 'emv' and 'maEMV'. But the documentation indicates the latter as 'emvMA'.
SNR has a bug in getting column by $:
snr <- SNR(HLC, n=10)
Error in ATR(HLC, n, ...)$atr : $ operator is invalid for atomic vectors
I might be using the dev version:
packageVersion("TTR")
[1] โ0.23.2โ
Thanks!
Submitted by: Joshua Ulrich
Assigned to: Joshua Ulrich
R-Forge link
Log into ftp.nasdaqtrader.com anonymously. Look in the directory SymbolDirectory. You'll notice two files: nasdaqlisted.txt and otherlisted.txt.
Hi there, when calculating the ALMA moving average, the resulting vector is shorter than the original data by 'n' where n is the length of the moving average..... Checking this against other moving average types, it seems to be that the ALMA resultant vector does not pad the start of the results with an NA.
HTH
Something strange seems to happen in runCov when the window is an integer and cumulative=TRUE
. For example:
data <- 1:1000
window = as.integer(100)
cov <- runCov(data, data, window, cumulative = TRUE)
window2 = 100
cov2 <- runCov(data, data, window2, cumulative = TRUE)
print(window)
tail(cov)
print(window2)
tail(cov2)
Gives the following output:
> print(window)
[1] 1000
> tail(cov)
[1] NA NA NA NA NA 83416.67
> print(window2)
[1] 100
> tail(cov2)
[1] 82585.00 82751.00 82917.17 83083.50 83250.00 83416.67
>
It looks like window
has been replaced by length(data)
. cov
only has one entry at the end whereas cov2
has all but the first 99 observations, as you would expect.
I think the culprit might be this line where n
is being updated by the Fortran routine. This updated value will be passed back to the R function and so the first 999 values are set to NA
here.
Similar things happen in the runMedian and runMAD functions.
My guess is that the as.integer()
call here is causing a copy of n
to be made in the second case which is why the answer in the second case is different. I'm not sure what the best solution is... Perhaps to take an explicit copy of n
in the Fortran routine rather than updating the variable that's passed in?
Hi,
Using the Ultimate Oscillator function on monthly data was throwing an error
require(quantmod)
getSymbols("AAPL")
AAPLm<-to.monthly(AAPL)[,1:5]
colnames(AAPLm)<-c("Open","High","Low","Close","Volume")
res<-ultimateOscillator(HLC=AAPLm[,c('High','Low','Close')],n=c(7,14,28), wts=c(4,2,1))
Error in avgs[, 1] : incorrect number of dimensions
So I changed the sapply
to lapply
in the function and it worked fine. Am I doing the right thing here?
ultimateOscillatorNew <-
function(HLC, n=c(7,14,28), wts=c(4,2,1)) {
# Ultimate Oscillator
if(length(n) != 3 || length(wts) != 3)
stop("length(n) and length(wts) must both be 3")
HLC <- try.xts(HLC, error=as.matrix)
# avoid reclassing in ATR and runSum
HLC.RECLASS <- attr(HLC, ".RECLASS")
attr(HLC, ".RECLASS") <- FALSE
# only need 'tr' and 'trueLow'
atr <- ATR(HLC, n=1)
buyPressure <- HLC[,3] - atr[,'trueLow']
avgs <- lapply(n, function(i) runSum(buyPressure, n=i)/runSum(atr[,'tr'], n=i))
# restore HLC .RECLASS attribute
attr(HLC, ".RECLASS") <- HLC.RECLASS
osc <- 100.0*(wts[1]*avgs[[1]] + wts[2]*avgs[[2]] + wts[3]*avgs[[3]]) / sum(wts)
reclass(osc, HLC)
}
Regards,
SD
I'm been investigating whether TTR::EMA works well on multidimensional (multi-column) xts objects. Eventually I called EMA on ttrc (which is a data frame, but anyway, I was just wondering what happens), and I'm consistently getting random crashes with that call. Here's my devtools::session_info()
:
Session info ----------------------------------------------------------------------------------------------------
setting value
version R version 3.2.1 (2015-06-18)
system x86_64, mingw32
ui RStudio (0.99.441)
language (EN)
collate English_United States.1252
tz Europe/Moscow
Packages --------------------------------------------------------------------------------------------------------
package * version date source
curl 0.9.2 2015-08-08 CRAN (R 3.2.1)
devtools * 1.8.0 2015-05-09 CRAN (R 3.2.1)
digest 0.6.8 2014-12-31 CRAN (R 3.2.0)
git2r 0.11.0 2015-08-12 CRAN (R 3.2.1)
lattice 0.20-33 2015-07-14 CRAN (R 3.2.1)
memoise 0.2.1 2014-04-22 CRAN (R 3.2.0)
Rcpp 0.12.0 2015-07-25 CRAN (R 3.2.1)
rstudioapi 0.3.1 2015-04-07 CRAN (R 3.2.0)
rversions 1.0.2 2015-07-13 CRAN (R 3.2.1)
TTR * 0.23-0 2015-07-10 CRAN (R 3.2.1)
xml2 0.1.1 2015-06-02 CRAN (R 3.2.1)
xts * 0.9-7 2014-01-02 CRAN (R 3.2.1)
zoo * 1.7-12 2015-03-16 CRAN (R 3.2.1)
Now, this is more or less reproducible example. I've tried ~10 times (in R, RStudio, with devel/stable version of xts), and the crash may occur on the first or the second call, but it is most likely to happen on the third.
library(TTR)
data(ttrc)
EMA(ttrc)
EMA(ttrc, 20)
EMA(ttrc, 30)
FWIW, I'm running Win 10, though sessionInfo()
says it's Running under: Windows 8 x64 (build 9200)
.
Hi Joshua
Thanks for the TTR package, it is quite helpful!
However, while calculating the moving average using SMA, I noticed some unexpected behavior
rm(list = ls())
options(digits = 10)
library(TTR)
library(xts)
floating0 <- 0.0000000000000000e+00
xts_floating <- xts(c(-1.218755021e-02,-4.729404862e-03, -4.114582223e-03,
-3.579686583e-03, -3.114327332e-03, -8.708210015e-05,
rep(floating0,9),4.0245789683433897e-02),
order.by = Sys.Date() + c(1:16))
TTR::SMA(xts_floating,5)
I am expecting the rolling average of 0s to be 0 as well, however, it returns a negative number -2.602085214e-19
instead.
SMA
2017-05-25 NA
2017-05-26 NA
2017-05-27 NA
2017-05-28 NA
2017-05-29 -5.545110242e-03
2017-05-30 -3.125016620e-03
2017-05-31 -2.179135648e-03
2017-06-01 -1.356219203e-03
2017-06-02 -6.402818864e-04
2017-06-03 -1.741642003e-05
2017-06-04 -2.602085214e-19
2017-06-05 -2.602085214e-19
2017-06-06 -2.602085214e-19
2017-06-07 -2.602085214e-19
2017-06-08 -2.602085214e-19
2017-06-09 8.049157937e-03
My session info
R version 3.3.3 (2017-03-06)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_Singapore.1252 LC_CTYPE=English_Singapore.1252 LC_MONETARY=English_Singapore.1252 LC_NUMERIC=C
[5] LC_TIME=English_Singapore.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] xts_0.9-7 zoo_1.7-14 TTR_0.23-1
loaded via a namespace (and not attached):
[1] tools_3.3.3 Rcpp_0.12.9 grid_3.3.3 roll_1.0.6 RcppParallel_4.3.20 lattice_0.20-34
The OBV function currently treats the no-price-change condition (Close[t] == Close[t-1]
) the same as if the price change were negative. This is not the same as several references:
The calculations in the above references are the same as these references in ?OBV
:
Note that the Linnsoft reference in ?OBV
is consistent with the current implementation, and that the StockCharts link in ?OBV
is dead.
Thanks to Anฤฑl รalฤฑลkan for the report.
Submitted by: Mirko Fit
Assigned to: Joshua Ulrich
R-Forge link
The implementation of the detrended price oscillator looks into the future by shifting moving averages backwards.
Why this is problematic:
1.) The current values of DPO contain information about the future
-> I used genetic programming to find trading rules in forex markets and
found a lot of unrealisticly successful trading rules with that approach.
By now it looks like the future information within DPO made it easy
to find trading rules with high forecasting abilities.
2.) It is impossible to use it in an event based system, as the information of future MA values is not available at calculation time
From my point of view, every indicator that produces n/a values at the end of the time series, may contain future information and is therefore not practically usable.
In case of the DPO, a hotfix could be to shift the final result forward by 'shift' (option).
The most clean I can imagine is to implement it via some buffer (like shift registers in hardware). One would create a buffer of size 'shift' and store the past prices in there. When the new value of DPO is calculated, one can substract the MA value from the price of 'shift' periods ago.
Followups:
Date: 2013-02-24 23:59
Sender: Joshua Ulrich
This isn't a bug; it's how the indicator is calculated. See the references below:
http://www.fmlabs.com/reference/DPO.htm
http://www.equis.com/Customer/Resources/TAAZ/?c=3&p=48
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:detrended_price_osci
In the documentation I did not find a parameter to move the NA to the end.
Is there one around?
> kurs <- c(1,2,3,4,5,6)
> sma3<-SMA(kurs,n=3)
> sma3
[1] NA NA 2 3 4 5
>
Default output NA NA 2 3 4 5
With additional parameter the output changes to 2 3 4 5 NA NA
Submitted by: Evelyn Mitchell
Assigned to: Joshua Ulrich
R-Forge link
ma in docs should be mavg
--- bollingerBands.Rd.orig 2012-06-18 19:08:34.477045035 -0600
+++ bollingerBands.Rd 2012-06-18 19:10:42.277048079 -0600
@@ -31,7 +31,7 @@
A object of the same class as \code{HLC} or a matrix (if \code{try.xts}
fails) containing the columns:
\item{ dn }{ The lower Bollinger Band. }
Followups:
Date: 2013-02-25 00:06
Sender: Joshua Ulrich
Fixed as of revision 148. Thanks!
Submitted by: Sarvesh S G
Assigned to: Joshua Ulrich
R-Forge link
add line
clv[is.infinite(clv)] <- 0 in CLV function
Followups:
Date: 2014-09-19 11:32
Sender: Joshua Ulrich
Changing to accepted. Fixed in r178. Issue arose when H == L, but H != C and L != C due to machine precision. In that case, division of a non-zero number by zero occurs, which results in +/-Inf.
Date: 2014-09-17 23:58
Sender: Joshua Ulrich
Reproducible example given by Sarvesh via email is attached in TTR_CLV_Inf.R. Issue that creates Inf values only occurs when you pass more than the 3 HLC columns to CLV. Closing/rejecting as an unnecessary change.
if( isTRUE(mean0) ) {
# This is an alternative SD calculation using an effective mean of 0
s <- sqrt(N) * sqrt(runSum(r^2, n-1) / (n-2))
} else {
# This is the standard SD calculation using the sample mean
s <- sqrt(N) * runSD(r, n-1)
}
runSD(r, n-1)
- why do we compute the SD using n-1
bars? runSD already computes the SD of the mean (the default for the "sample" parameter is TRUE
). I suspect that the formula in the mean0=TRUE
case has similar issue - the n-2
looks suspicious.
Hi Joshua, I found a bug in the TRIX function. If the "maType" is not a list variable, the "nSig" parameter will not be used when calculating the signal value from the TRIX value. Instead, the "n" parameter will be used as the "nSig" parameter.
Some of the code as bellow:
if (is.list(maType)) { signal <- do.call(maType[[4]][[1]], c(list(TRIX), maType[[4]][-1])) } else { signal <- do.call(maType, c(list(TRIX), list(n = n, ...))) }
The correct code might be:
if (is.list(maType)) { signal <- do.call(maType[[4]][[1]], c(list(TRIX), maType[[4]][-1])) } else { signal <- do.call(maType, c(list(TRIX), list(n = nSig, ...))) }
it seems for each iteration of i, this line always uses d_xl[1] and d_xl[0], should it be d_xl[i] and d_xl[i-1]? Thank you.
Package TTR version 0.23-1
If I do SMA with n=1 then the first number gets replaced with NA
Sample
kurs
[1] 1 2 3 4
> sma1 <- SMA(kurs,n=1)
> sma1
[1] NA 2 3 4
Expected result 1 2 3 4
> kurs <- ts(kurs)
> kurs
Time Series:
Start = 1
End = 4
Frequency = 1
[1] 1 2 3 4
> sma1 <- SMA(kurs,n=1)
> sma1
Time Series:
Start = 1
End = 4
Frequency = 1
[1] NA 2 3 4
I hope to calculate weekly or monthly MACD, therefore, I need a function to transfer daily data to weekly or monthly data and then to calculate MACD. However, it seem I am not familiar with โxtsโ object. and Hope Joshua could give some help.
daily2week<-function(Object){
Object1<-split(na.omit(Object),rep(1:round(nrow(na.omit(Object))/7),each = 7))
Open=unlist(lapply(Object1,function(x) unlist(x[1,1])))
High=unlist(lapply(Object1,function(x) max(unlist(x[,2]))))
Low=unlist(lapply(Object1,function(x) max(unlist(x[,2]))))
Close=unlist(lapply(Object1,function(x) max(unlist(x[,2]))))
Volume=unlist(lapply(Object1,function(x) max(unlist(x[,2]))))
output<-data.frame(Open,High,Low,Close,Volume)
return(output)
}
Thanks.
Hi, Joshua!
Please, see below:
library(TTR)
data(ttrc)
Error in force(Symbols) : object 'ttrc' not found
What's wrong?
Test=stockSymbols()
Fetching AMEX symbols...
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") : InternetOpenUrl failed: 'The operation timed out'
Hi for last two days (started April 17, 2017) the TTR::getYahooData
returns the following errors
> getYahooData("IBM", 19990404, 20050607)
Error in file(file, "rt") : cannot open the connection
There is absolutely no issue with my internet.
My TTR package version is 0.23-1
and R version is 2.15.2
I'd very much appreciate if someone takes a quick look and fix. This get function has been working daily for last 5 years.
Thanks
It may be helpful for debugging if the two conditions here were separated:
if( n < 1 || n > NROW(x) ) stop("Invalid 'n'")
For example:
if( n < 1 ) stop("n, Number of rows of data, 0 or negative.")
# If possible, give the actual n.
if( n > NROW(X) ) stop("Requested n greater than the length of provided data.")
# If possible give the actual n, and the comparison NROW(x), and x.
Hi,
Firstly, thanks for the TTR package, it is very useful. I written a code to compute various TTRs and output the results into a nice excel file. For the SMA
, EMA
, WMA
, the code works fine. However, when I try to use the HMA
, I keep getting the following error:
Error in WMA(x, n=n/2,...):
Length of 'wts' must equal the length of 'x' or 'n'
My code is:
short = HMA(z_data,n_short)
long = HMA(z_data,n_long)
Where z_data
is a price series while n_short
and n_long
are parameters between two values specified in the code. So to confirm, when the HMA
is changed to SMA
/WMA
/EMA
, the code works fine. I have added other inputs to the code such as: short = HMA(z_data,n_short,500)
and short = HMA(z_data,n_short,"length of data")
, but the error remains.
I think I am missing something pretty simple. Any ideas most welcome.
Many thanks.
If I am reading the code correctly, it's sd over the Hi - Lo series. That's forward looking in a way.
Internal Bar Strength (IBS) is a mean-reversion indicator described in a couple posts on the QUSMA blog.
The calculation is IBS = (Close - Low) / (High - Low)
, which equivalent to a 1-period stochastic oscillator with no smoothing. For example:
getSymbols("SPY")
IBS <- (Cl(SPY)-Lo(SPY))/(Hi(SPY)-Lo(SPY))
ibs <- stoch(HLC(SPY), 1)
sum(ibs$fastK - IBS, na.rm=TRUE) # 0 (or close to it)
Please add the Vortex Indicator ( http://www.vortexindicator.com/VFX_VORTEX.PDF )
Thank you.
Submitted by: ivan popivanov
Assigned to: Joshua Ulrich
R-Forge link
(A copy of my email sent to the maintainer)
Hello,
Let me first outline the 'problem' I see with the TTR::DVI indicator:
library(quantmod)
spy=getSymbols('SPY', from='1900-01-01', auto.assign=FALSE)
spy.dvi.all = DVI(Cl(spy))
spy.dvi = DVI(Cl(spy)['2011-01-01'])
spy.dvi.all['2012-01']
spy.dvi['2012-01']
The values for month of January are different. The reason is that when the rolling pctRank is performed on the 2011+ set, there are NAs in the mag and str vectors so the function ends up with different rankings.
In my opinion, we should start the computations later, when there are no NAs in the mag and str vector for the lookup period (defined by n). Please see the attachment for an illustration of the idea.
Regards,
Ivan
Followups:
Date: 2013-04-19 03:32
Sender: Joshua Ulrich
Replaced pctRank function with runPercentRank.
Column name for RSI is labelled EMA
Probably just after line 131, just needs to re-label
131 rsi <- 100 * mavgUp / ( mavgUp + mavgDn )
132 colnames(rsi) <- "rsi"
133
134 reclass( rsi, price )
Column is labelled "rsi"
> tail( RSI( Cl( xtsclean[[1]]) ))
EMA
2017-10-11 40.84447
2017-10-12 38.99656
2017-10-16 33.31531
2017-10-17 30.57424
2017-10-19 26.46984
2017-10-20 23.55141
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils
[5] datasets methods base
other attached packages:
[1] quadprog_1.5-5 e1071_1.6-8 ranger_0.8.0
[4] caret_6.0-77 lattice_0.20-35 lubridate_1.6.0
[7] plotly_4.7.1 scales_0.5.0 cowplot_0.8.0
[10] gridExtra_2.3 RcppRoll_0.2.2 dplyr_0.7.4
[13] ggplot2_2.2.1 quantmod_0.4-11 TTR_0.23-2
[16] xts_0.10-0 zoo_1.8-0 pacman_0.4.6
loaded via a namespace (and not attached):
[1] httr_1.3.1 ddalpha_1.3.1
[3] tidyr_0.7.2 sfsmisc_1.1-1
[5] jsonlite_1.5 viridisLite_0.2.0
[7] splines_3.4.0 foreach_1.4.3
[9] prodlim_1.6.1 assertthat_0.2.0
[11] stats4_3.4.0 DRR_0.0.2
[13] yaml_2.1.14 robustbase_0.92-7
[15] ipred_0.9-6 glue_1.1.1
[17] digest_0.6.12 colorspace_1.3-2
[19] recipes_0.1.0 htmltools_0.3.6
[21] Matrix_1.2-11 plyr_1.8.4
[23] timeDate_3012.100 pkgconfig_2.0.1
[25] CVST_0.2-1 purrr_0.2.4
[27] gower_0.1.2 lava_1.5.1
[29] tibble_1.3.4 withr_2.0.0
[31] nnet_7.3-12 lazyeval_0.2.0
[33] survival_2.41-3 magrittr_1.5
[35] nlme_3.1-131 MASS_7.3-47
[37] dimRed_0.1.0 class_7.3-14
[39] tools_3.4.0 data.table_1.10.4-2
[41] stringr_1.2.0 kernlab_0.9-25
[43] munsell_0.4.3 bindrcpp_0.2
[45] compiler_3.4.0 rlang_0.1.2
[47] grid_3.4.0 iterators_1.0.8
[49] htmlwidgets_0.9 gtable_0.2.0
[51] ModelMetrics_1.1.0 codetools_0.2-15
[53] curl_3.0 reshape2_1.4.2
[55] R6_2.2.2 bindr_0.1
[57] stringi_1.1.5 Rcpp_0.12.13
[59] rpart_4.1-11 DEoptimR_1.0-8
When the code below is run using TTR_0.22-0, the colnames are: c("dvi.mag", "dvi.str", "dvi")
. When run using TTR_0.23-0, the colnames are: c("..1", "..2", "..3")
.
require(TTR)
data(ttrc)
d <- setNames(ttrc$Close, ttrc$Date)
colnames(dvi <- DVI(d))
It appears the cause is due to the change in #2. The affected call is:
reclass(cbind(dvi.mag, dvi.str, dvi), price)
In 0.22-0, dvi.mag
, dvi.str
, and dvi
were all simple vectors. In 0.23-0, dvi.mag
is a matrix with row names indicating datetimes, while dvi.str
and dvi
are both xts objects. None of these objects have column names, which is likely what causes cbind.xts
/merge.xts
not to deparse the object names for column names on the new object.
Thanks to @ivannp for the report, and to @jjphorn for the reminder.
Dear Joshua,
While scanning some stocks I encountered a problem with the TTR::BBands
function, which I use in connection with HLC()
. The problem occurs with tickers containing the letter sequence LOW (such as NYSE:LOW and NYSE:PLOW). Maybe the code gets confused by the multiple occurrence of "low" in the column names while searching for the low of the price.
Here is an example:
library(quantmod)
library(TTR)
issue <- getSymbols("LOW", src="yahoo", auto.assign=FALSE)
BBands(HLC(issue))
The last command leads to the following error:
"Error in BBands(HLC(issue)) :
Price series must be either High-Low-Close, or Close/univariate."
I'm not sure if the problem arises from HLC()
or from BBands()
, although I suspect that the former might be the culprit. Maybe it helps to point out that, for example,
ADX(HLC(issue))
does not throw any error.
I'm using TTR version 0.23-0, quantmod version 0.4-5 and R version 3.2.2 on ubuntu 14.04.
Thanks for looking into this.
Cheers,
Riccardo
on line 10 of the function:
obv <- c(volume[1], ifelse(prChg > 0, volume, -volume)[-1])
in the case that both price and volumn argument is a numeric vector, volume[1] will return an 2d xts object but ifelse will return a numeric vector, which will return error if you combine them using c()
growth() returns NA for all values because growth <- cumprod(1 + ROC(price, ...) * signals) and ROC() returns an NA for the first value in a series. cumprod cannot handle the NA and returns NAs for everything.
Example:
IBM <- getYahooData('IBM')$Open
growth(IBM, rep(1, nrow(IBM)))
Error in library.dynam(lib, package, package.lib) :
DLL 'TTR' not found: maybe not installed for this architecture?
Error: loading failed
Execution halted
ERROR: loading failed
Exited with status 1.
The way of calculating DPO: Detrended Price Oscillator is confusing!
For Simple Moving Average, if I have a series
v <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
ma <- TTR::SMA(v, n=5)
NA NA NA NA 3 4 5 6 7 8
It is calculated by rolling mean from 1:5 -> 5:10
However, when I do DPO, it gives
TTR::DPO(v,n=5)
NA -1 -1 -1 -1 -1 -1 NA NA NA
It is calculated by: v[1:7] - ma[4:10], shifted by (n/2+1=3)
It uses current price to substract future moving average.
The correct way is: v[4:10] - ma[1:7], using current price to substract previous moving average, and the results should be:
NA NA NA NA NA NA NA 5 5 5
A real example here using TTR::SMA and TTR::DPO:
Date Close MA5 DPO5
1 2017-05-30 0.7465 NA NA
2 2017-05-31 0.7430 NA -0.00098
3 2017-06-01 0.7374 NA -0.00740
4 2017-06-02 0.7443 NA -0.00288
5 2017-06-05 0.7487 0.74398 -0.00194
6 2017-06-06 0.7506 0.74480 -0.00172
7 2017-06-07 0.7549 0.74718 0.00150
8 2017-06-08 0.7547 0.75064 0.00068
9 2017-06-09 0.7527 0.75232 -0.00204
10 2017-06-12 0.7541 0.75340 -0.00128
11 2017-06-13 0.7537 0.75402 -0.00356
12 2017-06-14 0.7585 0.75474 0.00006
13 2017-06-15 0.7579 0.75538 -0.00140
14 2017-06-16 0.7621 0.75726 0.00344
15 2017-06-19 0.7600 0.75844 0.00208
16 2017-06-20 0.7580 0.75930 0.00114
17 2017-06-21 0.7553 0.75866 -0.00126
18 2017-06-22 0.7542 0.75792 NA
19 2017-06-23 0.7568 0.75686 NA
20 2017-06-26 0.7585 0.75656 NA
This looks into future.
It's possible for a user to specify a center
argument that has more NA
than the number of NA
in x
+ n - 1
. This can even happen internally, for example with CCI
:
R> require(TTR)
R> data(ttrc)
R> cci <- CCI(ttrc$Close, maType="DEMA")
Error in runMAD(HLC, n, center = mavg, stat = "mean") :
NA/NaN/Inf in foreign function call (arg 2)
This is because DEMA
has more NA
than n
, due to double-smoothing.
R> dema <- DEMA(ttrc$Close, n=10)
R> runMAD(ttrc$Close, n=10, center=dema)
Error in runMAD(ttrc$Close, n = 10, center = dema) :
NA/NaN/Inf in foreign function call (arg 2)
R> sum(is.na(dema))
[1] 18
One possible solution is to set NAs
to max(sum(is.na(x)), sum(is.na(center)))
when center
is user-specified. Note that we should also check for non-leading NA
in center, as we do for
x`.
Submitted by: remy dodgier
Assigned to: Nobody
R-Forge link
It would be nice to have ichimoku cloud indicators in TTR.
Followups:
Date: 2015-01-25 19:17
Sender: Brian Peterson
Ilya Kipnis has implemented the ichimoku indicator, and has it on github here:
https://github.com/IlyaKipnis/IKTrading/blob/master/R/ichimoku.R
I have not tested it, but I hope it helps you out. - Brian
In the code it seems that n
for ADX
calculation is the same as n
for DX
calculation.
maArgs <- list(n = n, ...)
Should we separate these 2? If we change here, we should probably change in addADX
as well.
Is it just me or are MESA MAMA and FAMA averages not available for TTR? I'm in the process of switching a python project that uses TA-Lib to R using TTR and I can't find the MESA function.
It seems like there is an error, or unintended behavior, in WMA in the situation where NROW(wts)==n is true.
That's because:
if( NROW(wts) == n ) {
275
276 x <- na.omit(x)
You remove all na's from the data input and then calculate ma on x.
However, when you then call reclass(ma,x) after the ma is calculated, ma and x are of different length in the situation where x contained na. I think that means reclass will never succeed in that situation. Agree? If so, is there a reason for that, or is it just an situation that hasn't come up?
Hello,
I'm running the function stockSymbols(), but opposed to previous runs, today I simply don't get the data of IPOyear, Sector and Industry. It all returns NA.
Thanks!
Eran
I am having trouble pulling in data from Excel into T and calculating OHLC volatility using TTR. I am using the following code (I have also attached the code for your review).
The output generated by volatility(ohlc, calc="gk.yz")
is downward sloping... almost like a decay function. It looks completely wrong when I compare it to the data pulled from Yahoo Finance. Am I doing something wrong with how I am pulling the data? Appreciate any help or advice you could offer.
Best,
Stephen
Using the following packages: quantmod, xlsx, xts, zoo.
##R Code to pull data from Bloomberg/Excel & use quantmod/TTR
x=read.xlsx("Test OHLC Data.xlsx",sheetIndex=1)
x
x[1:756,1:5]
X=x[1:756,1:5]
X
summary(X)
typeof(X)
typeof(X$Open)
is.numeric(X$Open)
is.na(X)
str(X)
xts(X[,-1],order.by=X$NA.)
NewX=xts(X[,-1],order.by=X$NA.)
chartSeries(NewX)
is.OHLC(NewX)
has.Vo(NewX)
OHLC(NewX)
Op(NewX) ##Test - brings open data
Cl(NewX) ##Test - brings close data
HiCl(NewX) ##Test - brings in % change from Hi Low
plot(HiCl(NewX),type='l')
mean(HiCl(NewX))
ohlc = OHLC(NewX)
ohlc
volatility(ohlc,calc="garman")
IntraVol1=volatility(ohlc,calc="garman")
volatility(ohlc,calc="gk.yz")
IntraVol2=volatility(ohlc,calc="gk.yz")
The MFI
unit test in TTR fails when R is run under valgrind because the result of rowMeans
is slightly different when R is run under valgrind. Specifically:
> # R --vanilla
> library(TTR)
> data(ttrc)
> x <- rowMeans(ttrc[,c("High","Low","Close")])
> sprintf("%21.20f %21.20f", x[62], x[63])
[1] "3.38333333333333330373 3.38333333333333330373"
> sprintf("%21.20f %21.20f %21.20f", ttrc[62,"High"], ttrc[62,"Low"], ttrc[62,"Close"])
[1] "3.41000000000000014211 3.35999999999999987566 3.37999999999999989342"
> # R --vanilla -d "valgrind"
> library(TTR)
> data(ttrc)
> x <- rowMeans(ttrc[,c("High","Low","Close")])
> sprintf("%21.20f %21.20f", x[62], x[63])
[1] "3.38333333333333285964 3.38333333333333330373"
> sprintf("%21.20f %21.20f %21.20f", ttrc[62,"High"], ttrc[62,"Low"], ttrc[62,"Close"])
[1] "3.41000000000000014211 3.35999999999999987566 3.37999999999999989342"
This causes x[63] > x[62]
to be TRUE
under valgrind when it's FALSE
when running R without valgrind.
Prof Ripley explains the differences as,
One possible reason is that there will be more stores to memory and so the extended precision of x86_64 CPUs will be used less. I can confirm that via the use of flag -ffloat-store in gcc/gfortran...
A couple members of the CRAN team suggest having a tolerance for the logical comparison. While that would solve this specific issue, it wouldn't prevent a similar issue from occurring via a different logical comparison in another function. That would require adding a tolerance to all logical comparisons, which would be onerous.
The MFI
unit test that fails under valgrind will succeed if the call to rowMeans(HLC)
is replaced by a call to apply(HLC, 1, mean)
. rowMeans
is also used in bollingerBands
and CCI
.
I use R 3.1.2 and recently upgraded TTR from 0.22 to 0.23. However, now when I load TTR, xts/zoo are not automatically imported. Any clue? Thanks!
FIrst of all. Big thanks for TTR!
I've noticed a difference in GMMA
from old version to new version of TTR (or other updated part of my R setup...)
This used to work:
library(quantmod)
library(TTR)
getSymbols("^GSPC")
candleChart(GSPC, theme="white" , subset="last 5 months", TA=NULL)
# Line below is not working in new versions
addTA(GMMA(Cl(GSPC)),col=c(rep(c('blue','red'),each=6)), on=1)
But doesn't work on my new setup. I get this error:
Error in array(r, dim = d, dimnames = if (!(is.null(n1 <- names(x[[1L]])) & :
length of 'dimnames' [1] not equal to array extent
After digging around I've settled on this instead for my new setup. I'm switching to data.frame as this is what the ttrc
object is in example in the reference manual.
library(quantmod)
library(TTR)
getSymbols("^GSPC")
candleChart(GSPC, theme="white" , subset="last 5 months", TA=NULL)
GSPC.DF <- as.data.frame(GSPC)
GSPC.DF.GMMACL <- GMMA(GSPC.DF[,"GSPC.Close"])
addTA(GSPC.DF.GMMACL,col=c(rep(c('blue','red'),each=6)), on=1)
Am I thinking wrong or is there something in column naming or such I must adhere to in new version of TTR, as I suppose TTR is still working with xts?
Old system (don't laugh please):
> sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: i386-apple-darwin9.8.0/i386 (32-bit)
locale:
[1] C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] quantmod_0.3-17 TTR_0.21-1 xts_0.8-6 zoo_1.7-7
[5] Defaults_1.1-1
loaded via a namespace (and not attached):
[1] grid_2.15.0 lattice_0.20-6
New system:
> sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.5 (Yosemite)
locale:
[1] C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] quantmod_0.4-5 TTR_0.23-0 xts_0.9-7 zoo_1.7-12
loaded via a namespace (and not attached):
[1] coin_1.1-2 lattice_0.20-33 codetools_0.2-14 mvtnorm_1.0-3
[5] grid_3.2.3 stats4_3.2.3 multcomp_1.4-1 strucchange_1.5-1
[9] party_1.0-25 sandwich_2.3-4 splines_3.2.3 TH.data_1.0-6
[13] tools_3.2.3 survival_2.38-3 modeltools_0.2-21
Big thanks!
I'm proposing an extension to the Cl/Cl volatility estimator so that there's a version that effectively uses a fixed mean of 0 rather than the sample mean. For the case of small n with a strongly trending underlying, the sample mean can be skewed resulting in an underestimation of volatility.
I have working code and can submit a pull request if you're agreeable to extending your function. One question is the best way to select this functionality via the command-line arguments. One possibility is via the "calc"
argument. This method could be designated as "mean0"
or "close0"
. Alternatively, an additional command line argument could be added to the function such as mean0 = TRUE
.
Your thoughts? Thanks.
References:
Column name for Parabolic SAR is unnamed
Probably after line 84, just needs the colnames:
83 # Call C routine
84 sar <- .Call("sar", HL[,1], HL[,2], accel, initGap, PACKAGE = "TTR")
85 colnames(sar) <- "sar"
86
87 reclass( sar, HL )
***sorry, noob here. don't want to break anything
Column is labelled "sar"
> tail( SAR(xtsclean[[1]]))
[,1]
2017-10-11 9.733589
2017-10-12 9.718902
2017-10-16 9.705390
2017-10-17 9.686851
2017-10-19 9.662029
2017-10-20 9.629545
R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils
[5] datasets methods base
other attached packages:
[1] quadprog_1.5-5 e1071_1.6-8 ranger_0.8.0
[4] caret_6.0-77 lattice_0.20-35 lubridate_1.6.0
[7] plotly_4.7.1 scales_0.5.0 cowplot_0.8.0
[10] gridExtra_2.3 RcppRoll_0.2.2 dplyr_0.7.4
[13] ggplot2_2.2.1 quantmod_0.4-11 TTR_0.23-2
[16] xts_0.10-0 zoo_1.8-0 pacman_0.4.6
loaded via a namespace (and not attached):
[1] httr_1.3.1 ddalpha_1.3.1
[3] tidyr_0.7.2 sfsmisc_1.1-1
[5] jsonlite_1.5 viridisLite_0.2.0
[7] splines_3.4.0 foreach_1.4.3
[9] prodlim_1.6.1 assertthat_0.2.0
[11] stats4_3.4.0 DRR_0.0.2
[13] yaml_2.1.14 robustbase_0.92-7
[15] ipred_0.9-6 glue_1.1.1
[17] digest_0.6.12 colorspace_1.3-2
[19] recipes_0.1.0 htmltools_0.3.6
[21] Matrix_1.2-11 plyr_1.8.4
[23] timeDate_3012.100 pkgconfig_2.0.1
[25] CVST_0.2-1 purrr_0.2.4
[27] gower_0.1.2 lava_1.5.1
[29] tibble_1.3.4 withr_2.0.0
[31] nnet_7.3-12 lazyeval_0.2.0
[33] survival_2.41-3 magrittr_1.5
[35] nlme_3.1-131 MASS_7.3-47
[37] dimRed_0.1.0 class_7.3-14
[39] tools_3.4.0 data.table_1.10.4-2
[41] stringr_1.2.0 kernlab_0.9-25
[43] munsell_0.4.3 bindrcpp_0.2
[45] compiler_3.4.0 rlang_0.1.2
[47] grid_3.4.0 iterators_1.0.8
[49] htmlwidgets_0.9 gtable_0.2.0
[51] ModelMetrics_1.1.0 codetools_0.2-15
[53] curl_3.0 reshape2_1.4.2
[55] R6_2.2.2 bindr_0.1
[57] stringi_1.1.5 Rcpp_0.12.13
[59] rpart_4.1-11 DEoptimR_1.0-8
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.