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)
library(TSA)
## 
## 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
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## 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)
library(xml2)
library(tidyverse)
## ── Attaching packages ───────────────────────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ tibble  2.1.3     ✓ purrr   0.3.3
## ✓ tidyr   1.0.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ──────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## 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 lubridate::stamp()       masks reshape::stamp()
## x dplyr::summarise()       masks plyr::summarise()
## x dplyr::summarize()       masks plyr::summarize()
## x lubridate::union()       masks base::union()
library(tidyquant)
## 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
## ══ 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 </>
tickers<-c("^DJI","DAL","SPY","QQQ","TVIX", "UAL", "SNE",   "GOOG", "AAPL", "COST", "SBUX", "NFLX", "FB",   "MSFT", "NVDA", "RCL",  "DIS",  "BA",   "LMT",  "TSLA", "CHGG", "EDU",  "GSX",  "HD",   "SCI",  "BABA", "AMZN", "CSCO", "ROKU", "PDD",  "ADBE", "MDB",  "BILI", "SHOP", "ICE",  "IIPR", "MA",   "PYPL", "V",    "ISRG", "NVTA", "FN",   "SE",   "AMD",  "SNPS", "SQ",   "TTD",  "WIX","TPL", "SAVE", "HLT", "VRTX", "TWTR", "MRVL", "TTDKY", "MRAAY","FDX","AMAT","WB", "ANET", "WW", "QRVO", "SQ", "HEES", "SAP", "APPN", "NTNX", "QCOM", "DELL", "HUBS", "SEDG", "NTDOY", "UBER", "AMD", "PINS", "NVTA", "OKTA", "TAL", "TDOC","KO", "ABBV", "T", "MMM", "PEP", "LUV", "MRK", "ZNGA", "ATVI", "INTU", "ARCE", "DVA", "TGNA", "AVID", "JNJ", "AGN", "UNH", "CMCSA", "MU"   , "C", "JPM", "BAC", "FIS", "CRM","BMY") 

tick<-1    

                 
Price<- c(tickers[tick]) %>%
    tq_get(get  = "stock.prices",
           from = "2010-01-01",
           to   = "2020-04-10") %>%
    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)<252) {
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)]

MinMax<-xts(MinMax,MinMax$date)


dateWindow <- c("2010-01-01", "2020-04-10")


if ( "downTouch" %in% names(MinMax)==1)  {
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)
}
if ( "downTouch" %in% names(MinMax)==1)  {
dygraph(MinMax[,c("close","min","max","downTouch","downTouch.Low","downTouch.Hgh")],main = paste0('"', tickers[tick],' 364 days min max', '"'))%>%dySeries("downTouch.Low", strokeWidth = .5, label = "TLow")%>%dySeries("downTouch.Hgh", strokeWidth = .5, label = "THgh")%>% dySeries("downTouch",strokeWidth = 4, pointSize = 4, label = "DownTouch")%>%
  dyRangeSelector(dateWindow = dateWindow)%>%dyLegend(show =  "onmouseover", labelsDiv = NULL,labelsSeparateLines = FALSE, hideOnMouseOut = TRUE)
}
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)
}

## Warning in FUN(newX[, i], ...): no non-missing arguments, returning NA

## Warning in FUN(newX[, i], ...): no non-missing arguments, returning NA
## Warning in FUN(newX[, i], ...): no non-missing arguments, returning NA

## Warning in FUN(newX[, i], ...): no non-missing arguments, returning NA

## Warning in FUN(newX[, i], ...): no non-missing arguments, returning NA

## Warning in FUN(newX[, i], ...): no non-missing arguments, returning NA

## Warning in FUN(newX[, i], ...): no non-missing arguments, returning NA