Skip to content

Instantly share code, notes, and snippets.

@kumeS
Last active December 10, 2022 12:40
Show Gist options
  • Save kumeS/b4c2a978b31dbe5fc3cb41c4d3e0b6ef to your computer and use it in GitHub Desktop.
Save kumeS/b4c2a978b31dbe5fc3cb41c4d3e0b6ef 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())))])
#ロード
for(n in 1:length(pack)){ eval(parse(text = paste0("library(", pack[n], ")"))) }
rm("n")
getDJIA_list <- function(nodes1=2){
DJIA_url <- "https://en.wikipedia.org/wiki/Dow_Jones_Industrial_Average"
#browseURL(DJIA_url)
DJIA <- DJIA_url %>%
read_html() %>%
html_nodes("table") %>%
.[[nodes1]] %>%
html_table
DJIA.d <- data.frame(DJIA[,-c(5:7)])
colnames(DJIA.d) <- c("Company", "Exchange", "Ticker", "Sector")
return(DJIA.d)
}
DJIA_ChartData <- function(Dat, term=c("2022-01-01", "2022-12-31")){
#Dat=DJIAList; term=c("2022-01-01", "2022-12-31")
Ticker <- Dat$Ticker
#期間の定義
List <- as.character(Ticker)
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)
#head(List01)
#年初時の株価を 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)
}
DJIA_ChartData_mod <- function(Dat, dig=1, top=30){
#Dat=ChartData0; dig=1; top=30
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")]
#head(Dat0)
return(Dat0)
}
DJIA_animation <- function(Dat, Size1=4.5, Size2=5, Label, mar=c(0.5, 1.5, 0.5, 0.75)){
#Dat=ChartData1; Size1=2.5; Size2=5; Label="test"; mar=c(0.5, 1.5, 0.5, 0.75)
#head(Dat)
p <- ggplot(Dat,
aes(x = ranking, group=CompanyTicker, 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(CompanyTicker, " ")), colour = "black", size = Size1, vjust = 0.4, hjust = 0) +
geom_text(aes(y=close, label = close, hjust=0), size = Size2, hjust = -0.1) +
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 = "")
#p
return(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment