# https://bookdown.org/kochiuyu/Technical-Analysis-with-R/technical-indicators.html
# This is the case of downloading data from TEJ
rm(list=ls())
con = gzcon(url('https://github.com/systematicinvestor/SIT/raw/master/sit.gz', 'rb'))
source(con)
close(con)
install.packages('pacman')
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.4'
## (as 'lib' is unspecified)
library(pacman)
p_load(quantmod, xts)
# tickers = spl('0050.TW')
# etf50 <- read.table("tw50_20030630_20181231.txt", header = TRUE, fileEncoding = "UTF-8")
# etf56 <- read.csv("tw0056_2007_2019_03.csv", header = T)
# etf56 <- read.delim("tw0056_2007_2019_01.csv", header = T)
# etf56 <- read.table("tw0056_2007_2019.txt", header = TRUE)
etf56 <- read.table("tw0056_20070101_20191231(1).txt", header = TRUE)
#etf56 <- read.csv("tw0056_20070101_20191231.csv", header = TRUE)
#etf50 <- read.table("tw50_20030630_20181231.txt", header = TRUE)
etf56 <- etf56[c(3, 7)]
colnames(etf56) <- c("date", "price")
head(etf56)
## date price
## 1 20071226 14.2343
## 2 20071227 14.3927
## 3 20071228 14.4890
## 4 20071231 14.7380
## 5 20080102 14.5739
## 6 20080103 14.3758
tail(etf56)
## date price
## 2964 20191224 28.74
## 2965 20191225 28.83
## 2966 20191226 28.86
## 2967 20191227 28.90
## 2968 20191230 29.00
## 2969 20191231 28.97
str(etf56)
## 'data.frame': 2969 obs. of 2 variables:
## $ date : int 20071226 20071227 20071228 20071231 20080102 20080103 20080104 20080107 20080108 20080109 ...
## $ price: num 14.2 14.4 14.5 14.7 14.6 ...
# 檢查是否有na 值
sum(is.na(etf56$price))
## [1] 0
# convert to time series data
# library(lubridate)
# etf50.xts <- xts(etf50$tw50, order.by = ymd(as.character(etf50$date)))
etf56.xts <- xts(etf56$price, order.by = as.Date(as.character(etf56$date), format = "%Y%m%d"))
head(etf56.xts)
## [,1]
## 2007-12-26 14.2343
## 2007-12-27 14.3927
## 2007-12-28 14.4890
## 2007-12-31 14.7380
## 2008-01-02 14.5739
## 2008-01-03 14.3758
colnames(etf56.xts) <- 'price'
head(etf56.xts)
## price
## 2007-12-26 14.2343
## 2007-12-27 14.3927
## 2007-12-28 14.4890
## 2007-12-31 14.7380
## 2008-01-02 14.5739
## 2008-01-03 14.3758
#
data <- new.env()
# Three inputs that you have to provide for backtesting:
# 1. prices; 2. weight; 3. execution.price
data$prices = data$weight = data$execution.price = etf56.xts
#data$prices <- etf56.xts
#data$weight = etf56.xts
#data$execution.price <- etf56.xts
#
data$weight <- data$prices * NA
data$weight[] = 1
#data$execution.price <- data$prices
data$execution.price[] <- NA
names(data)
## [1] "prices" "weight" "execution.price"