1 The as.date Function

1.1 What as.date can handle

The dashes and slashes can be handled even without adding a zero. But, it has to be in the order of year, month and date(standard date data.)

as.Date("2014/02/04")
## [1] "2014-02-04"
as.Date("2014/2/4")
## [1] "2014-02-04"
as.Date("2014-02-04")
## [1] "2014-02-04"
as.Date("2014-2-4")
## [1] "2014-02-04"

1.2 How can as.date be more flexible?

The following table is how you can add a parameter, “format =,” to the function so that it can read your date format.

  1. month date are not hard to remember.

  2. Yy means year. the small letter means two-digit only.

  3. Aa means weekday. The small letter means it’s abbreviated.

  4. Bb means month in English.

  5. If month in English is used, remember to make sure the system time is in English. If not, type in Sys.setlocale(category = "LC_ALL", locale = "English")

## Use the format argument to specify the input format of the date if it is not in the default format
as.Date("1970.1.1", format="%Y.%m.%d") 
## [1] "1970-01-01"
as.Date("1/1/1970", format="%m/%d/%Y") 
## [1] "1970-01-01"
#Sys.setlocale(category = "LC_ALL", locale =
#"English")
as.Date("January 1, 1970", format="%B %d, %Y")
## [1] NA
as.Date("01JAN70", format="%d%b%y")
## [1] NA

1.3 Extracting Information from Date Objects

  1. Format function: format(some date object, "the desired format")

  2. weekdays(), months(), quarters(), julian(): Directly extract the single date format desired.

months(as.Date("2014-02-14"))
## [1] "二月"
format(as.Date("2014-02-14"), format="%B") # comparison
## [1] "二月"

2 Time Series Objects in R

2.1 Converting to time series object

2.1.1 zoo function

  1. zoo(data, as.Date(, )) :

    • remember to remove the date column from the data.

    • the as.Date is for the time index.

# Covert dataframe to timeseries object
# install.packages("zoo") # If not installed yet, needs installation once only
library(zoo) # load the package, everytime
## Warning: 套件 'zoo' 是用 R 版本 4.3.1 來建造的
## 
## 載入套件:'zoo'
## 下列物件被遮斷自 'package:base':
## 
##     as.Date, as.Date.numeric
tse<-read.table("C:/Users/travi/Downloads/tse.csv", header=T)
tse.ts<-zoo(tse[,-1],as.Date(as.character(tse[,"DATE"]), "%Y%m%d"))
plot(tse.ts[, "JS"])

2.1.1.1 Exercise 1 : Get all Friday data

  1. Changing the tse$Date to a character object: it was initially an integer. In order that it fits the as.Date function, we need to convert it to character.

  2. Extracting the weekdays data and assigning it to WD, so that we can extract the rows that have Friday as their WD.

# Get All Friday Data
x<-as.Date(as.character(tse$DATE),"%Y%m%d")
WD<-weekdays(x) 

x.ts<-zoo(cbind(tse[,-1],WD), x) 
head(x.ts)
##            JS       VAL.S     VOL.S      TRA.S   WD    
## 1990-01-01 <NA>     <NA>      <NA>       <NA>    星期一
## 1990-01-02 <NA>     <NA>      <NA>       <NA>    星期二
## 1990-01-03 <NA>     <NA>      <NA>       <NA>    星期三
## 1990-01-04  9853.15 115618.01  825590.58  312830 星期四
## 1990-01-05  9862.42 122593.01  954284.79  372348 星期五
## 1990-01-06  9927.06  78493.81  569919.00  225054 星期六
#Sys.setlocale(category = "LC_ALL", locale = "zh_TW.UTF-8")
x.ts.Fri<-x.ts[x.ts$WD=="Friday"] 
head(x.ts.Fri); tail(x.ts.Fri)
##      JS VAL.S VOL.S TRA.S WD
##      JS VAL.S VOL.S TRA.S WD

2.1.1.2 Make a better plot

  1. Add a label on x and y axis by using xlab and ylab.

  2. Horizontal and vertical line using abline(h or v=…(locaiton) , lty="?")

  3. text(x location, y location, "title", col="?"): or you can just use locator(1) to replace xy location and just pin the desired location on the plot.

# Plot Again
# library(zoo)

tse.dat <- na.omit(tse)
tse.ts<-zoo(tse.dat[,-1], as.Date(as.character(tse.dat[,1]), format="%Y%m%d"))

#col means color, ylab and xlab are labels on x and y axis
plot(tse.ts[,"JS"], main="Taiwan Stock Exchange Value-Weighted Index",col="slateblue1",ylab="TSE Index", xlab="",las=0, cex=2)

#abline(h= ...(location), lty=) means horizontal line.
#abline(v= ...(location), lty=) means vertical line.
#text(x-axis, y-axis, "words", col="")
abline(v=as.numeric(as.Date("1999/09/21")),lty=2)
text(as.numeric(as.Date("1999/09/21")), 4000,"921 Earthquake", col="red")
abline(h=c(min(tse.ts[,"JS"]),max(tse.ts[,"JS"])),lty=3)

#This doesn't work when knitting.
#text(locator(1), "Historical High", col="red")
#text(locator(1), "Historical Low", col="red")

2.1.1.3 Multiple Plots on the Same Page

  1. par():
    • mfrow=c(x,y): x rows and y collumns
    • oma=c(bottom, left, top, right) giving the size of the outer margins in lines of text.
par(mfrow=c(2,2), oma=c(1,1,2,1))
plot(tse.ts[,"JS"], ylab="TSE Index")
title("TSE Index")
plot(tse.ts[,"VAL.S"], ylab="TSE Trading Value")
title("Trading Value")
plot(tse.ts[,"VOL.S"], ylab="TSE Trading Volume")
title("Trading Volume")
plot(tse.ts[,"TRA.S"], ylab="TSE # of Transaction")
title("# of Transaction")
mtext(outer=T,"Taiwan Stock Exchange", cex=2)

2.1.2 as.POSIXct and as.POSIXIt

  1. as.POSIXct: total number of seconds starting from 1970/1/1.

  2. as.POSIXIt: sec, min, hr, day, months, years, etc.)

  3. format table:

# Date + time
now <- Sys.time()
a=as.POSIXct(now)
class(a)
## [1] "POSIXct" "POSIXt"
#returns the seconds passed starting from 1970-Jan-01
unclass(a)
## [1] 1698640448
b=as.POSIXlt(now)
class(b)
## [1] "POSIXlt" "POSIXt"
names(unclass(b))
##  [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"   "yday"  
##  [9] "isdst"  "zone"   "gmtoff"
unclass(b)$wday
## [1] 1

2.1.3 Flexible Time+Date with Lubridate

# Flexible Date+Time with Lubridate
#install.packages("lubridate")
library(lubridate)
## Warning: 套件 'lubridate' 是用 R 版本 4.3.1 來建造的
## 
## 載入套件:'lubridate'
## 下列物件被遮斷自 'package:base':
## 
##     date, intersect, setdiff, union
date<-dmy("01–12–18")
date
## [1] "2018-12-01"
date<-ymd("01-12-18")
date
## [1] "2001-12-18"
date<-ymd("2001-12-18")
date
## [1] "2001-12-18"

2.2 An FX Example

Intraday high-frequency (HF) USD/EUR quotes data from EBS (electronic broking services) for

  1. a period from 2001-03-11 to 2001-03-17.

  2. 151 FX-dealing banks.

  3. A total of 127,351 records.

  4. There are 5 columns: Date, Time, Bid, Ask, and Bank, although

    • no column names in the csv files

    • columns are separated by a white space

# Read HF FX Data
fx0 <- read.csv("C:/Users/travi/Downloads/fx.csv",sep=" ", stringsAsFactors =F, strip.white = T, header=F,na.strings="N.A.")

