# CSVデータをウェブサイトから取得する。
d0 <- read.csv('https://stats.dip.jp/01_ds/data/load_amedas_y2022_tokyo.csv')

# データの期間を絞る(2022年5月1日~2022年6月30日)
is.term <- '2022-05-01' <= d0$date & d0$date <= '2022-06-30'
d1 <- d0[is.term, ]

n <- nrow(d1)                 # データサイズ
t <- 1:n                      # 経過時間(hour)
px <- as.POSIXct(d1$datetime) # 時間オブジェクトに変換 
y <- d1$mw / 1000             # 測定値 (単位変換:MW -> GW)
d1 <- data.frame(px = format(px, '%Y-%m-%d %H'), t, y)

head(d1) # データの先頭の5行を表示
##              px t     y
## 1 2022-05-01 00 1 21.62
## 2 2022-05-01 01 2 20.65
## 3 2022-05-01 02 3 20.61
## 4 2022-05-01 03 4 20.81
## 5 2022-05-01 04 5 20.86
## 6 2022-05-01 05 6 20.72
library('forecast')
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
# LOESS(局所回帰)のフィッティング(fitting)
# 平滑化窓幅(span):30日(トレンドを捉えるのに十分な窓幅を設定する)
fit1 <- loess(y ~ t,
              data = data.frame(px, t = 1:n, y), 
              span = 24 * 30 / n)

# フィット値(fitted values)がトレンドとなる。
trend <- fit1$fitted

# 折れ線プロット(原系列)
matplot(px, y, type = 'l', pch = 1, col = 2,
        main = '電力需要',
        xlab = '月 日',
        ylab = 'GW')

abline(h = 0, col = 'gray') # x軸線

# 折れ線プロット(トレンド成分)
matlines(px, 
         trend, 
         pch = 2, 
         col = 4, 
         lwd = 2)

# 凡例(はんれい)
legend('topleft', lty = 1, col = c(2, 4), 
       legend = c('原系列', 'トレンド'))

# 残余成分(トレンド除去成分)計算
detrended <- y - trend

# 折れ線プロット(残余成分)
matplot(px, detrended, type = 'l', pch = 1, col = 2,
        main = '残余成分(原系列-トレンド)',
        xlab = '月 日',
        ylab = 'GW')

abline(h = 0, col = 'gray') # x軸線

fit2 <- loess(y ~ t, 
              data = data.frame(px, t = 1:n, y = detrended), 
              span = 24 * 4 / n)

seasonal <- fit2$fitted

# 折れ線プロット(トレンド除去成分・周期成分)
matplot(px, detrended, type = 'l', pch = 1, col = 2, ylim = c(-15, 15),
        main = '残余成分(トレンド除去後の成分)・周期成分',
        xlab = '月 日',
        ylab = 'GW')

# 折れ線プロット(周期成分)
matlines(px, seasonal, pch = 2, col = 4, lwd = 2)

abline(h = 0, col = 'gray') # x軸線

# 残余成分を計算(トレンド除去成分-周期成分)
remainder <- detrended - seasonal

# 折れ線プロット(残余成分)
matplot(px, remainder, type = 'l', pch = 1, col = 2, ylim = c(-15, 15),
        main = '残余成分(トレンド,周期成分除去後の成分)',
        xlab = '月 日',
        ylab = 'GW')

abline(h = 0, col = 'gray') # x軸線

s <- mstl(x = msts(y, seasonal.period = c(24, 24*7)),
          s.window = 'periodic')

autoplot(s, main = '周期成分:時間変動なし')

s <- mstl(x = msts(y, seasonal.period = c(24, 24*7)))

autoplot(s, main = '周期成分:時間変動あり')

px <- seq(as.POSIXct('1949-01-01'),
          as.POSIXct('1960-12-01'), by = 'month')

d0 <- data.frame(px = paste(px), y = AirPassengers)

library(DT)
datatable(d0)
s <- mstl(x = msts(y, seasonal.period = c(12, 12*7)),
          s.window = 'periodic')

autoplot(s, main = '周期成分:時間変動なし')

d <- read.csv(file = 'https://stats.dip.jp/01_ds/data/univ_exam_data.csv')

library(DT)
datatable(d, caption = '勉強時間と大学合否')
fit <- glm(合格 ~ 勉強時間, data = d, family = 'binomial')
#summary(fit)
library(sjPlot)
## #refugeeswelcome
tab_model(fit, show.aic = T)
  合格
Predictors Odds Ratios CI p
(Intercept) 0.06 0.00 – 0.51 0.029
勉強時間 1.94 1.25 – 3.86 0.015
Observations 20
R2 Tjur 0.446
AIC 21.662
x <- d$勉強時間
y <- d$合格

matplot(x = x, y = y, pch = 1,
        ylim = c(0, 1.1), xlim = c(0, 10),
        main = 'ロジスティック回帰分析',
        xlab = '平均勉強時間',
        ylab = '合格(1),不合格(0)')
grid()

xp <- seq(0, 10, 0.1)
yp <- predict(fit, type = 'response', newdata = data.frame(勉強時間 = xp))

matlines(x = xp, y = yp, lty = 1, col = 2, lwd = 2)

libraryx <- d$勉強時間
y <- d$合格

matplot(x = x, y = y, pch = 1,
        ylim = c(0, 1.1), xlim = c(0, 10),
        main = 'ロジスティック回帰分析',
        xlab = '平均勉強時間',
        ylab = '合格(1),不合格(0)')
grid()

xp <- seq(0, 10, 0.1)
yp <- predict(fit, type = 'response', newdata = data.frame(勉強時間 = xp))

matlines(x = xp, y = yp, lty = 1, col = 2, lwd = 2)

library(latex2exp)
text(x = 3.8, y = 0.4, adj = 0, 
     TeX('$\\leftarrow \\hat{p}=\\frac{1}{1+exp\\{-(b_0 + b_1 x)\\}}$'))
legend('topleft', pch = c(1, NA), lty = c(NA, 1), col = c(1, 2),
       legend = c('合格(1),不合格(0)', 'ロジスティック回帰モデル'))
text(x = 3.8, y = 0.4, adj = 0, 
     TeX('$\\leftarrow \\hat{p}=\\frac{1}{1+exp\\{-(b_0 + b_1 x)\\}}$'))
legend('topleft', pch = c(1, NA), lty = c(NA, 1), col = c(1, 2),
       legend = c('合格(1),不合格(0)', 'ロジスティック回帰モデル'))

yp <- predict(fit, type = 'response', newdata = data.frame(勉強時間 = 5.5))
sprintf('合格確率:%2.1f%', yp * 100)
## [1] "合格確率:70.9%"
d <- read.csv(file = 'https://stats.dip.jp/01_ds/data/gender.csv')

library(DT)
datatable(d, caption = '性別データ')
set.seed(1) # 乱数シード
n <- 100000 # データサイズ

# 正常値
rv <- runif(n = n, min = 0, max = 1) # 一様乱数

# 異常値1(負の値)
size <- 3   # ランダムサンプルサイズ
ii <- sample(n, size) # インデックスランダムサンプル
rv[ii] <- runif(n = size, min = -1, max = 0)

# 異常値2(とても大きな/小さな値)
rv[39] <- 22
rv[52] <- -21
rv[91] <- 11

# 小数点第2位に丸め行列(列数:100)に変換
m <- matrix(round(rv, 2), ncol = 100)

write.csv(as.data.frame(m), 
       file = 'data_cleansing2_dirty_data.csv',
       row.names = F, quote = F) 
# CSVデータを行列オブジェクトに変換
d <- read.csv(file = 'https://stats.dip.jp/01_ds/data/data_cleansing2_dirty_data.csv')
m <- as.matrix(d) 
boxplot(m)

any(m < 0)
## [1] TRUE
any(abs(m) > 3*sd(m)) # 3シグマ(標準偏差の3倍)を超えるデータが存在
## [1] TRUE
jj <- 36:46
boxplot(m[, jj])

# 異常値が入っているカラム(列)の棒グラフを作成 
j <- 37
y <- m[, j]

barplot(height    = y,         # 棒グラフの高さ
        names.arg = 1:nrow(m)) # 横軸名

ii <- 140:231
y <- m[ii, j]

barplot(height    = y,                        # 棒グラフの高さ
        cex.names = 0.4,                      # 横軸ラベルの大きさ
        names.arg = paste(ii, '\n(', y, ')')) # 横軸名 \nで改行して値も()内に表示

# さらにレコード(行)の範囲を絞り特定する。
ii <- 194:206
y <- m[ii, j]

barplot(height    = y,                        # 棒グラフの高さ
        cex.names = 0.4,                      # 横軸ラベルの大きさ
        names.arg = paste(ii, '\n(', y, ')')) # 横軸名 \nで改行して値も表示

# 異常値を特定
m[200, j]
##   V37 
## -0.78
# 負の値
m[m < 0]
## [1] -21.00  -0.78  -0.99  -0.68
# 3シグマ(標準偏差の3倍)を超える値
sigma <- sd(m) # 標準偏差

#m[abs(m) > 3*sigma] # 数が多いためコメントアウトした。

# 4シグマ(標準偏差の4倍)を超える値
m[abs(m) > 4*sigma]
## [1]  22 -21  11
# 行と列のインデックス(Row, Col)と値(Value)のデータを作成
m.a <- NULL # 結果格納用の空のオブジェクトを作成

for (i in 1:nrow(m))
{
  for (j in 1:ncol(m))
  {
    if ( m[i, j] < 0 | m[i, j] > 4*sigma)
    {
      cat('Row:', i, ', Col:', j, ', Value: ', m[i, j], fill = T) 
      m.a <- rbind(m.a, t(c(i, j, m[i, j]))) # rbind:行ベクトルを追加
    }
  }
}
## Row: 39 , Col: 1 , Value:  22
## Row: 52 , Col: 1 , Value:  -21
## Row: 91 , Col: 1 , Value:  11
## Row: 200 , Col: 37 , Value:  -0.78
## Row: 242 , Col: 100 , Value:  -0.68
## Row: 521 , Col: 59 , Value:  -0.99
# 結果表示
colnames(m.a) <- c('Row', 'Col', 'Value')
m.a
##      Row Col  Value
## [1,]  39   1  22.00
## [2,]  52   1 -21.00
## [3,]  91   1  11.00
## [4,] 200  37  -0.78
## [5,] 242 100  -0.68
## [6,] 521  59  -0.99
d <- read.csv(file = 'https://stats.dip.jp/01_ds/data/data_cleansing2_dirty_data_exercise.csv')

library(DT)
datatable(d)
d0 <- read.csv(file = 'https://stats.dip.jp/01_ds/data/dirty_data1.csv')

summary(d0) # 要約統計値 NA's:1 (NAが1つ含まれている)
##     会社名               気温            湿度             風速       
##  Length:22          Min.   :12.00   Min.   :-50.00   Min.   :-1.000  
##  Class :character   1st Qu.:20.00   1st Qu.: 30.00   1st Qu.: 1.000  
##  Mode  :character   Median :32.40   Median : 50.00   Median : 2.000  
##                     Mean   :28.18   Mean   : 39.73   Mean   : 2.052  
##                     3rd Qu.:34.10   3rd Qu.: 51.00   3rd Qu.: 4.000  
##                     Max.   :50.40   Max.   : 60.00   Max.   : 5.000  
##                     NA's   :1                        NA's   :1
library(DT)
datatable(d0)
d1 <- na.omit(d0)

summary(d1) # 要約統計値 NAがなくなった。
##     会社名               気温            湿度             風速       
##  Length:20          Min.   :12.00   Min.   :-50.00   Min.   :-1.000  
##  Class :character   1st Qu.:18.50   1st Qu.: 27.50   1st Qu.: 0.750  
##  Mode  :character   Median :32.40   Median : 50.00   Median : 2.000  
##                     Mean   :27.97   Mean   : 38.55   Mean   : 2.105  
##                     3rd Qu.:34.10   3rd Qu.: 51.00   3rd Qu.: 4.000  
##                     Max.   :50.40   Max.   : 60.00   Max.   : 5.000
datatable(d1)
# 各気象変数の許容範囲に入っているか否かを示す論理式を作成
is.tp <- -20 <= d1$気温 & d1$気温 <=  50
is.hm <-   0 <= d1$湿度 & d1$湿度 <= 100
is.ws <-   0 <= d1$風速 & d1$風速 <=  70

summary(is.tp)
##    Mode   FALSE    TRUE 
## logical       2      18
summary(is.hm)
##    Mode   FALSE    TRUE 
## logical       1      19
summary(is.ws)
##    Mode   FALSE    TRUE 
## logical       1      19
# 適切な範囲のレコードだけを抽出する。
d2 <- d1[is.tp & is.hm & is.ws, ]

datatable(d2)
d3 <- d2
d3$気温 <- round(d2$気温, 1)
d3$湿度 <- round(d2$湿度, 0)
d3$風速 <- round(d2$風速, 0)

datatable(d3)
d3$会社名
##  [1] "ソニー"         "Sony"           "SONY"           "sony"          
##  [5] "ソニー株式会社" "Sony(株)"     "ソニー(株)"     "sony"          
##  [9] "富士通"         "Fujitsu"        "Fujitu"         "FUJITSU"       
## [13] "富士通株式会社" "富士通(株)"     "fujitsu"        "FUJITSU"
# ソニー株式会社を意味する表記
LAB.SONY <- c("ソニー", "Sony(株)", "ソニー(株)", "Sony", "SONY", "sony")

# 富士通株式会社を意味する表記
LAB.FUJITSU <- c("富士通", "富士通(株)", "Fujitsu", "FUJITSU", "fujitsu", "Fujitu", "fujitu")

# %in%の記号は右辺の集合に含まれるか否かを示す論理記号
is.sony    <- d3$会社名 %in% LAB.SONY
is.fujitsu <- d3$会社名 %in% LAB.FUJITSU

d4 <- d3

# 各メーカーの正式名称に統一
d4$会社名[is.sony]    <- 'ソニー株式会社'
d4$会社名[is.fujitsu] <- '富士通株式会社'

d4$会社名
##  [1] "ソニー株式会社" "ソニー株式会社" "ソニー株式会社" "ソニー株式会社"
##  [5] "ソニー株式会社" "ソニー株式会社" "ソニー株式会社" "ソニー株式会社"
##  [9] "富士通株式会社" "富士通株式会社" "富士通株式会社" "富士通株式会社"
## [13] "富士通株式会社" "富士通株式会社" "富士通株式会社" "富士通株式会社"
# クリーンデータ(clean data)
datatable(d4)
d <- read.csv(file = 'https://stats.dip.jp/01_ds/data/dirty_data2.csv')

datatable(d)
d0 <- read.csv(file = 'https://stats.dip.jp/01_ds/data/dirty_data1.csv')

summary(d0) # 要約統計値 NA's:1 (NAが1つ含まれている)
##     会社名               気温            湿度             風速       
##  Length:22          Min.   :12.00   Min.   :-50.00   Min.   :-1.000  
##  Class :character   1st Qu.:20.00   1st Qu.: 30.00   1st Qu.: 1.000  
##  Mode  :character   Median :32.40   Median : 50.00   Median : 2.000  
##                     Mean   :28.18   Mean   : 39.73   Mean   : 2.052  
##                     3rd Qu.:34.10   3rd Qu.: 51.00   3rd Qu.: 4.000  
##                     Max.   :50.40   Max.   : 60.00   Max.   : 5.000  
##                     NA's   :1                        NA's   :1
d0 <- read.csv(file = 'https://stats.dip.jp/01_ds/data/dirty_data1.csv')

summary(d0) # 要約統計値 NA's:1 (NAが1つ含まれている)
##     会社名               気温            湿度             風速       
##  Length:22          Min.   :12.00   Min.   :-50.00   Min.   :-1.000  
##  Class :character   1st Qu.:20.00   1st Qu.: 30.00   1st Qu.: 1.000  
##  Mode  :character   Median :32.40   Median : 50.00   Median : 2.000  
##                     Mean   :28.18   Mean   : 39.73   Mean   : 2.052  
##                     3rd Qu.:34.10   3rd Qu.: 51.00   3rd Qu.: 4.000  
##                     Max.   :50.40   Max.   : 60.00   Max.   : 5.000  
##                     NA's   :1                        NA's   :1
library(DT)
datatable(d0)
d1 <- na.omit(d0)

summary(d1) # 要約統計値 NAがなくなった。
##     会社名               気温            湿度             風速       
##  Length:20          Min.   :12.00   Min.   :-50.00   Min.   :-1.000  
##  Class :character   1st Qu.:18.50   1st Qu.: 27.50   1st Qu.: 0.750  
##  Mode  :character   Median :32.40   Median : 50.00   Median : 2.000  
##                     Mean   :27.97   Mean   : 38.55   Mean   : 2.105  
##                     3rd Qu.:34.10   3rd Qu.: 51.00   3rd Qu.: 4.000  
##                     Max.   :50.40   Max.   : 60.00   Max.   : 5.000
# 各気象変数の許容範囲に入っているか否かを示す論理式を作成
is.tp <- -20 <= d1$気温 & d1$気温 <=  50
is.hm <-   0 <= d1$湿度 & d1$湿度 <= 100
is.ws <-   0 <= d1$風速 & d1$風速 <=  70

summary(is.tp)
##    Mode   FALSE    TRUE 
## logical       2      18
summary(is.hm)
##    Mode   FALSE    TRUE 
## logical       1      19
summary(is.ws)
##    Mode   FALSE    TRUE 
## logical       1      19
# 適切な範囲のレコードだけを抽出する。
d2 <- d1[is.tp & is.hm & is.ws, ]

datatable(d2)
d3 <- d2
d3$気温 <- round(d2$気温, 1)
d3$湿度 <- round(d2$湿度, 0)
d3$風速 <- round(d2$風速, 0)

datatable(d3)
d3$会社名
##  [1] "ソニー"         "Sony"           "SONY"           "sony"          
##  [5] "ソニー株式会社" "Sony(株)"     "ソニー(株)"     "sony"          
##  [9] "富士通"         "Fujitsu"        "Fujitu"         "FUJITSU"       
## [13] "富士通株式会社" "富士通(株)"     "fujitsu"        "FUJITSU"
# ソニー株式会社を意味する表記
LAB.SONY <- c("ソニー", "Sony(株)", "ソニー(株)", "Sony", "SONY", "sony")

# 富士通株式会社を意味する表記
LAB.FUJITSU <- c("富士通", "富士通(株)", "Fujitsu", "FUJITSU", "fujitsu", "Fujitu", "fujitu")

# %in%の記号は右辺の集合に含まれるか否かを示す論理記号
is.sony    <- d3$会社名 %in% LAB.SONY
is.fujitsu <- d3$会社名 %in% LAB.FUJITSU

d4 <- d3

# 各メーカーの正式名称に統一
d4$会社名[is.sony]    <- 'ソニー株式会社'
d4$会社名[is.fujitsu] <- '富士通株式会社'

