Skip to content

Instantly share code, notes, and snippets.

@kumeS
Last active November 25, 2022 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kumeS/c9883239311546c5ab1753676fa86514 to your computer and use it in GitHub Desktop.
Save kumeS/c9883239311546c5ab1753676fa86514 to your computer and use it in GitHub Desktop.
#パッケージ・インストール
pack <- c("rvest", "quantmod", "magrittr", "purrr", "tidyr", "ggplot2", "treemapify", "gganimate", "gapminder", "gifski")
install.packages(pack[!(pack %in% unique(rownames(installed.packages())))])
#ロード
library(rvest)
library(quantmod)
library(magrittr)
library(purrr)
library(tidyr)
library(ggplot2)
library(treemapify)
library(gganimate)
library(gapminder)
library(gifski)
#関数定義: 日経225のWikipediaページから銘柄リストを取得する
getNikkei225_list <- function(nodes1=6:40, nodes2=7:41){
Nikkei225_url <- "https://ja.wikipedia.org/wiki/%E6%97%A5%E7%B5%8C%E5%B9%B3%E5%9D%87%E6%A0%AA%E4%BE%A1"
#browseURL(Nikkei225_url)
Nikkei225.a <- Nikkei225_url %>%
read_html() %>%
html_nodes("table") %>%
html_table() %>%
.[6:40]
Nikkei225.b <- Nikkei225_url %>%
read_html() %>%
html_nodes("h3") %>%
html_text() %>%
.[nodes2]
Nikkei225.b1 <- unlist(purrr::map(Nikkei225.b, function(x){base::strsplit(x, split="(")[[1]][1]}))
#属性
for(n in 1:length(Nikkei225.a)){
Nikkei225.a[[n]]$`備考` <- Nikkei225.b1[n]
}
#head(Nikkei225.a)
#リストデータをデータフレームへ変換
Nikkei225 <- c()
for(n in 1:length(Nikkei225.a)){
Nikkei225 <- Nikkei225 %>% rbind(Nikkei225.a[[n]])
}
Nikkei225.d <- data.frame(Nikkei225)
#head(Nikkei225.d)
colnames(Nikkei225.d) <- c("Ticker", "Company", "Sector")
return(Nikkei225.d)
}
Nikkei225_ChartData <- function(Dat, term=c("2022-01-01", "2022-12-31")){
#Dat=Nikkei225List; term=c("2022-01-01", "2022-12-31")
Ticker <- Dat$Ticker
#期間の定義
List <- paste0(as.character(unlist(Ticker)), ".T")
quantmod::getSymbols(List, src = "yahoo", verbose = T, from = term[1], to=term[2])
#空のデータフレームの作成
m <- max(c(nrow(get(List[1])), nrow(get(List[2])), nrow(get(List[3])), nrow(get(List[4]))))
stock <- data.frame(matrix(NA, nrow=m, ncol=length(List)))
rownames(stock) <- rownames(data.frame(get(List[1])))
colnames(stock) <- List
#head(stock)
#データの代入
for(n in seq_len(length(List))){
a <- as.numeric(get(List[n])[,4])
if(length(a) == m){
stock[,n] <- a
}
}
#変数削除
rm(list = List)
#NA列を除く
stock0 <- stock[,apply(stock, 2, function(x){sum(is.na(x))}) == 0]
List01 <- Dat[apply(stock, 2, function(x){sum(is.na(x))}) == 0,]
#データ取得完了
#head(stock0)
#年初時の株価を 100 に補正
stock.c <- stock0
for(n in 1:ncol(stock0)){
stock.c[,n] <- as.numeric(stock0[,n])/as.numeric(stock0[1,n])*100
}
#head(stock.c)
#データの行列を入れ替える
stock.t <- t(stock.c)
#head(stock.t)
#stock01 <- data.frame(Ticker=List01$Company, Sector=List01$Sector, stock.t)
#stock01 <- data.frame(Ticker=paste0(List01$Company, "(", List01$Ticker, ")"), Sector=List01$Sector, stock.t)
stock01 <- data.frame(Company=List01$Company, Ticker=List01$Ticker, Sector=List01$Sector, stock.t)
rownames(stock01) <- 1:nrow(stock01)
#head(stock01)
stock02 <- stock01
stock03 <- gather(stock02, key="date", value="close", -c(Company, Ticker, Sector))
stock03$date <- sub("X", "", stock03$date)
stock03$date <- gsub("\\.", "/", stock03$date)
stock03$date <- paste0(stock03$date, "-16-00-00")
#head(stock03)
#日時列に変える
stock03$date <- as.Date(stock03$date)
#株価の変動幅から、カラーを決める
#head(stock03)
stock03$dclose <- stock03$close - 100
stock03$dclose2 <- NA
colfunc <- grDevices::colorRampPalette(c("brown3", "white", "darkgreen"))
a <- colfunc(18)
b1 <- seq(min(stock03$dclose)-10, 0, length.out=9)
b2 <- seq(0, max(stock03$dclose)+10, length.out=9)
b3 <- c(b1, b2[-1])
for(n in length(b3):1){
stock03$dclose2[stock03$dclose < b3[n]] <- a[n]
}
#ranking
stock03$ranking <- NA
#head(stock03)
ab <- unique(stock03$date)
for(l in 1:length(ab)){
#l <- 1
if(l == 1){
bc <- stock03$date == ab[l]
stock03[bc,]$ranking <- 1:nrow(List01)
}else{
#l <- 2
bc <- stock03$date == ab[l]
cd <- order(stock03[bc,]$close, decreasing = T)
for(k in 1:nrow(List01)){
stock03[bc,]$ranking[cd[k]] <- k
}
}
}
return(stock03)
#head(stock03)
#table(stock03$ranking)
#table(stock03$date)
}
Nikkei225_ChartData_mod <- function(Dat, dig=1, top=20){
#Dat=ChartData0; dig=2; top=20
Dat$CompanyTicker <- paste0(Dat$Company, "(", Dat$Ticker, ")")
Dat$CompanySector <- paste0(Dat$Company, "(", Dat$Sector, ")")
Dat <- Dat[order(Dat$CompanyTicker, decreasing = F),]
Dat$close <- round(Dat$close, digits=dig)
Dat$dclose <- round(Dat$dclose, digits=dig)
if(top > 0){
Dat0 <- Dat[Dat$ranking <= top,]
}else{
Dat0 <- Dat[c(Dat$ranking >= max(Dat$ranking) + top),]
}
#head(Dat)
Dat0 <- Dat0[,c("Company", "Ticker", "Sector", "CompanyTicker","CompanySector",
"date", "close", "dclose", "dclose2", "ranking")]
return(Dat0)
}
Nikkei225_animation <- function(Dat, Size1=3.5, Size2=5, Label, mar=c(0.5, 1.5, 0.5, 0.75)){
p <- ggplot(Dat,
aes(x = ranking, group=CompanySector, fill = as.factor(Sector), color = as.factor(Sector))) +
geom_tile(aes(y = close/2, height = close, width = 0.9), alpha = 0.8, color = NA) +
geom_text(aes(y = 0, label = paste(CompanySector, " ")), colour = "black", size = Size1, vjust = 0.2, hjust = 0) +
geom_text(aes(y=close, label = close, hjust=0), size = Size2) +
coord_flip(clip = "off", expand = FALSE) +
scale_x_reverse() +
scale_y_continuous(labels = scales::comma) +
theme(axis.line=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
legend.position="none",
panel.border=element_blank(),
axis.ticks=element_blank(),
panel.background=element_blank(),
panel.grid.major.x = element_line( linewidth=.1, color="grey" ),
panel.grid.minor.x = element_line( linewidth=.1, color="grey" ),
plot.title=element_text(size=22, hjust=0.5, face="bold", vjust=-1, lineheight = 1, family = "HiraKakuPro-W3"),
plot.subtitle=element_text(size=15, hjust=0.5, family = "HiraKakuPro-W3"),
plot.caption =element_text(size=8, hjust=0.5, face="italic", color="grey"),
plot.background=element_blank(),
plot.margin =unit(mar, "cm")) +
gganimate::view_follow(fixed_x = TRUE, fixed_y = TRUE)
#The order of edges for plot.margin is unit(c(top, right, bottom, left), units)
#アニメーション
p <- p +
transition_states(date, transition_length = 1, state_length = 1, wrap = FALSE) +
#transition_time(date) +
ease_aes('linear') +
labs(title = paste0(Label, ': {closest_state}'), subtitle = "", caption = "")
return(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment