library(quantmod)
## Warning: package 'quantmod' was built under R version 3.5.3
## Loading required package: xts
## Loading required package: zoo
## Warning: package 'zoo' was built under R version 3.5.3
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: TTR
## Version 0.4-0 included new data defaults. See ?getSymbols.
library(stargazer)
## 
## Please cite as:
##  Hlavac, Marek (2018). stargazer: Well-Formatted Regression and Summary Statistics Tables.
##  R package version 5.2.2. https://CRAN.R-project.org/package=stargazer
library(MASS)
## Warning: package 'MASS' was built under R version 3.5.3
library(fPortfolio)
## Warning: package 'fPortfolio' was built under R version 3.5.3
## Loading required package: timeDate
## Loading required package: timeSeries
## 
## Attaching package: 'timeSeries'
## The following object is masked from 'package:zoo':
## 
##     time<-
## Loading required package: fBasics
## Warning: package 'fBasics' was built under R version 3.5.3
## 
## Attaching package: 'fBasics'
## The following object is masked from 'package:TTR':
## 
##     volatility
## Loading required package: fAssets
library(forecast)
## Warning: package 'forecast' was built under R version 3.5.3
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 3.5.3
startDate = as.Date("2001-01-01") #Specify period of time we are interested in
endDate = as.Date("2019-06-20") 
getSymbols('GDX',src='yahoo',from = startDate, to = endDate)
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
## 
## This message is shown once per session and may be disabled by setting 
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
## [1] "GDX"
#quantmod default chart.
chartSeries(GDX)

GDXreturns<-dailyReturn(GDX,type='log')
# PLOTS
# Plot 1: Histogram
#h <- hist(GDXreturns,
#        prob = TRUE,  # Flipside of "freq = FALSE"
#        main = "GDX Returns Histogram")
x = GDXreturns

tmp <- density(x)
truehist(GDXreturns, prob = TRUE, ylim = c(0, max(tmp$y)),main = "GDX Returns Histogram")

# Plot 2: Normal curve (if prob = TRUE)
curve(dnorm(x, mean = mean(GDXreturns), sd = sd(GDXreturns)), 
      col = "red", 
      lwd = 3,
      add = TRUE)
curve( dt(x, df=15), add=TRUE, col='blue' )
lines(density(GDXreturns, adjust = 2), lwd = 2, col = "Blue")

#creates a frequency table from GDX data 
factorx <- factor(cut(GDXreturns, breaks=nclass.Sturges(GDXreturns)))
#TGDXulate and turn into data.frame
xoutGDX <- as.data.frame(table(factorx))
#Add cumFreq and proportions
xoutGDX <- transform(xoutGDX, cumFreq = cumsum(Freq), relative = prop.table(Freq))
# regression library which outputs nice simple rounded row summary data alernative to summarry command
library(stargazer)
summary(GDXreturns)
##      Index            daily.returns       
##  Min.   :2006-05-22   Min.   :-1.688e-01  
##  1st Qu.:2009-08-26   1st Qu.:-1.413e-02  
##  Median :2012-12-03   Median :-8.223e-05  
##  Mean   :2012-12-03   Mean   :-1.275e-04  
##  3rd Qu.:2016-03-11   3rd Qu.: 1.394e-02  
##  Max.   :2019-06-19   Max.   : 2.354e-01
stargazer(GDXreturns,type = "text",summary = TRUE)
## 
## ===================================================================
## Statistic       N    Mean   St. Dev.  Min   Pctl(25) Pctl(75)  Max 
## -------------------------------------------------------------------
## daily.returns 3,292 -0.0001  0.026   -0.169  -0.014   0.014   0.235
## -------------------------------------------------------------------
library(fPortfolio)
#write.csv(GDXreturns, file = "181223GDXreturns.csv")
#fportfolio Cvar calc
cv = cvarRisk(GDXreturns,1,alpha = .01)
cv
##     CVaR.1% 
## -0.09506055
#write.csv(xoutGDX,file = "GDX_freq231218.csv")
#last GDX data
endGDX = last(GDX)
endGDX
##            GDX.Open GDX.High GDX.Low GDX.Close GDX.Volume GDX.Adjusted
## 2019-06-19    23.52    24.03   23.45        24   46225800           24
#Cvar drawdown estimate
Potential_Avalanche = endGDX[,6]*cv
Potential_Avalanche
##            GDX.Adjusted
## 2019-06-19    -2.281453
#worst Cvar drawdown outcome estimate
Possible_Worst_case = endGDX[,6]+Potential_Avalanche
Possible_Worst_case
##            GDX.Adjusted
## 2019-06-19     21.71855
library(pracma)
## Warning: package 'pracma' was built under R version 3.5.3
## 
## Attaching package: 'pracma'
## The following objects are masked from 'package:fBasics':
## 
##     akimaInterp, inv, kron, pascal
hurstexp(GDXreturns)
## Simple R/S Hurst estimation:         0.5020807 
## Corrected R over S Hurst exponent:   0.5124296 
## Empirical Hurst exponent:            0.5001093 
## Corrected empirical Hurst exponent:  0.4689422 
## Theoretical Hurst exponent:          0.5311854
lastRtn <- last(GDXreturns)
lastRtn
##            daily.returns
## 2019-06-19    0.01384541
#GDX_opt = getOptionChain("GDX","2019-02-15")
#view(puts)
#puts
#GDX_opt$puts
head(GDX)
##            GDX.Open GDX.High GDX.Low GDX.Close GDX.Volume GDX.Adjusted
## 2006-05-22    36.52    37.29   35.87     37.23     197100     34.28022
## 2006-05-23    37.75    39.22   37.75     37.96     620900     34.95239
## 2006-05-24    37.13    37.57   35.87     36.52     638600     33.62648
## 2006-05-25    37.18    38.32   36.98     38.32     367000     35.28387
## 2006-05-26    38.74    38.74   37.77     38.55     269400     35.49564
## 2006-05-30    39.50    39.72   38.11     38.17     559100     35.14574
Adj<-GDX$GDX.Adjusted
head(Adj)
##            GDX.Adjusted
## 2006-05-22     34.28022
## 2006-05-23     34.95239
## 2006-05-24     33.62648
## 2006-05-25     35.28387
## 2006-05-26     35.49564
## 2006-05-30     35.14574
fit<-auto.arima(Adj)
fcstfit=forecast(fit,h=20)
autoplot(fcstfit)