d4$会社名
##  [1] "ソニー株式会社" "ソニー株式会社" "ソニー株式会社" "ソニー株式会社"
##  [5] "ソニー株式会社" "ソニー株式会社" "ソニー株式会社" "ソニー株式会社"
##  [9] "富士通株式会社" "富士通株式会社" "富士通株式会社" "富士通株式会社"
## [13] "富士通株式会社" "富士通株式会社" "富士通株式会社" "富士通株式会社"
# クリーンデータ(clean data)
datatable(d4)
d0 <- read.csv('https://stats.dip.jp/01_ds/data/load_amedas_y2017-2022_tokyo.csv')

head(d0)
##         date            datetime dow       name    event    md gr year month
## 1 2017-01-01 2017-01-01 00:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 2 2017-01-01 2017-01-01 01:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 3 2017-01-01 2017-01-01 02:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 4 2017-01-01 2017-01-01 03:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 5 2017-01-01 2017-01-01 04:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 6 2017-01-01 2017-01-01 05:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
##   day su mo tu we th fr sa wd ho bw af sp ab    mw     time hr mi    hm rm   ws
## 1   1  1  0  0  0  0  0  0  0  1  0  0  1  0 27830 00:00:00  0  0 77.43  0 2.32
## 2   1  1  0  0  0  0  0  0  0  1  0  0  1  0 26340 01:00:00  1  0 71.00  0 2.52
## 3   1  1  0  0  0  0  0  0  0  1  0  0  1  0 25200 02:00:00  2  0 68.86  0 1.52
## 4   1  1  0  0  0  0  0  0  0  1  0  0  1  0 24380 03:00:00  3  0 71.43  0 1.40
## 5   1  1  0  0  0  0  0  0  0  1  0  0  1  0 23890 04:00:00  4  0 74.86  0 1.97
## 6   1  1  0  0  0  0  0  0  0  1  0  0  1  0 23940 05:00:00  5  0 73.71  0 2.25
##     tp tp3h tp5h tp3d tp7d
## 1 4.87 5.31 5.53 5.50 6.74
## 2 4.49 5.01 5.20 5.53 6.73
## 3 4.07 4.48 4.90 5.54 6.72
## 4 3.91 4.16 4.60 5.56 6.71
## 5 3.19 3.72 4.11 5.58 6.69
## 6 3.14 3.41 3.76 5.61 6.68
d <- d0['2022-06-01' <= d0$date & d0$date <= '2022-07-03', ]
n <- nrow(d)
d$px <- as.POSIXct(d$datetime)
d$gw <- d$mw / 1000 # 測定値 (単位変換:MW -> GW)

# 気温欠損値処理(1箇所)
i.tp.na <- which(d$tp < -100)
d$tp[i.tp.na] <- mean(d$tp[c(i.tp.na-1, i.tp.na+1)])

# Suffixとしてtr: training term, te: test term, al: all term を使用する。

# 訓練期間フラグ
d.tr <- d['2017-06-01' <= d$date & d$date <= '2022-06-30', ]
n.tr <- nrow(d.tr)
ii.tr <- 1:n.tr

# テスト期間フラグ
d.te <- d['2022-07-01' <= d$date & d$date <= '2022-07-03', ]
n.te <- nrow(d.te)
ii.te <- (n.tr + 1):n

# グラフ表示期間フラグ
is.plot <- '2022-06-28' <= d$date & d$date <= '2022-07-03'
d.plot <- d[is.plot, ] # グラフ表用データ

#cairo_pdf('electricity_regarima.pdf')
matplot(d.tr$px, d.tr$gw, type = 'l', col = 2, ylim = c(0, 60),
        main = '電力需要', xlab = '年', ylab = '電力需要[GW], 気温[℃]')
matlines(d.tr$px, d.tr$tp, type = 'l', col = 4)
legend('topleft', lty = 1, col = c(2, 4), 
       legend = c('電力需要[GW]', '気温[℃]'))

#dev.off()
#View(d.tr[, c('datetime', 'tp')])

fq <- 24
fit <- lm(gw ~ tp + I(tp^2) + sa + su - 1, data = d.tr)
d.tr$gw.tp.adj <- d.tr$gw - fit$fitted

matplot(d.tr$gw.tp.adj, type = 'l', pch = 1, col = 2, ylab = 'y')

a <- acf(d.tr$gw.tp.adj, lag.max = 50) # MA(q)
grid()
abline(v = fq, col = 3, lty = 3)

q <- 0
pa <- pacf(d.tr$gw.tp.adj, lag.max = 50) # AR(p)【注意】acfと違いグラフが1次ラグから始まる。
grid()
abline(v = fq, col = 3, lty = 3)

p <- 2
library(forecast)
fit.arima <- Arima(ts(d.tr$gw, frequency = fq),
                   xreg     =  model.matrix(fit, data = d.tr),
                   order    = c(p, 0, q),
                   seasonal = c(1, 0, 0)) # SARIMA
fit.arima
## Series: ts(d.tr$gw, frequency = fq) 
## Regression with ARIMA(2,0,0)(1,0,0)[24] errors 
## 
## Coefficients:
##          ar1      ar2    sar1  intercept       tp  I(tp^2)       sa       su
##       1.5421  -0.5814  0.8821    38.1882  -0.5204   0.0122  -0.1601  -0.1879
## s.e.  0.0334   0.0335  0.0186     3.7493   0.1620   0.0033   0.1266   0.1271
## 
## sigma^2 = 0.2449:  log likelihood = -531.2
## AIC=1080.39   AICc=1080.65   BIC=1121.61
checkresiduals(fit.arima) # 残差分析グラフ

## 
##  Ljung-Box test
## 
## data:  Residuals from Regression with ARIMA(2,0,0)(1,0,0)[24] errors
## Q* = 141.08, df = 45, p-value = 7.651e-12
## 
## Model df: 3.   Total lags used: 48
pred <- forecast(fit.arima, xreg = model.matrix(fit, data = d.te), level = 95)
#cairo_pdf('regarima_forecast.pdf')
matplot(d.plot$px, d.plot$gw, type = 'o', pch = 16, col = 2, main = pred$method)
grid()
abline(v = n.tr + 1, lty  = 3, col = 3)
matlines(d.tr$px, fit.arima$fitted, type = 'o', pch = 16, lty = 2, col = 4)
matlines(d.te$px, pred$mean,        type = 'o', pch =  1, lty = 2, col = 4)
matlines(d.te$px, pred$lower, lty = 3, col = 'gray')
matlines(d.te$px, pred$upper, lty = 3, col = 'gray')
legend('topleft', bg = 'white', lty = c(1, 2, 2, 3),
       col = c(2, 4, 4, 'gray'), pch = c(16, 16, 1, NA),
       legend = c('原系列', '1期先予測値', '予測値', '95%予測区間'))

#dev.off()
get.accuracy <- function(yhat, y)
{
  data.frame(MBE  = mean(yhat - y),
             MAE  = mean(abs(yhat - y)),
             MAPE = mean(abs((yhat - y) / y)) * 100,
             RMSE = sqrt(mean((yhat - y)^2))
  )
}

get.accuracy(yhat = pred$mean, y = d.te$gw)
##        MBE      MAE     MAPE     RMSE
## 1 1.915914 2.731864 7.272117 3.519398
y <- c(AirPassengers) # 月間航空旅客数
n <- length(y)        # 月数
n.tr <- 120           # 訓練月数
n.te <- n - n.tr      # テスト月数
t <- 1:n              # 月
ii.tr <- 1:120        # 訓練期間インデックス
ii.te <- 121:n        # テスト期間インデックス
matplot(y, type = 'o', pch = 1, col = 2)

fq <- 12
library(MASS)
bc <- boxcox(y ~ t, data = data.frame(y = y[ii.tr], t = t[ii.tr]))

lambda <- round(bc$x[which.max(bc$y)], 1)
lambda
## [1] 0
library(forecast)
y.bc <- BoxCox(y[ii.tr], lambda)

matplot(y.bc, type = 'o', pch = 1, col = 2, ylab = 'y')

d <- 1

dy <- diff(y.bc, diff = d)

matplot(dy, type = 'o', pch = 1, col = 2, ylab = 'y')

ys <- ts(10 * sin(2 * pi * t / 10) + rnorm(n))

dir.create('acf_lag', showWarnings = F)

for (k in 1:25)
{
  png(paste0('acf_lag/acf_lag', k, '.png'))

  ys.lag <- lag(ys, k = -k)
  ts2 <- cbind(ys, ys.lag)

  par(mfrow = c(3, 1), mar = c(2, 4, 1, 1))
  matplot(ts2, type = 'o', pch = 1, col = c(1, 4), 
          xlab = '', ylab = '', xlim = c(0, 120))
  abline(v = c(0, k), col = 2)
  arrows( 0, 0, k, 0, length = 0.1, col = 2)
  mtext(paste(k), side = 1, at = k, line = 1, col = 2)
  legend('topright', col = c(1, 4), bg = 'white', lty = 1,
        legend = c('原系列(周期10の正弦波+ノイズ)', paste0(k, '次ラグ系列')))
  grid()
   acf(ys, lag.max = k, xlim = c(0, 120), ylim = c(-1, 1), main = '')
  pacf(ys, lag.max = k, xlim = c(0, 120), ylim = c(-1, 1), main = '')

  dev.off()
}
#system('bash -c 'convert -delay 100 -loop 0 ./acf_lag/acf_lag{1..25}.png ./acf_lag/acf_lag.gif'')
a <- acf(dy, lag.max = 50) # MA(q)
grid()
abline(v = fq, col = 3, lty = 3)

q <- 12 
pa <- pacf(dy, lag.max = 50) # AR(p)【注意】acfと違いグラフが1次ラグから始まる。
grid()
abline(v = fq, col = 3, lty = 3)

fit.arima <- Arima(ts(y[ii.tr], frequency = fq), lambda = 'auto',
                   order    = c(p, d, q),
                   seasonal = c(1, 1, 0)) # SARIMA

# c.f.
#fit.arima <- auto.arima(ts(y[ii.tr], frequency = fq), lambda = 'auto')
fit.arima
## Series: ts(y[ii.tr], frequency = fq) 
## ARIMA(2,1,12)(1,1,0)[12] 
## Box Cox transformation: lambda= -0.3096643 
## 
## Coefficients:
##           ar1     ar2     ma1      ma2      ma3      ma4     ma5     ma6
##       -0.3511  0.0854  0.0202  -0.1614  -0.1299  -0.2076  0.0995  0.2321
## s.e.   0.1638  0.1617  0.1507   0.1355   0.0864   0.1003  0.1118  0.1214
##           ma7      ma8      ma9    ma10    ma11     ma12     sar1
##       -0.0880  -0.0222  -0.0594  0.0378  0.1787  -0.6759  -0.0860
## s.e.   0.1103   0.1050   0.0973  0.0954  0.1058   0.1168   0.1282
## 
## sigma^2 = 5.106e-05:  log likelihood = 378.47
## AIC=-724.94   AICc=-718.9   BIC=-682.18
checkresiduals(fit.arima) # 残差分析グラフ

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(2,1,12)(1,1,0)[12]
## Q* = 10.064, df = 9, p-value = 0.3454
## 
## Model df: 15.   Total lags used: 24
pred <- forecast(fit.arima, h = n.te, level = 95)
matplot(t, y, type = 'o', pch = 16, col = 2, main = pred$method)
grid()
abline(v = n.tr + 1, lty  = 3, col = 3)
matlines(t[ii.tr], fit.arima$fitted, type = 'o', pch = 16, lty = 2, col = 4)
matlines(t[ii.te], pred$mean,        type = 'o', pch =  1, lty = 2, col = 4)
matlines(t[ii.te], pred$lower, lty = 3, col = 'gray')
matlines(t[ii.te], pred$upper, lty = 3, col = 'gray')
legend('topleft', bg = 'white', lty = c(1, 2, 2, 3),
       col = c(2, 4, 4, 'gray'), pch = c(16, 16, 1, NA),
       legend = c('原系列', '1期先予測値', '予測値', '95%予測区間'))

get.accuracy <- function(yhat, y)
{
  data.frame(MBE  = mean(yhat - y),
             MAE  = mean(abs(yhat - y)),
             MAPE = mean(abs((yhat - y) / y)) * 100,
             RMSE = sqrt(mean((yhat - y)^2))
  )
}

get.accuracy(yhat = pred$mean, y = y[ii.te])
##         MBE      MAE     MAPE     RMSE
## 1 -9.728978 13.88215 3.229449 15.89875
n <- 24*7*2            # 時間数
t <- 1:n               # 時間
n.tr <- floor(n * 0.8) # 訓練期間数
n.te <- n - n.tr       # テスト期間数
ii.tr <- 1:n.tr        # 訓練期間インデックス
ii.te <- (n.tr+1):n    # テスト期間インデックス

set.seed(5)

y <- 100 + 0.1 * t + 0.02 * t^2 + 100 * sin(2 * pi * t / 24) + rnorm(n, sd = 5)

matplot(y, type = 'o', pch = 1, col = 2)

n <- 100                         # 全時間
x <- 1:n                         # 時刻
t <- 2 * x                       # トレンド(係数:2)
e <- rnorm(n, mean = 0, sd = 10) # 不規則変動 
y <- t + e                       # 合成変動 

matplot(x, y, type = 'o', pch = 16, col = 2)

n.tr <- n * 0.8   # 訓練時間(80%)
n.te <- n - n.tr  # テスト時間(20%)

ii.tr <- 1:n.tr 
ii.te <- (n.tr + 1):n

fit <- lm(y ~ x, data = data.frame(x = x[ii.tr], y = y[ii.tr]))
#summary(fit)
pred <- predict(fit, newdata = data.frame(x = x[ii.te]), interval = 'prediction')

myplot <- function(x, y, pred)
{
  matplot(x, y, type = 'o', pch = 16, col = 2, cex = 0.5)
  abline(v = n.tr+1, col = 3, lty = 2)
  matlines(x[ii.te], pred[, 'fit'], type = 'o', pch = 1, lty = 2, col = 4)
  matlines(x[ii.te], pred[, 'lwr'], lty = 3, col = 'lightgray')
  matlines(x[ii.te], pred[, 'upr'], lty = 3, col = 'lightgray')
  legend('topleft', bg = 0,
        lty = c(1, 2, 3), pch = c(16, 1, NA), col = c(2, 4, 'lightgray'),
        legend = c('原系列', '予測値', '95%予測区間'))
}

myplot(x, y, pred)

t <- 0.05 * x^2 - 2 * x          # 2次のトレンド
e <- rnorm(n, mean = 0, sd = 10) # 不規則変動 
y <- t + e                       # 合成変動 

fit <- lm(y ~ poly(x, 2, raw = T), data = data.frame(x = x[ii.tr], y = y[ii.tr]))
#summary(fit)
pred <- predict(fit, newdata = data.frame(x = x[ii.te]), interval = 'prediction')

myplot(x, y, pred)

T <- 10                          # 周期
c <- 30 * sin(2 * pi * x / T)    # 周期変動(振幅:30,周期:10)
t <- 2 * x                       # トレンド(係数:2)
e <- rnorm(n, mean = 0, sd = 10) # 不規則変動 
y <- t + c + e                   # 合成変動 

fit <- lm(y ~  poly(x, 2, raw = T), data = data.frame(x = x[ii.tr], y = y[ii.tr]))
#summary(fit)
pred <- predict(fit, newdata = data.frame(x = x[ii.te]), interval = 'prediction')

myplot(x, y, pred)

T <- 10                          # 周期
c <- 30 * sin(2 * pi * x / T)    # 周期変動(振幅:30,周期:10)
t <- 2 * x                       # トレンド(係数:2)
e <- rnorm(n, mean = 0, sd = 10) # 不規則変動 
y <- t + c + e                   # 合成変動 

fit <- lm(y ~  poly(x, 2, raw = T), data = data.frame(x = x[ii.tr], y = y[ii.tr]))
#summary(fit)
pred <- predict(fit, newdata = data.frame(x = x[ii.te]), interval = 'prediction')

myplot(x, y, pred)

dir.create('./ts_reg_periodic', showWarnings = F)

yhat <- rep(NA, n)

for (j in 1:T)
{
  # j <- 1
  ii <- seq(j, n.tr, T)
  ii.pred <- ii[length(ii)] + seq(T, T*2, T)

  fit <- lm(y ~  x, data = data.frame(x = x[ii], y = y[ii]))
  pred <- predict(fit, newdata = data.frame(x = x[ii.pred]), interval = 'prediction')
  yhat[ii.pred] <- pred[, 'fit']

  png(paste0('./ts_reg_periodic/ts_reg_periodic', j, '.png'))
  matplot(x, y, type = 'o', pch = 16, col = 2, cex = 0.5, ylim = c(0, 250))
  abline(v = n.tr+1, col = 3, lty = 2)
  matlines(x[ii], y[ii], type = 'o', pch = 1, col = 1, cex = 1.5)
  matlines(x, yhat, type = 'o', pch = 1, col = 4)
  matpoints(x[ii.pred], yhat[ii.pred], pch = 1, col = 1)
  dev.off()
  #Sys.sleep(2)
}

#system('bash -c "convert -delay 100 -loop 0 ./ts_reg_periodic/ts_reg_periodic{1..10}.png ./ts_reg_periodic/ts_reg_periodic.gif"')
d0 <- read.csv('https://stats.dip.jp/01_ds/data/load_amedas_y2017-2022_tokyo.csv')

head(d0)
##         date            datetime dow       name    event    md gr year month
## 1 2017-01-01 2017-01-01 00:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 2 2017-01-01 2017-01-01 01:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 3 2017-01-01 2017-01-01 02:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 4 2017-01-01 2017-01-01 03:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 5 2017-01-01 2017-01-01 04:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
## 6 2017-01-01 2017-01-01 05:00:00  日 祝日:元日 年末年始 01-01  6 2017     1
##   day su mo tu we th fr sa wd ho bw af sp ab    mw     time hr mi    hm rm   ws
## 1   1  1  0  0  0  0  0  0  0  1  0  0  1  0 27830 00:00:00  0  0 77.43  0 2.32
## 2   1  1  0  0  0  0  0  0  0  1  0  0  1  0 26340 01:00:00  1  0 71.00  0 2.52
## 3   1  1  0  0  0  0  0  0  0  1  0  0  1  0 25200 02:00:00  2  0 68.86  0 1.52
## 4   1  1  0  0  0  0  0  0  0  1  0  0  1  0 24380 03:00:00  3  0 71.43  0 1.40
## 5   1  1  0  0  0  0  0  0  0  1  0  0  1  0 23890 04:00:00  4  0 74.86  0 1.97
## 6   1  1  0  0  0  0  0  0  0  1  0  0  1  0 23940 05:00:00  5  0 73.71  0 2.25
##     tp tp3h tp5h tp3d tp7d
## 1 4.87 5.31 5.53 5.50 6.74
## 2 4.49 5.01 5.20 5.53 6.73
## 3 4.07 4.48 4.90 5.54 6.72
## 4 3.91 4.16 4.60 5.56 6.71
## 5 3.19 3.72 4.11 5.58 6.69
## 6 3.14 3.41 3.76 5.61 6.68
d0$px <- as.POSIXct(d0$datetime)
d0$gw <- d0$mw / 1000 # 測定値 (単位変換:MW -> GW)
d0$gwfit <- NA
d0$gwlwr <- NA
d0$gwupr <- NA