names(fx0) <- c("Date","Time", "Bid", "Ask", "Bank")
head(fx0)
##         Date     Time    Bid    Ask Bank
## 1 11.03.2001 01:07:46 0.9337 0.9342 AREX
## 2 11.03.2001 01:07:52 0.9336 0.9341 AREX
## 3 11.03.2001 01:07:57 0.9334 0.9339 AREX
## 4 11.03.2001 01:08:04 0.9337 0.9342 AREX
## 5 11.03.2001 05:42:35 0.9330 0.9340 CMBK
## 6 11.03.2001 05:42:37 0.9336 0.9341 AREX

You can recognize the date and time format is “day.month.year” and “hour:minute:second”. Hence, you convert it accordingly.

td <- as.POSIXct(
  paste(fx0$Date, fx0$Time, sep=" "),   format="%d.%m.%Y %H:%M:%S"
) 
head(td)
## [1] "2001-03-11 01:07:46 CST" "2001-03-11 01:07:52 CST"
## [3] "2001-03-11 01:07:57 CST" "2001-03-11 01:08:04 CST"
## [5] "2001-03-11 05:42:35 CST" "2001-03-11 05:42:37 CST"

2.2.1 Can zoo deal with duplicated dates?

#library(zoo)
fx0.ts <- zoo(fx0[,-c(1,2)], td) # Note the duplicated date
## Warning in zoo(fx0[, -c(1, 2)], td): some methods for "zoo" objects do not work
## if the index entries in 'order.by' are not unique
head(fx0.ts)
##                     Bid    Ask    Bank
## 2001-03-11 01:07:46 0.9337 0.9342 AREX
## 2001-03-11 01:07:52 0.9336 0.9341 AREX
## 2001-03-11 01:07:57 0.9334 0.9339 AREX
## 2001-03-11 01:08:04 0.9337 0.9342 AREX
## 2001-03-11 05:42:35 0.9330 0.9340 CMBK
## 2001-03-11 05:42:37 0.9336 0.9341 AREX
## This is tedious and tiresome!

We will resolve this issue by aggregating the date.

2.2.2 Alternative way to read the HF FX Data

  1. Disclaimer: this object is not a time series object yet.

  2. col_names to assign the column names.

  3. col_types to assign the col_date and col_time.:

    • col_types = cols(X1 = col_date(format = "%d.%m.%Y"), X2 = col_time(format = "%H:%M:%S")))
# Read HF FX Data - Alternative
# See in-class demo for the following
# install.packages("readr")
library(readr) # part of the tidyverse package, read functions in readr is 10 times faster than base R’s read.csv()
## Warning: 套件 'readr' 是用 R 版本 4.3.1 來建造的
fx1<- read_table("C:/Users/travi/Downloads/fx.csv", 
                 col_names = c("Date","Time", "Bid", "Ask", "Bank"),
                 col_types = cols(X1 = col_date(format = "%d.%m.%Y"), 
                                  X2 = col_time(format = "%H:%M:%S")))
## Warning: The following named parsers don't match the column names: X1, X2
# fx1 is not an R timeseries object yet! Why not?

View(fx1)

2.2.3 Splitting the HF FX Data