summary(fcstfit)
## 
## Forecast method: ARIMA(0,1,0)
## 
## Model Information:
## Series: Adj 
## ARIMA(0,1,0) 
## 
## sigma^2 estimated as 0.6956:  log likelihood=-4072.43
## AIC=8146.85   AICc=8146.85   BIC=8152.95
## 
## Error measures:
##                        ME      RMSE       MAE         MPE     MAPE
## Training set -0.003112377 0.8338959 0.5994007 -0.04531639 1.891871
##                   MASE         ACF1
## Training set 0.9997136 -0.007755313
## 
## Forecasts:
##      Point Forecast    Lo 80    Hi 80    Lo 95    Hi 95
## 3293             24 22.93116 25.06884 22.36535 25.63465
## 3294             24 22.48843 25.51157 21.68825 26.31175
## 3295             24 22.14871 25.85129 21.16870 26.83130
## 3296             24 21.86231 26.13769 20.73069 27.26931
## 3297             24 21.60999 26.39001 20.34480 27.65520
## 3298             24 21.38188 26.61812 19.99593 28.00407
## 3299             24 21.17211 26.82789 19.67511 28.32489
## 3300             24 20.97686 27.02314 19.37650 28.62350
## 3301             24 20.79347 27.20653 19.09604 28.90396
## 3302             24 20.62002 27.37998 18.83077 29.16923
## 3303             24 20.45505 27.54495 18.57847 29.42153
## 3304             24 20.29742 27.70258 18.33739 29.66261
## 3305             24 20.14623 27.85377 18.10617 29.89383
## 3306             24 20.00076 27.99924 17.88368 30.11632
## 3307             24 19.86039 28.13961 17.66901 30.33099
## 3308             24 19.72463 28.27537 17.46138 30.53862
## 3309             24 19.59305 28.40695 17.26015 30.73985
## 3310             24 19.46528 28.53472 17.06475 30.93525
## 3311             24 19.34102 28.65898 16.87471 31.12529
## 3312             24 19.21999 28.78001 16.68960 31.31040
res=residuals(fcstfit)
hist(res)

autoplot(res)

GDXacf = acf(res)

autoplot(GDXacf)

rwf(Adj)
##      Point Forecast    Lo 80    Hi 80    Lo 95    Hi 95
## 3293             24 22.93116 25.06884 22.36535 25.63465
## 3294             24 22.48843 25.51157 21.68825 26.31175
## 3295             24 22.14871 25.85129 21.16870 26.83130
## 3296             24 21.86231 26.13769 20.73069 27.26931
## 3297             24 21.61000 26.39000 20.34480 27.65520
## 3298             24 21.38188 26.61812 19.99593 28.00407
## 3299             24 21.17211 26.82789 19.67511 28.32489
## 3300             24 20.97686 27.02314 19.37650 28.62350
## 3301             24 20.79347 27.20653 19.09604 28.90396
## 3302             24 20.62002 27.37998 18.83077 29.16923
drifted = rwf(Adj,drift = TRUE)
autoplot(drifted)

yearlag1 <- GDXreturns["2018-6/2019-6-19"]

x = yearlag1

tmp <- density(x)
truehist(GDXreturns, prob = TRUE, ylim = c(0, max(tmp$y)),main = "GDX Returns Histogram")

# Plot 2: Normal curve (if prob = TRUE)
curve(dnorm(x, mean = mean(yearlag1), sd = sd(yearlag1)), 
      col = "red", 
      lwd = 3,
      add = TRUE)
curve( dt(x, df=15), add=TRUE, col='blue' )
lines(density(yearlag1, adjust = 2), lwd = 2, col = "Blue")

cv1yr = cvarRisk(yearlag1,1,alpha = .01)
cv1yr
##     CVaR.1% 
## -0.05501061
last<- last(GDX[,6])
drawdown <- last*cv1yr
last
##            GDX.Adjusted
## 2019-06-19           24
 crash <-last+drawdown
crash
##            GDX.Adjusted
## 2019-06-19     22.67975