library(ggplot2,forecast)
library(astsa)
library(zoo,lmtest)
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(fUnitRoots)
## Loading required package: timeDate
## Loading required package: timeSeries
## 
## Attaching package: 'timeSeries'
## The following object is masked from 'package:zoo':
## 
##     time<-
## Loading required package: fBasics
## 
## Attaching package: 'fBasics'
## The following object is masked from 'package:astsa':
## 
##     nyse
library(FitARMA)
## Loading required package: FitAR
## Loading required package: lattice
## Loading required package: leaps
## Loading required package: ltsa
## Loading required package: bestglm
library(strucchange)
## Loading required package: sandwich
library(reshape)
library(Rmisc)
## Loading required package: plyr
## 
## Attaching package: 'plyr'
## The following objects are masked from 'package:reshape':
## 
##     rename, round_any
library(fBasics)
library(tsoutliers)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(TSA)
## Registered S3 methods overwritten by 'TSA':
##   method       from    
##   fitted.Arima forecast
##   plot.Arima   forecast
## 
## Attaching package: 'TSA'
## The following objects are masked from 'package:timeDate':
## 
##     kurtosis, skewness
## The following objects are masked from 'package:stats':
## 
##     acf, arima
## The following object is masked from 'package:utils':
## 
##     tar
library(dygraphs)
library(quantmod)
## Loading required package: xts
## Loading required package: TTR
## 
## Attaching package: 'TTR'
## The following object is masked from 'package:fBasics':
## 
##     volatility
## Version 0.4-0 included new data defaults. See ?getSymbols.
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following object is masked from 'package:reshape':
## 
##     stamp
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(DT)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:lubridate':
## 
##     intersect, setdiff, union
## The following objects are masked from 'package:xts':
## 
##     first, last
## The following objects are masked from 'package:plyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
## The following object is masked from 'package:reshape':
## 
##     rename
## The following objects are masked from 'package:timeSeries':
## 
##     filter, lag
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(quantstrat)
## Loading required package: blotter
## Loading required package: FinancialInstrument
## Loading required package: PerformanceAnalytics
## 
## Attaching package: 'PerformanceAnalytics'
## The following objects are masked from 'package:TSA':
## 
##     kurtosis, skewness
## The following objects are masked from 'package:timeDate':
## 
##     kurtosis, skewness
## The following object is masked from 'package:graphics':
## 
##     legend
## Loading required package: foreach
library(xml2)
library(tidyverse)
## ── Attaching packages ───────────────────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ tibble  3.0.0     ✓ purrr   0.3.3
## ✓ tidyr   1.0.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ──────────────────────────────────────────────────────── tidyverse_conflicts() ──
## x purrr::accumulate()      masks foreach::accumulate()
## x dplyr::arrange()         masks plyr::arrange()
## x lubridate::as.difftime() masks base::as.difftime()
## x stringr::boundary()      masks strucchange::boundary()
## x purrr::compact()         masks plyr::compact()
## x dplyr::count()           masks plyr::count()
## x lubridate::date()        masks base::date()
## x tidyr::expand()          masks reshape::expand()
## x dplyr::failwith()        masks plyr::failwith()
## x dplyr::filter()          masks timeSeries::filter(), stats::filter()
## x dplyr::first()           masks xts::first()
## x dplyr::id()              masks plyr::id()
## x lubridate::intersect()   masks base::intersect()
## x dplyr::lag()             masks timeSeries::lag(), stats::lag()
## x dplyr::last()            masks xts::last()
## x dplyr::mutate()          masks plyr::mutate()
## x dplyr::rename()          masks plyr::rename(), reshape::rename()
## x lubridate::setdiff()     masks base::setdiff()
## x readr::spec()            masks TSA::spec()
## x tidyr::spread()          masks FinancialInstrument::spread()
## x lubridate::stamp()       masks reshape::stamp()
## x dplyr::summarise()       masks plyr::summarise()
## x dplyr::summarize()       masks plyr::summarize()
## x lubridate::union()       masks base::union()
## x purrr::when()            masks foreach::when()
library(tidyquant)
## ══ Need to Learn tidyquant? ══════════════════════════════════════════════════════════════════
## Business Science offers a 1-hour course - Learning Lab #9: Performance Analysis & Portfolio Optimization with tidyquant!
## </> Learn more at: https://university.business-science.io/p/learning-labs-pro </>
startdt<-  cbind("2010","-01","-01")
startdt <- paste(startdt, collapse="")
startdt
## [1] "2010-01-01"
enddt<-  cbind("2021","-01","-06")
enddt <- paste(enddt, collapse="")
enddt
## [1] "2021-01-06"
start_time <- Sys.time()
tickers<-c("^DJI","DAL","SPY","AAPL","GOOG","WB","FB","BABA","NFLX","TSLA","BILI",
           "LK","GILD","BYND","SPCE","ZM", "BA","JD","DAL","AAL","CVX","ANPDF","EDU",
           "CSCO","CCL","TTD","XOM","SCI","JBLU","LUV","RCL","SHOP",
           "TCEHY","TAL","GSX","WFC","C","MS","ALNY","BAC","UAL","PDD","COST","NCLH",
           "PPC","SNE","TSN","DELL","SAVE","JPM","JETS","LKQ","NVDA","INTC","TGT",
           "MSFT","ADSK","BAND","NIO","FSLY","NKE","TDOC","XPEV","ABNB","PTON")
