Monday, 18 March 2019

Using dplyr for data visulization (Part 2: ARRANGE, SELECT, RENAME, MUTATE)

rm(list= ls())
library(tidyverse)
options(repos = c(CRAN = "http://cran.rstudio.com"))
install.packages("nycflights13")
library(nycflights13)
nycflights13::flights
arrange(flights, year, month, day)

#Using desc() to reorder by a column in descending order#
arrange(flights, desc(arr_delay))
?select

#select a column by name#
select(flights, year, month, day)
#select all columns between year and day#
select(flights, year:day)
#or except for year to day#
select(flights, -(year:day))

#rename a variable#
rename(flights,tail_num = tailnum)

#Add new variable by Mutate() function#
flights <- data.frame(flights)
head(flights)
flightsml <- select(flights, year:day, ends_with("delay"), distance, air_time)
head(flightsml)
mutate(flightsml,delay = arr_delay - dep_delay, speed = distance/air_time*60)
?flights
#*ends_with: for the variable which ends by letter "delay", such as dep_delay, arr_delay...*#

#Using pipe function : this is a series of imperative statements: group, then summarize, then filter. As suggested by this reading, a good way to pronounce %>% when reading code is “then.”
#This code is to explore the relationship between the distance and average delay for each location. 

delays <- flights %>%
  group_by(dest) %>%
  summarise(count = n(),
            dist = mean(distance, na.rm = TRUE),
            delay = mean(arr_delay, na.rm = TRUE)
            ) %>%
  filter(count > 20, dest != "HNL")

delays %>% ggplot(delays, mapping = aes(x = dist, y = delay))+
  geom_point(aes(size = count), alpha = 1/3)+
  geom_smooth(se = FALSE)
#It looks like delays increase with distance up to ~750 miles and then decrease.

# Na.rm = TRUE
The aggregation functions obey the usual rule of missing values: if there’s any missing value in the input, the output will be a missing value. Fortunately, all aggregation functions have an na.rm argument, which removes the missing values prior to computation.



Using dplyr for data visulization (Part1: FILTER)


###Using package dplyr for data visualization###
rm(list=ls())
options(repos = c(CRAN = "http://cran.rstudio.com"))
install.packages("nycflights13")
library(nycflights13)
library(tidyverse)

###Using flights data to practice###
int stands for integers.
dbl stands for doubles, or real numbers.
chr stands for character vectors, or strings.
dttm stands for date-times (a date + a time)
lgl stands for logical, vectors that contain only TRUE or FALSE
fctr stands for factors, which R uses to represent categorical variables with fixed possible values
date stands for dates

?flights
nycflights13::flights
head(flights, n= 10)

### Using dplyr function to manipulate the data ###
Filter (): Pick observations by their values
Arrange (): Reorder the rows
Select (): Pick variables by their names
Mutate(): Create new variables with functions of existing variables
Summarize (): Collapse many values down to a single summary
Group_by():changes the scope of each function from operating on the entire dataset to operating on it group-by-group

Filter:
filter(flights, month == 1, day == 1)
filter(flights, month == 2, day == 2)

jan1 <- filter(flights, month ==1, day ==1)
head(jan1, n =10)
dec25 <- filter(flights, month == 12, day ==25)
head(dec25, n =9)

### Comparision: the standard suite: >, >=, <, <=, != (not equal), and == (equal)###
###Boolean operators: & is “and,” | is “or,” and ! is “not.”
filter(flights, month == 11 | month ==12)

### x %in% y: This will select every row where x is one of the values in y
nov_dec <- filter(flights, month %in% c(11,12))

### find flights that weren’t delayed (on arrival or departure) by more than two hours
filter(flights, !(arr_delay >=120 | dep_delay >=120))
filter(flights, !(arr_delay >= 45 & dep_delay >=45))
filter(flights, (arr_delay <=-3 | dep_delay <=-3 ))

Sunday, 17 March 2019

Some basic code for Stock Analysis + Value at Risk (VaR)


rm(list = ls())
setwd("D:/R studio/R portable/Practice/Stock Analysis")
options(repos = c(CRAN = "http://cran.rstudio.com"))
library(readxl)
vnindex <- read_excel("Historical data.xlsx")
head(vnindex)

#Check the data#
str(vnindex)
class(vnindex)

#Delete volume column#
vnindex$`Vol,` <- NULL

#Check missing data by Amelia package#
library(Amelia)
amelia(vnindex, m = 5)

#Check the normality#
hist(vnindex$Price,probability=T, main="Histogram of normal
data",xlab="Approximately normally distributed data")
+ line(density(vnindex$Price))

#Change the variable names#
names(vnindex)[names(vnindex)=='ï..NgÃ.y'] <- 'Date'
names(vnindex)[names(vnindex) == 'Láº.n.cuá..i'] <- 'Price'
names(vnindex)[names(vnindex) == 'Má.Ÿ'] <- 'Open'
names(vnindex)[names(vnindex) == 'Cao'] <- 'High'
names(vnindex)[names(vnindex) == 'Tháº.p'] <- 'Low'
names(vnindex)[names(vnindex)== 'KL'] <- 'Volume'
names(vnindex)[names(vnindex) == 'X..Thay.Ä.á..i'] <- 'Change'
names(vnindex)[names(vnindex) == 'Volumn'] <- 'Volume'
plot(vnindex)
library(ggplot2)
str(vnindex)
class(vnindex$Date)
class(vnindex)
library(lubridate)
vnindex$Date <- as.Date(vnindex$Date, format= "%d/%m/%Y")
vnindex$Date
class(vnindex$Date)
head(vnindex)

#Draw line graph through plot function#
plot(vnindex$Date, vnindex$Price, type="l", xlab="Date",
     ylab="Price" )

#Draw line graph by ggplot package align with pipe function %>%#
library(tidyverse)
vnindex %>% ggplot(aes(x = vnindex$Date, y = vnindex$Price)) +geom_line()
*Vẽ bằng ggplot cho kết quả đẹp hơn*

#Tach cot du lieu#
attach(vnindex)

#Tách cột giá đóng cửa#
closeprice <- rev(vnindex$Price)
head(closeprice)

#Tính lợi suất của chuỗi dữ liệu vnindex#

#Công thức lợi suất P(vnindex) = (p(n) - p(n-1))/p(n-1) Hoặc ln (P(n)/P(n-1))#
n <- length(closeprice)

#Cach 1:
vnreturn <- (closeprice[2:n]-closeprice[1:(n-1)])/closeprice[1:(n-1)]

#Cach 2:
lnvnreturn <- log((closeprice[2:n])/(closeprice[1:(n-1)])

#Load dữ liệu chứng khoán của thị trường thế giới#
install.packages("quantmod")
library(quantmod)

# Đọc dữ liệu DowJones từ nguồn finance.yahoo.com#
getSymbols('DJI', src = 'yahoo', from = "2018-01-01", to = "2019-03-01")
DJI
head(DJI, n = 10)
str(DJI)
class(DJI)

#Chuyển dạng data frame cho DownJone#
DJI <- data.frame(DJI)

#Vẽ đồ thị stock trong gói quantmod#
chartSeries(DJI, theme = chartTheme("white"), subset = 'last 5 months')


#Kiểm tra phân phối dữ liệu lợi suất vnindex#
hist(vnreturn, breaks = 12, col = "blue")

d <- density(vnreturn)                 
plot(d)

#Đo độ biến động volatility của một số cổ phiếu (trường hợp vnindex)#
Volatility là một phương pháp thống kê đo độ phân tán của các khoản thu hồi được của các Chứng khoán hoặc chỉ số thị trường. Volatility có thể được đo bằng cách sử dụng độ lệch chuẩn giữa các khoản thu hồi từ các loại chứng khoán tương tự hay chỉ số thị trường. Thông thường, nếu Chứng khoán có volatility (độ biến động) cao, thì sẽ bị rủi ro nhiều hơn. (1) Volatility là một biến số trong công thức định giá giá trị Hợp đồng quyền chọn chỉ ra phạm vi mà tài sản underlying (xem UNDERLYING) sẽ giao động trong khoảng thời gian giữa hiện tại và lúc đáo hạn hợp đồng quyền chọn. Volatility, được miêu tả là một hệ số phần trăm trong các công thức định giá giá trị hợp đồng quyền chọn (option pricing formulas), sinh ra từ các hoạt động giao dịch hàng ngày. Cách mà volatility được đo sẽ ảnh hưởng đến giá trị của hệ số được sử dụng. (2) Theo cách diễn đạt khác, volatility đặc trưng cho độ bất ổn hoặc là mức rủi ro trong giao động của giá trị Chứng khoán. Độ bất ổn càng cao đồng nghĩa với giá trị của chứng khoáncàng có nguy cơ bị giãn ra theo nhiều bậc giá trị. Điều này có nghĩa là giá cả của chứng khoán có thể bị thay đổi đột ngột chỉ trong một khoảng thời gian ngắn theo cả hai hướng (tăng đột ngột hoặc giảm đột ngột). Và ngược lại, độ Bất ổn thấp có nghĩa là giá trị của Chứng khoán không bị biến động đột ngột, mà chỉ thay đổi từ từ chắc chắn sau một quá trình. Một phép đo độ bất ổn tương đối của một loại Cổ phần cụ thể đối với thị trường là chỉ số bêta của nó. Chỉ số beta xấp xỉ độ Bất ổn chung của các khoản thu hồi của chứng khoán so với thu hồi của thị trường.
Ví dụ: Một Cổ phần có chỉ số beta giá trị là 1,1 có nghĩa là Chứng khoán sẽ thu hồi lại được 110% so với tổng các khoản thị trường thu hồi được sau một khoảng thời gian xác định. Ngược lại, chỉ số beta là 0,9 sẽ cho khoản thu hồi là 90% của tổng số thu hồi của thị trường.

n <- length(vnindex$Price)
volatility<-sqrt(252)*sqrt(var(log(vnindex$Price[2:n]/vnindex$Price[1:n-1])))
volatility
[1] 0.2141678

Độ biến động của VN-index trong năm qua không cao. (Theo quy ước độ biến đông nhỏ hơn 20% có thể xem là biến động ở mức thấp, nến lớn hơn 40% có thể xem là mức cao). Volatility của VN-index trong khoảng thời gian qua ở mức thấp, nó phản ánh đúng tình trạng ảm đạm của thị trường chứng khoán Việt Nam – hàn thử biểu của nền kinh tế đất nước.

#Value at Risk VaR#
Value at Risk (giá trị chịu rủi ro) của một tài sản (hoặc danh mục, chỉ số) là một con số, ký hiệu là VaR(τ,α), cho biết với độ tin cậy (1- α)100%, sau một chu kỳ thời gian τ thì lợi suất của tài sản sụt giảm không quá VaR(τ,α)100%.
Chu kỳ τ có thể là ngày, tháng, năm nhưng với các chu kỳ thời gian khác đều có thể quy đổi về chu kỳ ngày, α thường chọn là 0.01 hoặc 0.05; VaR cũng được tính cho chuỗi giá, tuy nhiên từ VaR của chuỗi lợi suất ta cũng tính được VaR của chuỗi giá. Có nhiều phương pháp để tính VaR như phương pháp lịch sử, phương pháp tham số, phương pháp mô phỏng,… sự khác nhau nằm ở các phương pháp để các định phân phối của chuỗi lợi suất.

Tính VaR(chu kỳ ngày, α = 0.05)
##Ta đã có chuỗi lợi suất của VN index vnreturn
> library(PerformanceAnalytics) ##Gọi package ra để sử dụng

##VaR lịch sử
> VaR(vnreturn, p=.95, method="historical")
VaR -0.02127722

##VaR tham số (giả thiết phân phối chuẩn)
> VaR(vnreturn, p=.95, method="gaussian")
VaR -0.02211347

##VaR Cornish-Fishe hiệu chỉnh (phương pháp được đánh giá là khắc phục được nhược điểm giả thiết “chuẩn” của chuỗi lợi suất)
> VaR(vnreturn, p=.95, method="modified")
VaR -0.01856129

#VaR của một số cổ phiếu: Ta dùng phương pháp VaR lịch sử để tính VaR theo ngày của một số cổ phiếu phiếu HAG, STB, VT1#

#Hệ số Beta#
Hệ số beta là đại lượng đo tốc độ thay đổi tương đối của một cổ phiếu (hoặc danh mục) với thị trường. Phần lớn hệ số beta là số dương – các cổ phiếu thường biến động cùng chiều thị trường – hệ số beta càng lớn thì tốc độ tăng/ giảm cùng chiều với thị trường càng lớn; khi hệ số beta âm, nó thể hiện cổ phiếu biến động ngược thị trường.
Sau đây, ta sẽ tính chỉ số beta của một số cổ phiếu trên sàn HOSE với chỉ số đại diện thị trường VN index, chuỗi dữ liệu 100 ngày giao dịch. Tính hệ số beta chuỗi lợi suất vnreturn và cổ phiếu HAG gồm 100 ngàygiao dịch:
beta<-cov(hagreturn,vnreturn)/var(vnreturn)
beta