# Splitting the HF FX Data
# Checking how much data do each bank provide
table(fx1$Bank) # not in order
## 
##  ABIV  ACBF  ADCB  AIBM  ALBX  ALFN  ALMA  AMRA  ANZH  ANZN  ANZW  AREX  ATLX 
##   113   322     2  4085     2  5147     2     8     7     5     6  8874   544 
##  BADI  BANK  BAON  BAUA  BBIQ  BBLH  BBMF  BCIK  BCIO  BCIS  BCIX  BDRH  BES3 
##   486   231   234   277     1     6    24    10     4     6   981    30    54 
##  BGFX  BGLX  BHFX  BIET  BIGO  BILZ  BKR1  BKSA  BMST  BMXL  BNL1  BNLA  BNPT 
##  7091   583  8658     2     1    18    11    45     6     3     3     5    16 
##  BNYT  BNZW  BOEB  BOID  BOIS  BPAX  BPMX  BQNP  BRAZ  BREL  BSAB  BSPP  CBKH 
##     6     3     1     1     2  1735   761    54   461   236     1  2076     4 
##  CGD1  CHFX  CHNY  CIBT  CLHK  CMBK  CRE1  CTTI  DBFX  DDBX  DEUA  DGHK  DGZF 
##   307   400   332   584     4    11   273     5  1094   627  1906    10    25 
##  DKFX  DNBO  DNBS  DRE1  EBAG  EMBA  ESFO  FJBK  FLTG  GTCX  GUTA  HSHK  IBJQ 
##    36   395     3  1679    12     7    55     2     2     4   389     4    71 
##  ICC1  INGV  INGX  INTS  INVM  ISBR  KBPH  KPBH  KRBL  KRFZ  LBBW  LBDB  LEOF 
##    17   193 10516     1     1  9193     2     7     3    12   760     3  1164 
##  LUBA  MBBX  MIDX  MINN  MPSS  MPSW  MTKH  NABM  NAPX  NATA  NBCM  NBFX  NBGX 
##   187     2     4    39     1  2902     9     4     3     4    25     3    58 
##  NBJX  NBKX  NBP1  NEDL  NTCC  NWHK  OBER  ONEC  PAMX  PBNY  PETR  PKOQ  PRIV 
##  5209     1  1860     2    32  1432     3  2414   146     4   211     4    15 
##  RAB1  RBCJ  RBCT  RBOZ  RCBW  RVTB  RZBA  SBIQ  SBIX  SBLI  SCKL  SCXD  SELY 
##  5611     4  1693     1     2  2711   320    12     1    27     3     4   546 
##  SGOX  SKRQ  SOBN  SPVT  STST  TDFX  TEKT  TMFT  TRAQ  TRBR  TUBD  UBFX  UGBA 
## 14303     4    70    77     1     2   191    21    19  7352  3022     7     8 
##  UNPR  UOBX  VIZA  VUBR  VUWX  WBCA  WFSF  WLNY 
##     5   219    89  3036     4     2    51     6
sort(table(fx1$Bank)) # increasing order
## 
##  BBIQ  BIGO  BOEB  BOID  BSAB  INTS  INVM  MPSS  NBKX  RBOZ  SBIX  STST  ADCB 
##     1     1     1     1     1     1     1     1     1     1     1     1     2 
##  ALBX  ALMA  BIET  BOIS  FJBK  FLTG  KBPH  MBBX  NEDL  RCBW  TDFX  WBCA  BMXL 
##     2     2     2     2     2     2     2     2     2     2     2     2     3 
##  BNL1  BNZW  DNBS  KRBL  LBDB  NAPX  NBFX  OBER  SCKL  BCIO  CBKH  CLHK  GTCX 
##     3     3     3     3     3     3     3     3     3     4     4     4     4 
##  HSHK  MIDX  NABM  NATA  PBNY  PKOQ  RBCJ  SCXD  SKRQ  VUWX  ANZN  BNLA  CTTI 
##     4     4     4     4     4     4     4     4     4     4     5     5     5 
##  UNPR  ANZW  BBLH  BCIS  BMST  BNYT  WLNY  ANZH  EMBA  KPBH  UBFX  AMRA  UGBA 
##     5     6     6     6     6     6     6     7     7     7     7     8     8 
##  MTKH  BCIK  DGHK  BKR1  CMBK  EBAG  KRFZ  SBIQ  PRIV  BNPT  ICC1  BILZ  TRAQ 
##     9    10    10    11    11    12    12    12    15    16    17    18    19 
##  TMFT  BBMF  DGZF  NBCM  SBLI  BDRH  NTCC  DKFX  MINN  BKSA  WFSF  BES3  BQNP 
##    21    24    25    25    27    30    32    36    39    45    51    54    54 
##  ESFO  NBGX  SOBN  IBJQ  SPVT  VIZA  ABIV  PAMX  LUBA  TEKT  INGV  PETR  UOBX 
##    55    58    70    71    77    89   113   146   187   191   193   211   219 
##  BANK  BAON  BREL  CRE1  BAUA  CGD1  RZBA  ACBF  CHNY  GUTA  DNBO  CHFX  BRAZ 
##   231   234   236   273   277   307   320   322   332   389   395   400   461 
##  BADI  ATLX  SELY  BGLX  CIBT  DDBX  LBBW  BPMX  BCIX  DBFX  LEOF  NWHK  DRE1 
##   486   544   546   583   584   627   760   761   981  1094  1164  1432  1679 
##  RBCT  BPAX  NBP1  DEUA  BSPP  ONEC  RVTB  MPSW  TUBD  VUBR  AIBM  ALFN  NBJX 
##  1693  1735  1860  1906  2076  2414  2711  2902  3022  3036  4085  5147  5209 
##  RAB1  BGFX  TRBR  BHFX  AREX  ISBR  INGX  SGOX 
##  5611  7091  7352  8658  8874  9193 10516 14303
sort(table(fx1$Bank), decreasing =T) # decreasing order
## 
##  SGOX  INGX  ISBR  AREX  BHFX  TRBR  BGFX  RAB1  NBJX  ALFN  AIBM  VUBR  TUBD 
## 14303 10516  9193  8874  8658  7352  7091  5611  5209  5147  4085  3036  3022 
##  MPSW  RVTB  ONEC  BSPP  DEUA  NBP1  BPAX  RBCT  DRE1  NWHK  LEOF  DBFX  BCIX 
##  2902  2711  2414  2076  1906  1860  1735  1693  1679  1432  1164  1094   981 
##  BPMX  LBBW  DDBX  CIBT  BGLX  SELY  ATLX  BADI  BRAZ  CHFX  DNBO  GUTA  CHNY 
##   761   760   627   584   583   546   544   486   461   400   395   389   332 
##  ACBF  RZBA  CGD1  BAUA  CRE1  BREL  BAON  BANK  UOBX  PETR  INGV  TEKT  LUBA 
##   322   320   307   277   273   236   234   231   219   211   193   191   187 
##  PAMX  ABIV  VIZA  SPVT  IBJQ  SOBN  NBGX  ESFO  BES3  BQNP  WFSF  BKSA  MINN 
##   146   113    89    77    71    70    58    55    54    54    51    45    39 
##  DKFX  NTCC  BDRH  SBLI  DGZF  NBCM  BBMF  TMFT  TRAQ  BILZ  ICC1  BNPT  PRIV 
##    36    32    30    27    25    25    24    21    19    18    17    16    15 
##  EBAG  KRFZ  SBIQ  BKR1  CMBK  BCIK  DGHK  MTKH  AMRA  UGBA  ANZH  EMBA  KPBH 
##    12    12    12    11    11    10    10     9     8     8     7     7     7 
##  UBFX  ANZW  BBLH  BCIS  BMST  BNYT  WLNY  ANZN  BNLA  CTTI  UNPR  BCIO  CBKH 
##     7     6     6     6     6     6     6     5     5     5     5     4     4 
##  CLHK  GTCX  HSHK  MIDX  NABM  NATA  PBNY  PKOQ  RBCJ  SCXD  SKRQ  VUWX  BMXL 
##     4     4     4     4     4     4     4     4     4     4     4     4     3 
##  BNL1  BNZW  DNBS  KRBL  LBDB  NAPX  NBFX  OBER  SCKL  ADCB  ALBX  ALMA  BIET 
##     3     3     3     3     3     3     3     3     3     2     2     2     2 
##  BOIS  FJBK  FLTG  KBPH  MBBX  NEDL  RCBW  TDFX  WBCA  BBIQ  BIGO  BOEB  BOID 
##     2     2     2     2     2     2     2     2     2     1     1     1     1 
##  BSAB  INTS  INVM  MPSS  NBKX  RBOZ  SBIX  STST 
##     1     1     1     1     1     1     1     1
# Splitting data according to different bank and  storing all of which into a large list.
fx1.splitted<-split(fx1, fx1$Bank)
names(fx1.splitted)
##   [1] "ABIV" "ACBF" "ADCB" "AIBM" "ALBX" "ALFN" "ALMA" "AMRA" "ANZH" "ANZN"
##  [11] "ANZW" "AREX" "ATLX" "BADI" "BANK" "BAON" "BAUA" "BBIQ" "BBLH" "BBMF"
##  [21] "BCIK" "BCIO" "BCIS" "BCIX" "BDRH" "BES3" "BGFX" "BGLX" "BHFX" "BIET"
##  [31] "BIGO" "BILZ" "BKR1" "BKSA" "BMST" "BMXL" "BNL1" "BNLA" "BNPT" "BNYT"
##  [41] "BNZW" "BOEB" "BOID" "BOIS" "BPAX" "BPMX" "BQNP" "BRAZ" "BREL" "BSAB"
##  [51] "BSPP" "CBKH" "CGD1" "CHFX" "CHNY" "CIBT" "CLHK" "CMBK" "CRE1" "CTTI"
##  [61] "DBFX" "DDBX" "DEUA" "DGHK" "DGZF" "DKFX" "DNBO" "DNBS" "DRE1" "EBAG"
##  [71] "EMBA" "ESFO" "FJBK" "FLTG" "GTCX" "GUTA" "HSHK" "IBJQ" "ICC1" "INGV"
##  [81] "INGX" "INTS" "INVM" "ISBR" "KBPH" "KPBH" "KRBL" "KRFZ" "LBBW" "LBDB"
##  [91] "LEOF" "LUBA" "MBBX" "MIDX" "MINN" "MPSS" "MPSW" "MTKH" "NABM" "NAPX"
## [101] "NATA" "NBCM" "NBFX" "NBGX" "NBJX" "NBKX" "NBP1" "NEDL" "NTCC" "NWHK"
## [111] "OBER" "ONEC" "PAMX" "PBNY" "PETR" "PKOQ" "PRIV" "RAB1" "RBCJ" "RBCT"
## [121] "RBOZ" "RCBW" "RVTB" "RZBA" "SBIQ" "SBIX" "SBLI" "SCKL" "SCXD" "SELY"
## [131] "SGOX" "SKRQ" "SOBN" "SPVT" "STST" "TDFX" "TEKT" "TMFT" "TRAQ" "TRBR"
## [141] "TUBD" "UBFX" "UGBA" "UNPR" "UOBX" "VIZA" "VUBR" "VUWX" "WBCA" "WFSF"
## [151] "WLNY"