ticks<-function(tick){ 
  tick<<-tick
Price<- c(tickers[tick]) %>%
    tq_get(get  = "stock.prices",
           from = startdt,
           to   = enddt) %>%
    group_by(symbol)



min_max<-function(data){
  data=timetk::tk_tbl(data, silent = TRUE)
min.close<-min(data$close)
max.close<-max(data$close)
cbind(min.close,max.close)
}

if (nrow(Price)<15) {
MinMax <- Price %>%
         tq_mutate(mutate_fun = rollapply,
                   width      = 5,
                   FUN        = min_max,
                   by.column  = FALSE,
                   col_rename = c("min", "max"))
}

if (nrow(Price)>=15 & nrow(Price)<20) {
MinMax <- Price %>%
         tq_mutate(mutate_fun = rollapply,
                   width      = 10,
                   FUN        = min_max,
                   by.column  = FALSE,
                   col_rename = c("min", "max"))
}


if (nrow(Price)<252 & nrow(Price)>=20) {
MinMax <- Price %>%
         tq_mutate(mutate_fun = rollapply,
                   width      = 20,
                   FUN        = min_max,
                   by.column  = FALSE,
                   col_rename = c("min", "max"))
}

if (nrow(Price)>=252) {
MinMax <- Price %>%
         tq_mutate(mutate_fun = rollapply,
                   width      = 252,
                   FUN        = min_max,
                   by.column  = FALSE,
                   col_rename = c("min", "max"))
}
MinMax$minRange<-MinMax$min*1.02
MinMax$downTouch <- NA
MinMax$downTouch.Low<-NA
MinMax$downTouch.Hgh<-NA

MinMax$downTouch[which(MinMax$low<=MinMax$min)]<-MinMax$low[which(MinMax$low<=MinMax$min)]
MinMax$downTouch.Low[which(MinMax$low<=MinMax$minRange)]<-MinMax$low[which(MinMax$low<=MinMax$minRange)]
MinMax$downTouch.Hgh[which(MinMax$low<=MinMax$minRange)]<-MinMax$high[which(MinMax$low<=MinMax$minRange)]


MA3D<-as.data.frame(TTR::SMA(Price$close,n=3))
colnames(MA3D)<-"SMA3D"

MA5D<-as.data.frame(TTR::SMA(Price$close,n=5))
colnames(MA5D)<-"SMA5D"


#RSI based on 200 days lookback period with simple moving average
#RSISMA<-as.data.frame(TTR:: RSI(Price$close, n=200, maType="SMA"))
#colnames(RSISMA)<-"RSI.SMA"

#RSI based on 14 days lookback period 
RSI<-as.data.frame(TTR:: RSI(Price$close,n=2))
colnames(RSI)<-"RSI"

MinMax<-as.data.frame(MinMax)
#MinMax<-cbind(MinMax, MA3D, MA5D,RSISMA,RSI)
MinMax<-cbind(MinMax, MA3D, MA5D)

MinMax<-xts(MinMax,MinMax$date)


dateWindow <<- c(startdt, enddt)

MinMax<<-MinMax
}
ticks(1)

if ( "downTouch" %in% names(MinMax)==1)  {
dygraph(MinMax[,c("close","SMA3D", "SMA5D")],main = paste0('"', tickers[tick],' 364 days min max, 3 vs.5 MA', '"'))
}
if ( "downTouch" %in% names(MinMax)==1)  {
dygraph(MinMax[,c("close","min","max","downTouch","downTouch.Low","downTouch.Hgh","SMA3D", "SMA5D")],main = paste0('"', tickers[tick],' 364 days min max, 3 vs.5 MA', '"'))%>%
    dyShading(from=startdt ,to=enddt, color="#000000")%>%
    dySeries("downTouch.Low", strokeWidth = .5, label = "TLow")%>%dySeries("downTouch.Hgh", strokeWidth = .5, label = "THgh")%>% dySeries("downTouch",strokeWidth = 4, pointSize = 4, label = "DownTouch")%>%
dySeries("close",strokeWidth = 0.5, label = "close", color="#ffffff")%>%   
dySeries("SMA3D",strokeWidth = 0.5, label = "SMA3D", color="#00ff00")%>%   
dySeries("SMA5D",strokeWidth = 0.5, label = "SMA5D", color="#ffff66")%>% 
  dyRangeSelector(dateWindow = dateWindow)%>%dyLegend(show =  "onmouseover", labelsDiv = NULL,labelsSeparateLines = FALSE, hideOnMouseOut = TRUE, width=500)
}
if ( "downTouch" %in% names(MinMax)==0)  {
dygraph(MinMax[,c("close","min","max")], main = paste0('"', tickers[tick],' 364 days min max', '"'))%>%
  dyRangeSelector(dateWindow = dateWindow)%>%dyLegend(show =  "onmouseover", labelsDiv = NULL,labelsSeparateLines = FALSE, hideOnMouseOut = TRUE, width=500)
}

"