R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

library(dslabs)
## Warning: package 'dslabs' was built under R version 4.3.3
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.3.3
## Warning: package 'ggplot2' was built under R version 4.3.3
## Warning: package 'tibble' was built under R version 4.3.3
## Warning: package 'tidyr' was built under R version 4.3.2
## Warning: package 'readr' was built under R version 4.3.3
## Warning: package 'purrr' was built under R version 4.3.2
## Warning: package 'dplyr' was built under R version 4.3.2
## Warning: package 'stringr' was built under R version 4.3.2
## Warning: package 'forcats' was built under R version 4.3.3
## Warning: package 'lubridate' was built under R version 4.3.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.0     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
head(gapminder)
##               country year infant_mortality life_expectancy fertility
## 1             Albania 1960           115.40           62.87      6.19
## 2             Algeria 1960           148.20           47.50      7.65
## 3              Angola 1960           208.00           35.98      7.32
## 4 Antigua and Barbuda 1960               NA           62.97      4.43
## 5           Argentina 1960            59.87           65.39      3.11
## 6             Armenia 1960               NA           66.86      4.55
##   population          gdp continent          region
## 1    1636054           NA    Europe Southern Europe
## 2   11124892  13828152297    Africa Northern Africa
## 3    5270844           NA    Africa   Middle Africa
## 4      54681           NA  Americas       Caribbean
## 5   20619075 108322326649  Americas   South America
## 6    1867396           NA      Asia    Western Asia
View(gapminder)
dat<-gapminder
#1.1.   Tỷ lệ tử vong trẻ sơ sinh (infant mortality) ở Việt Nam thay đổi như thế nào (tăng/giảm theo phần trăm) qua các năm 1980, 1990, 2000, và 2010? Bạn có nhận xét gì về sự thay đổi này không ?
VN.2010= filter(gapminder,country=="Vietnam",year==2010)
VN.2000= filter(gapminder,country=="Vietnam",year==2000)
VN.1990= filter(gapminder,country=="Vietnam",year==1990)
VN.1980= filter(gapminder,country=="Vietnam",year==1980)
growth_1990_1980 = VN.1990$infant_mortality/VN.1980$infant_mortality-1
growth_2000_1990 = VN.2000$infant_mortality/VN.1990$infant_mortality-1
growth_2010_2000 = VN.2010$infant_mortality/VN.2000$infant_mortality-1
growth_1990_1980
## [1] -0.2179487
growth_2000_1990
## [1] -0.2868852
growth_2010_2000
## [1] -0.2413793

#NHẬN XÉT: #TỈ LỆ TRẺ TỬ VONG Ở NĂM 1990 GIẢM 21,79% SO VỚI NĂM 1980 #TỈ LỆ TRẺ TỬ VONG Ở NĂM 2000 GIẢM 28,68% SO VỚI NĂM 1990 #TỈ LỆ TRẺ TỬ VONG Ở NĂM 2010 GIẢM 24,13% SO VỚI NĂM 2000 #CÓ THỂ THẤY TỈ LỆ TỬ VONG GIẢM QUA CÁC NĂM, ĐIỀU NÀY CHO THẤY CÔNG TÁC CHĂM SÓC Y TẾ, SỨC KHỎE #NGÀY CÀNG CẢI THIỆN, GIAI ĐOẠN 1990 → 2000 LÀ THỜI KỲ CÓ MỨC GIẢM MẠNH NHẤT (~28.69%). #GIAI ĐOẠN 2000 → 2010 VẪN GIẢM, NHƯNG CÓ XU HƯỚNG GIẢM CHẬM LẠI

#2. Thêm một cột mới có tên gdp_per_capital được tính bằng cách lấy GDP chia cho dân số. Trong mỗi châu lục, ba quốc gia nào có gdp_per_capital cao nhất vào các năm 1990, 2000 và 2010? Bạn có nhận xét gì về kết quả này không ?
dat=mutate(gapminder,gdp_per_capital=gdp/population)
#1990
top_3_1990 <- dat %>%
  filter(year == 1990) %>%
  arrange(desc(gdp_per_capital)) %>%
  head(3)

print(top_3_1990)
##                country year infant_mortality life_expectancy fertility
## 1 United Arab Emirates 1990             14.1            70.6      4.39
## 2                Japan 1990              4.6            79.0      1.57
## 3          Switzerland 1990              6.7            77.5      1.55
##   population          gdp continent         region gdp_per_capital
## 1    1811458 6.619208e+10      Asia   Western Asia        36540.78
## 2  122249285 4.229501e+12      Asia   Eastern Asia        34597.35
## 3    6673920 2.247734e+11    Europe Western Europe        33679.36
#2000
top_3_2000 <- dat %>%
  filter(year == 2000) %>%
  arrange(desc(gdp_per_capital)) %>%
  head(3)

