How to generate buy sell trading signals using ggplot in r

r
data_science

#1

I have made a ggplot with my data set having close price and two sets of limits(upper limit 1=ucl1,lower limit 1=lcl1,upper limit 2= ucl2, lower limit 2=lcl2) using following commands

date=seq(as.Date(‘2000-1-3’),length.out=6486,by=1)
ggplot(mrfdata,aes(x=date))+geom_line(aes(y=ucl2),colour=“blue”)+geom_line(aes(y=lcl2),colour=“blue”)+geom_line(aes(y=close),colour=“red”)+geom_line(aes(y=ucl1),colour=“green”)+geom_line(aes(y=lcl1),colour=“green”)+ggtitle(“7 days”) + xlab(“ma of 7 days”) + ylab(“standard deviation”)
library(shiny)
ui <- basicPage(
plotOutput(“zoom”, height = “350px”),
plotOutput(“overall”, height = “150px”,
brush = brushOpts(id = “brush”, direction = “x”)
)
)

server <- function(input, output){
mrfdata=data.frame(date=date,ucl2=ucl2,ucl1=ucl1,close=close,lcl1=lcl1,lcl2=lcl2)

p <- ggplot(mrfdata,aes(x=date))+geom_line(aes(y=ucl2),colour=“blue”)+geom_line(aes(y=lcl2),colour=“blue”)+geom_line(aes(y=close),colour=“red”)+geom_line(aes(y=ucl1),colour=“green”)+geom_line(aes(y=lcl1),colour=“green”)+ggtitle(“7 days”) + xlab(“ma of 7 days”) + ylab(“standard deviation”)

output$zoom <- renderPlot({``
if (!is.null(input$brush)) {
p <- p +xlim(as.Date(“1970-01-01”) + input$brush$xmin, as.Date(“1970-01-01”) + input$brush$xmax)
}
p
})

output$overall <- renderPlot§
}

shinyApp(ui, server)

Now I need to generate buy and sell trading signals using this gg plot. Buy signal whenever close price intersects lcl1 and ucl2. Sell signal whenever close price intersects ucl1 and lcl2. I have done a lot of research but as I am new to R, not able to apply commands. Any help will be appreciated.


#2

Hi @devrajan

Could you share a sample data with reproducible code?