# Suffixとしてtr: training term, te: test term, al: all term を使用する。

# 訓練データの取得期間フラグ(ここでは予測日の前後1ヶ月間をとった)
is.67 <- '06-01' <= d0$md & d0$md <= '07-31'

# 訓練期間フラグ
is.tr <- '2017-06-01' <= d0$date & d0$date <= '2022-06-30'

# テスト期間フラグ
is.te <- '2022-07-01' <= d0$date & d0$date <= '2022-07-03'

# グラフ表示期間フラグ
is.plot <- '2022-06-28' <= d0$date & d0$date <= '2022-07-03'
d.plot <- d0[is.plot, ] # グラフ表用データ

matplot(d0$px, d0$gw, 
        main = '電力需要',
        xlab = '年', ylab = '電力需要[GW]',
        type = 'l', col = 2, ylim = c(20, 70))

for (hr in 0:23)
{
# 予測時間
#hr <- 10
is.hr <- d0$hr == hr

# 訓練データ
d.tr <- d0[is.hr & is.67 & is.tr, ]

# テストデータ(予測区間の正解データとして精度評価に利用)
d.te <- d0[is.hr & is.te, ]

# フィッティング
# (ここでは,トレンドがなく気温の2次多項式と曜日ダミーのモデルとした)
fit <- lm(gw ~ tp + I(tp^2) + dow, data = d.tr)
summary(fit)

# 予測(予測区間付き)
pred <- predict(fit, newdata = d.te, interval = 'prediction')

# 毎時の予測値を保存
d0$gwfit[d0$px %in% d.te$px] <- pred[, 'fit']
d0$gwlwr[d0$px %in% d.te$px] <- pred[, 'lwr']
d0$gwupr[d0$px %in% d.te$px] <- pred[, 'upr']

# 時間別グラフ
dir.create('./load', showWarnings = F)
png(paste0('./load/load_at', hr, '.png'))

matplot(d0$px[is.hr & is.plot], d0$gw[is.hr & is.plot], 
        main = paste0(hr, '時の電力需要'),
        xlab = format(d0$px[1], '%Y年'), ylab = '電力需要[GW]',
        type = 'n', pch = 16, col = 2, xaxt = 'n', 
        xlim = range(d0$px[is.plot]), ylim = c(20, 70))

px.ax <- seq(d0$px[1], d0$px[nrow(d0)], by = 60*60*24)
abline(v = px.ax, col = 'lightgray', lty = 2)
abline(v = as.POSIXct('2022-07-01'), col = 3, lty = 2) # 予測開始線
axis(side = 1, at = px.ax, labels = format(px.ax, '%-m/%-d(%a)')) 

matlines(d0$px[is.plot], d0$gw[is.plot], type = 'o', pch = 1, col = 'lightgray') 
matlines(d.te$px, pred[, 'fit'], type = 'o', pch = 1, lty = 2, col = 4)
matlines(d.te$px, pred[, 'lwr'], lty = 3, col = 'lightgray')
matlines(d.te$px, pred[, 'upr'], lty = 3, col = 'lightgray')
matlines(d0$px[is.hr & is.plot], d0$gw[is.hr & is.plot], type = 'o', pch = 16, col = 2) 

# 凡例
legend('topleft', bg = 0,
       lty = c(1, 2, 3), pch = c(16, 1, NA), col = c(2, 4, 'lightgray'),
       legend = c('原系列', '予測値', '95%予測区間'))
legend('topright', bg = 0,
       legend = sprintf('MAPE: %2.1f%%', 
                        mean(abs((pred[, 'fit'] - d.te$gw)/d.te$gw))*100))
dev.off()
}

#system('bash -c "convert -delay 100 -loop 0 ./load/load_at{0..23}.png ./load/load_at.gif"')
#cairo_pdf('load_0-23.pdf')

matplot(d0$px[is.plot], d0$gw[is.plot], 
        main = '電力需要',
        xlab = format(d0$px[1], '%Y年'), ylab = '電力需要[GW]',
        type = 'o', pch = 16, col = 2, xaxt = 'n',
        xlim = range(d0$px[is.plot]), ylim = c(20, 70))

px.ax <- seq(d0$px[1], d0$px[nrow(d0)], by = 60*60*24)
axis(side = 1, at = px.ax, labels = format(px.ax, '%-m/%-d(%a)')) 
abline(v = px.ax, col = 'lightgray', lty = 2)
abline(v = as.POSIXct('2022-07-01'), col = 3, lty = 2) # 予測開始線

matlines(d0$px[is.te], d0$gwlwr[is.te], lty = 3, col = 'lightgray')
matlines(d0$px[is.te], d0$gwupr[is.te], lty = 3, col = 'lightgray')
matlines(d0$px[is.te], d0$gwfit[is.te], type = 'o', pch = 1, lty = 2, col = 4)

# 凡例
legend('topleft', bg = 0,
       lty = c(1, 2, 3), pch = c(16, 1, NA), col = c(2, 4, 'lightgray'),
       legend = c('原系列', '予測値', '95%予測区間'))
legend('topright', bg = 0,
       legend = sprintf('MAPE: %2.1f%%', 
                        mean(abs((d0$gwfit[is.te] - d0$gw[is.te])/d0$gw[is.te]))*100))

#dev.off()
d0 <- read.csv('https://stats.dip.jp/01_ds/data/e-stat_expenditure.csv', skip = 11)

# タイムスタンプと支出金額のカラムを探しデータを抽出
j.time <- grep('時間軸.月次..コード', colnames(d0))
j.ice  <- grep('アイスクリーム',      colnames(d0))

d1 <- d0[, c(j.time, j.ice)]

# 時間コード(10桁)からPOSIX準拠時間を作成
yyyy <- substr(paste(d1[, 1]), 1, 4)
mm   <- substr(paste(d1[, 1]), 7, 8)
px <- as.POSIXct(paste(yyyy, mm, '01 12:00:00'), format = '%Y%m%d %H:%M:%S')

d <- data.frame(px, date = format(px, '%Y-%m-%d'), y = d1[, 2])

# 暦,気象とマージ
d <- merge(d, read.csv('https://stats.dip.jp/01_ds/data/calendar.csv'))
d <- merge(d, read.csv('https://stats.dip.jp/01_ds/data/amedas_tokyo.csv')) 
#View(d)

# グラフ
MAIN <- 'アイスクリーム月間世帯支出'
matplot(d$px, d$y, type = 'o', pch = 16, lty =1, col = 2,
        main = MAIN, xlab = '年', ylab = '円')

options(digits = 2)
year  <- 2011:2017
sales <- c(1, 3, 2, 7, 3, 8, 7)
n <- length(year)
d <- data.frame(year, sales)
library(kableExtra)
kable(d,caption = 'ロボット販売', col.names = c('会計年', '台数'))%>%
  kable_classic('striped', full_width = F)
ロボット販売
会計年 台数
2011 1
2012 3
2013 2
2014 7
2015 3
2016 8
2017 7
#cairo_pdf('robot_sales.pdf')
matplot(x = year, y = sales, type = 'o', pch = 1,
        main = 'ロボット販売',
        xlab = '会計年',
        ylab = '台数')
grid()

#dev.off()
d$ma3 <- NA # 値がNAの移動平均のカラム(ma3)を追加

for (i in 2:(n-1))
{
  d$ma3[i] <- (sales[i-1] + sales[i] + sales[i+1]) / 3
}
# filter関数を使用した(中心化)移動平均
ma3 <- stats::filter(sales, rep(1/3, 3))
ma3
## Time Series:
## Start = 1 
## End = 7 
## Frequency = 1 
## [1] NA  2  4  4  6  6 NA
# quantmodパッケージのrollmean関数を使用する場合
library(quantmod)
##  要求されたパッケージ xts をロード中です
##  要求されたパッケージ zoo をロード中です
## 
##  次のパッケージを付け加えます: 'zoo'
##  以下のオブジェクトは 'package:base' からマスクされています:
## 
##     as.Date, as.Date.numeric
##  要求されたパッケージ TTR をロード中です
ma3 <- rollmean(sales, 3, na.pad = T)
ma3
## [1] NA  2  4  4  6  6 NA
d$ma4 <- NA # 値がNAの移動平均のカラム(ma4)を追加

for (i in 3:(n-2)) 
{
  d$ma4[i] <-
    (0.5 * sales[i-2] + sales[i-1] + sales[i] + sales[i+1] + 0.5 * sales[i+2]) / 4
}
# filter関数を使用する場合
  ma4 <- stats::filter(sales, c(0.5/4, 1/4, 1/4, 1/4, 0.5/4))
  ma4
## Time Series:
## Start = 1 
## End = 7 
## Frequency = 1 
## [1]  NA  NA 3.5 4.4 5.6  NA  NA
# quantmodパッケージのrollmean関数を使用する場合
# 計算方法が異なり単純な4項の平均であるため中心が1つずれるので注意
  ma4 <- rollmean(sales, k = 4, na.pad = T)
  ma4
## [1]  NA 3.2 3.8 5.0 6.2  NA  NA
kable(d, caption = 'ロボット販売',
      col.names = c('会計年', '台数', '3項移動平均', '4項移動平均'))%>%
kable_classic('striped', full_width = F)
ロボット販売
会計年 台数 3項移動平均 4項移動平均
2011 1 NA NA
2012 3 2 NA
2013 2 4 3.5
2014 7 4 4.4
2015 3 6 5.6
2016 8 6 NA
2017 7 NA NA
#cairo_pdf('robot_sales_moving_average.pdf')

matplot(x = year, y = sales, type = 'o', pch = 1,
        main = 'ロボット販売', xlab = '会計年', ylab = '台数')
grid()

matlines(x = year, y = d$ma3, type = 'o', pch = 2, col = 2)
matlines(x = year, y = d$ma4, type = 'o', pch = 4, col = 4)

legend('topleft', col = c(1, 2, 4), pch = c(1, 2, 4), lty = 1,
       legend = c('台数', '3項移動平均', '4項移動平均'))

#dev.off()
matplot(x = x, y = y, type = 'l', col = 3, 
        main = '新規陽性者数の推移(日別)', xlab = '年', ylab = '陽性者数')
matlines(x = x, y = yhat, col = 1)
grid()
legend('topleft', col = c(3, 1), lty = 1, legend = c('原系列', '31日移動平均'))

library(quantmod)

z <- getSymbols('9984', src='yahooj',
                        from = '2022-01-01',
                        to   = '2022-12-31',
                        auto.assign = F)

# データの保存
write.zoo(z, file = 'softbank.csv', sep = ',', quote = F)

x <- as.POSIXct(index(z), format = '%Y-%m-%d')
y <- z[, 'YJ9984.Close']

# 1日分データをずらすことで当日の日付の株価が1日前のものになる。
ylag1 <- lag(y, k = 1)

# align = 'right'で右寄せ移動平均となる。
yhat5   <- rollmean(ylag1,  5, fill = NA, align = 'right')
yhat25  <- rollmean(ylag1, 25, fill = NA, align = 'right')
yhat25c <- rollmean(y, 25, fill = NA) # 参考(通常の移動平均:中心化移動平均)

matplot(x, y, type = 'l', col = 3,
main = 'ソフトバンク(9984)', xlab = '日', ylab = '円')
matlines(x, yhat5,   col = 2)
matlines(x, yhat25,  col = 4)
matlines(x, yhat25c, col = 1)
grid()
legend('topleft', col = c(3, 2, 4, 1), lty = 1,
       legend = c('株価',
                  '5日移動平均',
                  '25日移動平均',
                  '25日中心化移動平均(参考)'))

# (参考)パッケージのグラフ機能
chartSeries(z, TA = c(addBBands(), addMACD()), type='bar',
            subset='2022-06-01/2022-12-31')

# LOESS(平滑化窓幅: span)
x <- seq_along(y)
fit10 <- loess(y ~ x, data = data.frame(x, y), span = 0.1) # 10%
fit30 <- loess(y ~ x, data = data.frame(x, y), span = 0.3) # 30%

matplot(x, y = y, type = 'l', col = 3,
main = 'ソフトバンク(9984)', xlab = '日', ylab = '円')
matlines(x, fit10$fitted, col = 1, lwd = 2)
matlines(x, fit30$fitted, col = 2, lwd = 2)
grid()
legend('topleft', col = c(3, 1, 2), lty = 1,
       legend = c('株価',
                  'LOESS(平滑化窓幅10%)',
                  'LOESS(平滑化窓幅30%)'))