print(top_3_2000)
##      country year infant_mortality life_expectancy fertility population
## 1 Luxembourg 2000              3.9            78.5      1.70     436107
## 2      Japan 2000              3.3            81.0      1.32  125714674
## 3     Norway 2000              4.0            78.6      1.85    4491572
##            gdp continent          region gdp_per_capital
## 1 2.026958e+10    Europe  Western Europe        46478.45
## 2 4.731199e+12      Asia    Eastern Asia        37634.42
## 3 1.682885e+11    Europe Northern Europe        37467.62
#2010
top_3_2010 <- dat %>%
  filter(year == 2010) %>%
  arrange(desc(gdp_per_capital)) %>%
  head(3)

print(top_3_2010)
##      country year infant_mortality life_expectancy fertility population
## 1 Luxembourg 2010              1.9            81.3      1.64     507889
## 2      Japan 2010              2.4            82.7      1.37  127319802
## 3     Norway 2010              2.6            81.1      1.95    4891251
##            gdp continent          region gdp_per_capital
## 1 2.651690e+10    Europe  Western Europe        52210.04
## 2 5.094423e+12      Asia    Eastern Asia        40012.81
## 3 1.954248e+11    Europe Northern Europe        39953.96

#United Arab Emirates ĐỨNG ĐẦU NĂM 1990, NHƯNG TỪ NĂM 2000 KHÔNG CÒN TRONG TOP 3 #JAPAN LUÔN ĐỨNG THỨ 2 TRONG TOP 3, CHỈ SỐ NÀY LUÔN TĂNG QUA CÁC NĂM, CHO THẤY SỰ ỔN ĐỊNH CỦA QUỐC GIA NÀY #Luxembourg ĐỨNG THỨ NHẤT 2 LẦN, Ở NĂM 2000 VÀ 2010, NHƯNG KHÔNG TRONG TOP 3 Ở NĂM 1990, CHO THẤY TỪ NĂM 1990-2000, QUỐC GIA NÀY CÓ SỰ TĂNG TRƯỞNG RÕ RỆT VÀ PHÁT HUY TỐT, ỔN ĐỊNH TRONG NHỮNG NĂM TIẾP THEO #NHÌN CHUNG CÁC QUỐC GIA TÌM RA ĐỀU CÓ TĂNG TRƯỞNG, CHỨNG TỎ NỀN KINH TẾ THẾ GIỚI ĐANG TRÊN ĐÀ TĂNG TRƯỞNG

#3.Xếp hạng của Việt Nam về gdp_per_capital trên thế giới, tại châu Á và khu vực Đông Nam Á vào các năm 1990, 2000 và 2010 là bao nhiêu? Bạn có nhận xét gì không ?
#1990
v1<-(dat%>% filter(year==1990) %>% arrange(desc(gdp_per_capital)))$country 
which(v1=="Vietnam")
## [1] 158
v1<-(dat%>% filter(year==1990, continent=="Asia") %>%  arrange(desc(gdp_per_capital)))$country 
which(v1=="Vietnam")
## [1] 39
v1<-(dat %>% filter(year==1990, region=="South-Eastern Asia") %>% arrange(desc(gdp_per_capital)))$country 
which(v1=="Vietnam")
## [1] 8
#2000
v1<-(dat%>% filter(year==2000) %>%  arrange(desc(gdp_per_capital)))$country 
which(v1=="Vietnam")
## [1] 152
v1<-(dat%>% filter(year==2000, continent=="Asia") %>% arrange(desc(gdp_per_capital)))$country 
which(v1=="Vietnam")
## [1] 40
v1<-(dat %>% filter(year==2000, region=="South-Eastern Asia") %>%  arrange(desc(gdp_per_capital)))$country 
which(v1=="Vietnam")
## [1] 7
#2010
v1<-(dat%>% filter(year==2010) %>% arrange(desc(gdp_per_capital)))$country 
which(v1=="Vietnam")
## [1] 132
v1<-(dat%>% filter(year==2010, continent=="Asia") %>% arrange(desc(gdp_per_capital)))$country 
which(v1=="Vietnam")
## [1] 36
v1<-(dat %>% filter(year==2010, region=="South-Eastern Asia") %>%  arrange(desc(gdp_per_capital)))$country 
which(v1=="Vietnam")  
## [1] 7