2.2.4 Exercise with SGOX

SGOX <- fx1.splitted$SGOX; head(SGOX)
## # A tibble: 6 × 5
##   Date       Time       Bid   Ask Bank 
##   <chr>      <time>   <dbl> <dbl> <chr>
## 1 12.03.2001 07:00:27 0.933 0.934 SGOX 
## 2 12.03.2001 07:00:30 0.933 0.933 SGOX 
## 3 12.03.2001 07:00:35 0.933 0.934 SGOX 
## 4 12.03.2001 07:00:56 0.933 0.933 SGOX 
## 5 12.03.2001 07:01:16 0.933 0.933 SGOX 
## 6 12.03.2001 07:01:21 0.933 0.933 SGOX
td.SGOX <- as.POSIXct(
  paste(SGOX$Date, SGOX$Time, sep=" "),     format="%d.%m.%Y %H:%M:%S"
) 

# get rid off duplicated data on the same time spot
which(duplicated(td.SGOX))
## [1]  6269 10973
# making sure the date and time are actually duplicated 
SGOX[6268:6269,]
## # A tibble: 2 × 5
##   Date       Time       Bid   Ask Bank 
##   <chr>      <time>   <dbl> <dbl> <chr>
## 1 14.03.2001 12:15:56 0.918 0.918 SGOX 
## 2 14.03.2001 12:15:56 0.918 0.918 SGOX
SGOX[10972:10973,]
## # A tibble: 2 × 5
##   Date       Time       Bid   Ask Bank 
##   <chr>      <time>   <dbl> <dbl> <chr>
## 1 15.03.2001 18:33:48 0.898 0.898 SGOX 
## 2 15.03.2001 18:33:48 0.898 0.899 SGOX
# removing the duplicated date and time rows from the objects 
SGOX<- SGOX[-c(6269,10973),]
td.SGOX <- td.SGOX[-c(6269,10973)]
# make sure the data and the index have the same length
dim(SGOX)
## [1] 14301     5
length(td.SGOX)
## [1] 14301
#converting and plotting
SGOX.ts <-zoo(SGOX[,-c(1:2,5)], td.SGOX )
plot(SGOX.ts$Ask); lines(SGOX.ts$Bid, col=2)

