IceIceIce
IceIceIce

Reputation: 5

R- programming- Error in get.current.chob() : improperly set or missing graphics device

library(quantmod)
getSymbols("LT.NS")
plot(LT.NS["2013-12-01::2014-12-01"])
close<-Cl(LT.NS["2013-12-01::2014-12-01"])
open<-Op(LT.NS["2013-12-01::2014-12-01"])
close<-as.matrix(close)
open<-as.matrix(open)
bbands<-addBBands(n=20,sd=2)
values_bbands<[email protected]
values_bbands[is.na(values_bbands)]<-0
bbands<-as.matrix(values_bbands)
up<-bbands[,1]
up<-as.matrix(up)
down<-bbands[,3]
down<-as.matrix(down)
data<-read.table("c:\\temp\\dates.txt")
attach(data)
head(data)
stock<-as.matrix(data)

for(i in 131:261)
{
    if(close[i]>down[i])
    {
    print("the selling date is:")
    print(i)
    big.red.dot <- xts(open[i], as.Date(stock[i,1]))
    points(big.red.dot, col="red", pch=19, cex=0.5  )
    }
    if(close[i]<up[i])
    {
        print("the buying date is:")
        print(i)
        big.green.dot <- xts(open[i], as.Date(stock[i,1]))
        points(big.green.dot, col="green", pch=19, cex=0.5  )
    }

}

When I run this code in R , I get "****Error in get.current.chob() : improperly set or missing graphics device"****. 2-3 times I could get an output with the proper graph with buy and sell signals indicated on the graph but now when I run the code this error gets displayed I tried it on a different version of R-1.3 too still the error appears. In my above code is bbands<-addBBands(n=20,sd=2) appropriate? Because when i run my code in individual lines the same error gets displayed for this line too. I want final output to be a graph with buy and sell points indicated at respective points.

Upvotes: 0

Views: 2771

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176668

No, bbands <- addBBands(n=20,sd=2) is not appropriate.

addBBands should be called to add Bollinger Bands to an already-existing graphics device created by chartSeries. You can also include it directly in your chartSeries call:

library(quantmod)
getSymbols("LT.NS")
chartSeries(LT.NS, TA="addBBands(n=20)", subset="2013-12-01::2014-12-01")

If you just want to calculate Bollinger Bands, just call TTR::BBands (which is what addBBands does).

bbands <- BBands(HLC(LT.NS), n=20, sd=2)

All the other stuff you're doing can be done with a couple calls to addPoints, after constructing the necessary objects to plot.

# sells
sell <- Op(LT.NS)
is.na(sell) <- which(!Cl(LT.NS) > bbands$dn)
addPoints(1:nrow(sell), sell, col='red', pch=19, cex=0.5)
# buys
buy <- Op(LT.NS)
is.na(buy) <- which(!Cl(LT.NS) < bbands$up)
addPoints(1:nrow(buy), buy, col='green', pch=19, cex=0.5)

But note that your buys and sells are not mutually exclusive.

> head(cbind(buy,sell))
           LT.NS.Open LT.NS.Open.1
2007-01-01     1445.9       1445.9
2007-01-02     1447.0       1447.0
2007-01-03     1458.0       1458.0
2007-01-04     1489.7       1489.7
2007-01-05     1500.0       1500.0
2007-01-08     1471.0       1471.0

Upvotes: 4

Related Questions