#NHẬN XÉT: NHÌN CHUNG TRONG GIAI ĐOẠN NÀY, TRÊN BXH THẾ GIỚI, VIỆT NAM TĂNG TỪ 158 LÊN THỨU 132, KHU VỰC CHÂU Á TĂNG TỪ 39 LÊN 36, KHU VỰC ĐÔNG NAM Á TĂNG TỪ 8 LÊN 7. KẾT QUẢ CHO THẤY VIỆT NAM CÓ PHÁT TRIỂN VỀ KINH TẾ NHƯNG CÒN CHẬM, NGOÀI RA KHU VỰC CHÂU Á VÀ ĐÔNG NAM Á CÓ TỐC ĐỘ PHÁT TRIỂN TƯƠNG ĐỐI ĐỒNG ĐỀU NÊN THỨ HẠNG CỦA VIỆT NAM Ở 2 KHU VỰC NÀY KHÔNG CÓ THAY ĐỔI NHIỀU.

#4. Mỹ là quốc gia có GDP lớn nhất thế giới qua nhiều năm trong khi Top 5 nước có GDP cao nhất lại có sự thay đổi đáng kể. Bạn có nhận xét gì về GDP của Mỹ và tổng GDP của 4 nước còn lại trong Top 5 nước có GDP cao nhất trên thế giới từ 1960 đến 2010 ?
# Lọc dữ liệu từ năm 1960 đến 2010
dat_filtered <- gapminder %>%
  filter(year >= 1960, year <= 2010)

# Lặp qua từng năm để lấy Top 5 quốc gia có GDP cao nhất
top5_gdp_data <- dat_filtered %>%
  group_by(year) %>%
  arrange(desc(gdp)) %>%
  slice(1:5) %>%  # Lấy top 5 GDP cao nhất
  mutate(is_USA = ifelse(country == "United States", "USA", "Other"))  # Đánh dấu Mỹ
# Tách GDP của Mỹ và tổng GDP của 4 nước còn lại
gdp_analysis <- top5_gdp_data %>%
  group_by(year) %>%
  summarise(
    GDP_USA = sum(gdp * (is_USA == "USA")),  # GDP của Mỹ
    GDP_Others = sum(gdp * (is_USA == "Other"))  # Tổng GDP của 4 nước còn lại
  )

# Vẽ biểu đồ so sánh GDP của Mỹ và tổng GDP 4 nước còn lại
ggplot(gdp_analysis, aes(x = year)) +
  geom_line(aes(y = GDP_USA, color = "Mỹ"), size = 1.2) +
  geom_line(aes(y = GDP_Others, color = "Top 4 còn lại"), size = 1.2) +
  labs(title = "So sánh GDP của Mỹ và 4 quốc gia còn lại trong Top 5 (1960-2010)",
       x = "Năm",
       y = "GDP (tỷ USD)",
       color = "Quốc gia") +
  theme_minimal()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

#NHẬN XÉT: #TỪ NĂM 1960-1970, GDP CỦA MỸ CAO HƠN TỔNG GDP 4 NƯỚC CÒN LẠI #TỪ NĂM 1970-KHOẢNG NĂM 1998, TỔNG GDP 4 QUỐC GIA CÒN LẠI CÓ XU HƯỚNG BẮT KỊP VÀ VƯỢT QUA MỸ, CHO THẤY SỰ PHÁT TRIỂN MẠNH MẼ CỦA CÁC QUỐC GIA CÒN LẠI, NGOÀI MỸ. #TỪ KHOẢNG NĂM 1998 TRỞ ĐI, ĐẾN KHOẢNG NĂM 2008, MỸ LẠI CÓ GDP CAO HƠN TỔNG 4 NƯỚC CÒN LẠI NHƯNG KHÔNG ĐÁNG KỂ #TỪ ĐÓ ĐẾN NĂM 2010, TỔNG GDP 4 NƯỚC CÒN LẠI TIẾP TỤC VƯỢT QUA MỸ, NHƯNG CON SỐ CHÊNH LỆCH KHÔNG ĐÁNG KỂ #CÓ THỂ THẤY GIAI ĐOẠN ĐẦU(ĐẾN KHOẢNG NĂM 1985), MỸ CÓ TĂNG TRƯỞNG NHƯNG KHÔNG QUÁ NHIỀU, GIAI ĐOẠN SAU ĐÓ ĐẾN 2010, MỸ TĂNG TRƯỞNG MẠNH HƠN #TỔNG GDP CỦA 4 QUỐC GIA CÒN LẠI CÓ XU HƯỚNG TĂNG NHANH HƠN, NHƯNG TỪ NĂM 2000-2010 LẠI CÓ XU HƯỚNG TĂNG CHẬM LẠI

#Dữ liệu “CafeF.HSX.Upto07.08.2024”
library(readr)
data <- read_csv("D:/KHOA HỌC DỮ LIỆU/CafeF.HSX.Upto07.08.2024.csv")
## Rows: 1260500 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): <Ticker>
## dbl (6): <DTYYYYMMDD>, <Open>, <High>, <Low>, <Close>, <Volume>
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
View(data)
#1.     Thêm một cột mới có tên Trading_Value, được tính bằng công thức: (High + Low)/2 * Volume.
#Giá trị giao dịch của một cổ phiếu trong một khoảng thời gian được hiểu là tổng giá trị giao dịch hàng ngày của cổ phiếu đó trong khoảng thời gian đó.

#Hỏi: tìm 5 mã cổ phiếu có Trading_Value cao nhất vào:
#•  Ngày 08/03/2022
#•  Trong tháng 03 năm 2022
#•  Trong năm 2022
library(dplyr)
names(data)=c("Ticker","Date","Open","High","Low","Close","Volume")

data1= mutate(data,Trading_Value=(High + Low)/2*Volume)
data1%>% filter(Date==20220308) %>% arrange(-Trading_Value)%>% head(6)
## # A tibble: 6 × 8
##   Ticker          Date   Open   High    Low  Close    Volume Trading_Value
##   <chr>          <dbl>  <dbl>  <dbl>  <dbl>  <dbl>     <dbl>         <dbl>
## 1 VNAll-INDEX 20220308 1538.  1538.  1512.  1513.  842012300       1.28e12
## 2 HPG         20220308   34.8   35.2   34.0   34.0  40509400       1.40e 9
## 3 SSI         20220308   40.4   41.9   40.1   40.9  24333500       9.97e 8
## 4 GEX         20220308   40.3   41.0   38.1   38.1  23652700       9.36e 8
## 5 DIG         20220308   73.9   76.6   71.8   71.8   9470200       7.02e 8
## 6 KBC         20220308   40.4   40.9   39     39    15754700       6.29e 8
data1%>% filter(Date%/%100==202203)%>%
  group_by(Ticker) %>% summarise(Trading_Value.m=sum(Trading_Value))%>%
  arrange(-Trading_Value.m)%>% head(6)
## # A tibble: 6 × 2
##   Ticker      Trading_Value.m
##   <chr>                 <dbl>
## 1 VNAll-INDEX         2.36e13
## 2 HPG                 1.96e10
## 3 STB                 1.32e10
## 4 GEX                 1.22e10
## 5 DXG                 1.13e10
## 6 NKG                 1.10e10
data1%>% filter(Date%/%10000==2022)%>%
  group_by(Ticker) %>% summarise(Trading_Value.m=sum(Trading_Value))%>%
  arrange(-Trading_Value.m)%>% head(6)
## # A tibble: 6 × 2
##   Ticker      Trading_Value.m
##   <chr>                 <dbl>
## 1 VNAll-INDEX         1.62e14
## 2 HPG                 1.40e11
## 3 STB                 1.18e11
## 4 SSI                 9.59e10
## 5 GEX                 8.81e10
## 6 DIG                 8.80e10
#2. 2.  Lợi suất (return) của một cổ phiếu từ ngày T1 đến ngày T2 được tính theo công thức:
#(Giá đóng cửa ngày T2) / (Giá đóng cửa ngày T1) - 1.
#Tức là nếu bạn đầu tư $1 vào cổ phiếu đó tại ngày T1 và giữ đến ngày T2, lợi suất đầu tư sẽ là:
#(Close_T2 / Close_T1) - 1 
#Hỏi: Tính tổng lợi suất tính đến ngày 08/03/2022 nếu bạn đầu tư 1 triệu đồng vào cổ phiếu của Tập đoàn Hòa Phát (mã HPG) vào mỗi ngày giao dịch kể từ ngày 02/01/2019?

data2= data %>% filter(Ticker=="HPG") 
re=rep(0,length(data2$Date))
for (i in 1:length(data2$Date)) {
  re[i]=data2$Close[i]/data2$Close[i+1]-1
}
data2=mutate(data2,re)
# Tong loi nhuan 
a=data2 %>% filter(Date>=20190102, Date<=20220308)
sum(a$re)
## [1] 1.418855