2.3 Aggregating a time series object

  1. the aggregateTS function can only aggregate xts objects.

    • as.xts() converts an object to an xts.

    • on assigns the frequency and k assigns the amount.

# Aggregate a time series
#install.packages("highfrequency")
#install.packages("xts")
library(highfrequency)
## Warning: 套件 'highfrequency' 是用 R 版本 4.3.1 來建造的
library(xts)
## Warning: 套件 'xts' 是用 R 版本 4.3.1 來建造的
SGOX.10min = aggregateTS(as.xts(SGOX.ts), on="minutes",k=10)
# Aggregate tick-by-tick to 10 minutes data
dim(SGOX); dim(SGOX.10min)
## [1] 14301     5
## [1] 6480    2
plot(SGOX.10min$Ask)

3 Quantmod Application

3.1 Example 1: TSMC from Yahoo

  1. getSymbols to obtain the data

    • from and to attributes to assign the date interval.
  2. chartSeries to plot.

# Example 1: TSMC from Yahoo
#install.packages ("quantmod") 
# install the package, only required once  (the 1st time)
library(quantmod) # Load the package
## Warning: 套件 'quantmod' 是用 R 版本 4.3.1 來建造的
## 載入需要的套件:TTR
## Warning: 套件 'TTR' 是用 R 版本 4.3.1 來建造的
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
getSymbols("2330.TW",from="2016-01-02", to=Sys.Date())
## Warning: 2330.TW contains missing values. Some functions will not work if
## objects contain missing values in the middle of the series. Consider using
## na.omit(), na.approx(), na.fill(), etc to remove or replace them.
## [1] "2330.TW"
TSMC<-get("2330.TW") #Avoid using numbers to start an object name.
dim(TSMC) # dimension
## [1] 1906    6
head(TSMC,3) # Show the first 3 rows
##            2330.TW.Open 2330.TW.High 2330.TW.Low 2330.TW.Close 2330.TW.Volume
## 2016-01-04        142.5        143.5         139         139.5       39169000
## 2016-01-05        139.0        140.0         137         138.0       46381000
## 2016-01-06        138.0        138.0         135         135.5       53617000
##            2330.TW.Adjusted
## 2016-01-04         110.0191
## 2016-01-05         108.8361
## 2016-01-06         106.8644
tail(TSMC,3) # Show last 3 rows
##            2330.TW.Open 2330.TW.High 2330.TW.Low 2330.TW.Close 2330.TW.Volume
## 2023-10-25          544          551         544           544       16526355
## 2023-10-26          530          535         530           531       28188348
## 2023-10-27          534          536         532           533       15679643
##            2330.TW.Adjusted
## 2023-10-25              544
## 2023-10-26              531
## 2023-10-27              533
colnames(TSMC) #variables
## [1] "2330.TW.Open"     "2330.TW.High"     "2330.TW.Low"      "2330.TW.Close"   
## [5] "2330.TW.Volume"   "2330.TW.Adjusted"
chartSeries(TSMC,theme="white")

3.2 Example 2: CBOE Volatility Index: VIX from FRED

  1. src is for source other than Yahoo Finance.

  2. window is the designated function for datas from FRED

getSymbols("VIXCLS",src="FRED")
## [1] "VIXCLS"
VIXCLS2<-window(VIXCLS, start = "2016-02-01", end = Sys.Date())

chartSeries(VIXCLS2,theme="white")

3.3 Example 3: Japan / U.S. Foreign Exchange Rate from FRED

DEXJPUS doesn’t allow date interval modification. It just provides the full data.

getSymbols("DEXJPUS",src="FRED")
## [1] "DEXJPUS"
start(DEXJPUS)
## [1] "1971-01-04"
end(DEXJPUS)
## [1] "2023-10-20"
chartSeries(DEXJPUS,theme="white")