nikkei225

Author

Takafumi Kubota

Published

July 7, 2024

Abstract

This R script conducts time series analysis and visualization of selected Nikkei 225 stocks. Utilizing quantmod for data retrieval and dplyr for data manipulation, it fetches one-year historical stock data from Yahoo Finance. The script calculates the most recent and prior year weekdays to ensure accurate trading data. It dynamically generates variables for each stock’s data and visualizes them using chartSeries with a clean theme. This streamlined process aids financial analysts and researchers in efficiently analyzing and visualizing stock performance.

Keywords

Time Series, Nikkei 225, Visualization

1 Time Series Analysis and Visualization of Nikkei 225 Stocks Using R

This script performs a detailed time series analysis and visualization of selected Nikkei 225 stocks using R programming language. The analysis begins by installing and loading the necessary packages, quantmod and dplyr. The quantmod package is essential for obtaining and analyzing financial data, while dplyr is used for efficient data manipulation.

The script then creates a list of Nikkei 225 stocks, including their codes and names, and generates a shortened version of the stock codes. A custom operator %ni% is defined to filter out specific stock codes that are not required for the analysis.

Current date and the most recent weekday are calculated using Sys.Date and weekdays functions. If the current date is a weekend, the script adjusts to the most recent preceding weekday. Similarly, the script calculates the date one year prior and adjusts for weekends to ensure the start date is also a weekday. This ensures that the data covers exactly one year of trading days, avoiding non-trading days which could skew the analysis.

A loop iterates over each stock in the filtered list, using the getSymbols function from the quantmod package to download historical stock data from Yahoo Finance. The downloaded data spans from the calculated start date to the most recent weekday. The assign function dynamically creates variables to store the downloaded data.

Each stock’s data is then visualized using the chartSeries function. This function generates time series charts with a specified theme, in this case, a white background, and omits additional technical analysis overlays. The charts are titled with the respective stock names for clarity.

This script provides a streamlined approach to retrieving, filtering, and visualizing financial data, making it useful for financial analysts, researchers, and investors interested in the historical performance of Nikkei 225 stocks. By automating the process of data retrieval and visualization, it enhances productivity and accuracy, reducing the manual effort required for similar tasks.

Moreover, the script’s structure allows for easy modification and expansion to include additional stocks or different indices. The use of R and its powerful libraries exemplifies the benefits of leveraging programming for financial data analysis, offering reproducibility, flexibility, and the ability to handle large datasets efficiently.

Code
# 必要なパッケージをインストール
#install.packages("quantmod")
#install.packages("dplyr")

# パッケージを読み込む
library(quantmod)
library(dplyr)

# 日経225の銘柄リスト
nikkei_225 <- tibble::tibble(
  Code = c("1332.T", "1333.T", "1605.T", "1721.T", "1801.T", "1802.T", "1803.T", "1808.T",
           "1925.T", "1928.T", "1963.T", "2002.T", "2269.T", "2282.T", "2413.T", "2432.T",
           "2768.T", "2801.T", "2802.T", "2871.T", "2914.T", "3086.T", "3099.T", "3101.T",
           "3103.T", "3105.T", "3116.T", "3141.T", "3401.T", "3402.T", "3405.T", "3407.T",
           "3436.T", "3606.T", "3632.T", "3659.T", "3738.T", "3861.T", "3863.T", "3865.T",
           "4183.T", "4188.T", "4208.T", "4272.T", "4324.T", "4502.T", "4503.T", "4506.T",
           "4507.T", "4519.T", "4523.T", "4568.T", "4689.T", "4704.T", "4751.T", "4755.T",
           "4901.T", "4902.T", "4911.T", "5019.T", "5020.T", "5101.T", "5108.T", "5201.T",
           "5202.T", "5232.T", "5233.T", "5301.T", "5332.T", "5333.T", "5401.T", "5406.T",
           "5411.T", "5703.T", "5706.T", "5707.T", "5711.T", "5713.T", "5714.T", "5801.T",
           "5802.T", "5803.T", "5901.T", "5902.T", "6103.T", "6113.T", "6301.T", "6302.T",
           "6305.T", "6326.T", "6361.T", "6366.T", "6367.T", "6417.T", "6471.T", "6472.T",
           "6473.T", "6479.T", "6501.T", "6503.T", "6504.T", "6506.T", "6645.T", "6674.T",
           "6701.T", "6702.T", "6703.T", "6724.T", "6752.T", "6758.T", "6762.T", "6770.T",
           "6841.T", "6856.T", "6902.T", "6952.T", "6954.T", "6971.T", "6976.T", "6981.T",
           "6988.T", "7003.T", "7004.T", "7011.T", "7012.T", "7013.T", "7186.T", "7201.T",
           "7202.T", "7203.T", "7261.T", "7267.T", "7269.T", "7270.T", "7272.T", "7731.T",
           "7733.T", "7735.T", "7741.T", "7751.T", "7752.T", "7762.T", "7832.T", "7911.T",
           "7912.T", "7936.T", "7951.T", "8001.T", "8002.T", "8015.T", "8031.T", "8035.T",
           "8053.T", "8058.T", "8233.T", "8252.T", "8253.T", "8267.T", "8303.T", "8304.T",
           "8316.T", "8331.T", "8354.T", "8355.T", "8369.T", "8377.T", "8410.T", "8411.T",
           "8601.T", "8604.T", "8628.T", "8630.T", "8697.T", "8725.T", "8750.T", "8766.T",
           "8795.T", "8801.T", "8802.T", "8804.T", "8830.T", "9001.T", "9005.T", "9007.T",
           "9008.T", "9009.T", "9020.T", "9021.T", "9022.T", "9062.T", "9064.T"),
  Name = c("Nippon Suisan Kaisha, Ltd.", "Maruha Nichiro Corporation", "INPEX Corporation", 
           "COMSYS Holdings Corporation", "Taisei Corporation", "Obayashi Corporation", 
           "Shimizu Corporation", "HASEKO Corporation", "DAIWA HOUSE INDUSTRY CO., LTD.", 
           "SEKISUI HOUSE, LTD.", "JGC Corporation", "Nisshin Seifun Group Inc.", 
           "Meiji Holdings Co., Ltd.", "NH Foods Ltd.", "M3, Inc.", "DENTSU GROUP INC.", 
           "Sojitz Corporation", "Kikkoman Corporation", "Ajinomoto Co., Inc.", 
           "Nissin Foods Holdings Co., Ltd.", "JAPAN TOBACCO INC.", 
           "J. FRONT RETAILING Co., Ltd.", "Isetan Mitsukoshi Holdings Ltd.", 
           "TOYOBO Co., Ltd.", "Unitika Ltd.", "Nisshinbo Holdings Inc.", "TOYOBO Co., Ltd.", 
           "Welcia Holdings Co., Ltd.", "TEIJIN LIMITED", "TORAY INDUSTRIES, INC.", 
           "KURARAY CO., LTD.", "ASAHI KASEI CORPORATION", "SUMCO Corporation", 
           "KURARAY CO., LTD.", "GMO Internet, Inc.", "Nexon Co., Ltd.", "T-Gaia Corporation", 
           "Oji Holdings Corporation", "Nippon Paper Industries Co., Ltd.", 
           "JAPAN PULP AND PAPER COMPANY LIMITED", "MITSUI CHEMICALS, INC.", 
           "Mitsubishi Chemical Holdings Corporation", "UBE INDUSTRIES, LTD.", 
           "Kureha Corporation", "DENTSU GROUP INC.", "Takeda Pharmaceutical Company Limited", 
           "Astellas Pharma Inc.", "Sumitomo Dainippon Pharma Co., Ltd.", 
           "SHIONOGI & CO., LTD.", "Chugai Pharmaceutical Co., Ltd.", "Eisai Co., Ltd.", 
           "DAIICHI SANKYO COMPANY, LIMITED", "Z Holdings Corporation", 
           "Trend Micro Incorporated", "CyberAgent, Inc.", "Rakuten, Inc.", 
           "FUJIFILM Holdings Corporation", "KONICA MINOLTA, INC.", "SHISEIDO Company, Limited", 
           "Idemitsu Kosan Co., Ltd.", "ENEOS Holdings, Inc.", "The Yokohama Rubber Co., Ltd.", 
           "Bridgestone Corporation", "AGC Inc.", "Nippon Sheet Glass Co., Ltd.", 
           "Sumitomo Osaka Cement Co., Ltd.", "Taiheiyo Cement Corporation", 
           "Tokai Carbon Co., Ltd.", "TOTO LTD.", "NGK Insulators, Ltd.", 
           "NIPPON STEEL CORPORATION", "Kobe Steel, Ltd.", "JFE Holdings, Inc.", 
           "Sumitomo Metal Mining Co., Ltd.", "Mitsubishi Materials Corporation", 
           "Toho Zinc Co., Ltd.", "Mitsubishi Chemical Holdings Corporation", 
           "Sumitomo Metal Mining Co., Ltd.", "DOWA HOLDINGS CO., LTD.", 
           "Furukawa Electric Co., Ltd.", "Sumitomo Electric Industries, Ltd.", 
           "Fujikura Ltd.", "Toyo Seikan Group Holdings, Ltd.", "Kobe Steel, Ltd.", 
           "Okuma Corporation", "AMADA CO., LTD.", "Komatsu Ltd.", "Sumitomo Heavy Industries, Ltd.", 
           "Hitachi Construction Machinery Co., Ltd.", "Kubota Corporation", "EBARA CORPORATION", 
           "CHIYODA CORPORATION", "Daikin Industries, Ltd.", "SANKYO CO., LTD.", "NSK Ltd.", 
           "NTN Corporation", "JTEKT Corporation", "MINEBEA MITSUMI Inc.", "Hitachi, Ltd.", 
           "Mitsubishi Electric Corporation", "FUJI ELECTRIC CO., LTD.", "Yaskawa Electric Corporation", 
           "OMRON Corporation", "GS Yuasa Corporation", "NEC Corporation", "FUJITSU LIMITED", 
           "OKI Electric Industry Co., Ltd.", "Seiko Epson Corporation", "Panasonic Corporation", 
           "Sony Group Corporation", "TDK Corporation", "ALPS ALPINE CO., LTD.", 
           "Yokogawa Electric Corporation", "HORIBA, Ltd.", "DENSO CORPORATION", 
           "CASIO COMPUTER CO., LTD.", "FANUC CORPORATION", "Kyocera Corporation", 
           "Taiyo Yuden Co., Ltd.", "Murata Manufacturing Co., Ltd.", "Nitto Denko Corporation", 
           "Mitsubishi Heavy Industries, Ltd.", "Hitachi Zosen Corporation", 
           "Mitsubishi Heavy Industries, Ltd.", "Kawasaki Heavy Industries, Ltd.", 
           "IHI Corporation", "Concordia Financial Group, Ltd.", "Nissan Motor Co., Ltd.", 
           "ISUZU MOTORS LIMITED", "TOYOTA MOTOR CORPORATION", "Mazda Motor Corporation", 
           "Honda Motor Co., Ltd.", "SUZUKI MOTOR CORPORATION", "Subaru Corporation", 
           "Yamaha Motor Co., Ltd.", "NIKON CORPORATION", "Olympus Corporation", 
           "SCREEN Holdings Co., Ltd.", "HOYA CORPORATION", "Canon Inc.", "RICOH COMPANY, LTD.", 
           "Citizen Watch Co., Ltd.", "Bandai Namco Holdings Inc.", "TOPPAN PRINTING CO., LTD.", 
           "Dai Nippon Printing Co., Ltd.", "ASICS Corporation", "YAMAHA CORPORATION", 
           "ITOCHU Corporation", "Marubeni Corporation", "Toyota Tsusho Corporation", 
           "MITSUI & CO., LTD.", "Tokyo Electron Limited", "Sumitomo Corporation", 
           "Mitsubishi Corporation", "Takashimaya Company, Limited", "Marui Group Co., Ltd.", 
           "Credit Saison Co., Ltd.", "AEON Co., Ltd.", "Shinsei Bank, Limited", 
           "Aozora Bank, Ltd.", "Sumitomo Mitsui Financial Group, Inc.", "The Chiba Bank, Ltd.", 
           "Fukuoka Financial Group, Inc.", "THE SHIZUOKA BANK, LTD.", "The Bank of Kyoto, Ltd.", 
           "Hokuhoku Financial Group, Inc.", "Seven Bank, Ltd.", "Mizuho Financial Group, Inc.", 
           "Daiwa Securities Group Inc.", "Nomura Holdings, Inc.", "Mizuho Securities Co., Ltd.", 
           "SOMPO Holdings, Inc.", "Japan Exchange Group, Inc.", "MS&AD Insurance Group Holdings, Inc.", 
           "Dai-ichi Life Holdings, Inc.", "Tokio Marine Holdings, Inc.", "T&D Holdings, Inc.", 
           "Mitsui Fudosan Co., Ltd.", "Mitsubishi Estate Co., Ltd.", "Tokyo Tatemono Co., Ltd.", 
           "Sumitomo Realty & Development Co., Ltd.", "Tobu Railway Co., Ltd.", 
           "Tokyu Corporation", "Odakyu Electric Railway Co., Ltd.", "Keio Corporation", 
           "Keisei Electric Railway Co., Ltd.", "East Japan Railway Company", 
           "West Japan Railway Company", "Central Japan Railway Company", "NIPPON EXPRESS CO., LTD.", 
           "SG Holdings Co., Ltd.")
)

# 短縮レター+コード(4桁)を作成
nikkei_225 <- nikkei_225 %>%
  mutate(ShortCode = paste0("N", substr(Code, 1, 4)))

# %ni% 演算子を定義
`%ni%` <- Negate(`%in%`)
nikkei_225 <- nikkei_225[nikkei_225$Code %ni% c("3606.T","8303.T","8355.T","8369.T","9062.T"),]

# 今日の日付を取得
today <- Sys.Date()

# 今日の直前の平日を取得
if (weekdays(today) == "Saturday") {
  last_weekday <- today - 1
} else if (weekdays(today) == "Sunday") {
  last_weekday <- today - 2
} else {
  last_weekday <- today
}

# 1年前の日付を計算し、直前の平日を取得
one_year_ago <- last_weekday - 365
if (weekdays(one_year_ago) == "Saturday") {
  one_year_ago <- one_year_ago - 1
} else if (weekdays(one_year_ago) == "Sunday") {
  one_year_ago <- one_year_ago - 2
}

# データをダウンロードしてプロット
for (i in 1:nrow(nikkei_225)) {
  code <- nikkei_225$Code[i]
  name <- nikkei_225$Name[i]
  varname <- nikkei_225$ShortCode[i]
  
  # データをダウンロード
  assign(varname, getSymbols(code, src = "yahoo", from = one_year_ago, to = last_weekday, auto.assign = FALSE))
  
  # グラフをプロット
  chartSeries(get(varname), theme = chartTheme("white"), TA = NULL, name = name)
}

1.0.1 パッケージのインストールと読み込み

quantmoddplyrのパッケージをインストールし、使用するためにライブラリとして読み込む。quantmodは金融データの取得と解析、dplyrはデータフレームの操作に便利な関数を提供する。

1.0.2 日経225の銘柄リストの作成

日経225に含まれる銘柄リストを作成する。データフレームtibble::tibbleを使用して、銘柄コードCodeと銘柄名Nameを格納する。

1.0.3 短縮レター+コード(4桁)の作成

データフレームnikkei_225に新しい列ShortCodeを追加する。これは、mutate関数を使用して、各銘柄コードの最初の4桁を取得し、前に”N”を付けたものである。

  • mutate:既存のデータフレームに新しい列を追加する。

  • paste0:文字列を結合する。

  • substr:文字列の一部を抽出する。

1.0.4 %ni% 演算子の定義とデータフィルタリング

カスタム演算子%ni%を定義し、特定の銘柄コードを除外する。Negate関数を使用して%in%演算子の否定を作成する。

  • %in%:ベクトルに特定の要素が含まれているかどうかを確認する。

  • Negate:関数を反転する。

1.0.5 今日の日付と直前の平日の取得

Sys.Date関数を使用して現在の日付を取得する。次に、その日付が週末である場合、直前の平日の日付を計算する。

  • Sys.Date:現在の日付を取得する。

  • weekdays:日付から曜日を取得する。

  • if文:条件分岐を行う。

1.0.6 1年前の日付の計算と直前の平日の取得

現在の日付から1年前の日付を計算し、その日付が週末である場合、直前の平日の日付を計算する。

  • 日付の引き算:1年は365日とし、日付から365日を引く。

  • 週末チェックと平日調整:if文を使用して土曜日や日曜日の場合に1日または2日を引く。

1.0.7 データのダウンロードとプロット

日経225の各銘柄について、過去1年間のデータをYahoo Financeからダウンロードし、グラフをプロットする。

  • forループ:各銘柄について繰り返し処理を行う。

    • nrow:データフレームの行数を取得する。
  • getSymbols関数:Yahoo Financeからデータを取得する。

    • code:ダウンロードする銘柄のコード。

    • src:データソース(“yahoo”)。

    • from:データの開始日。

    • to:データの終了日。

    • auto.assign:FALSEに設定すると、結果を返し、環境に変数として自動的に割り当てない。

  • assign関数:変数名を指定して値を環境に割り当てる。

    • varname:割り当てる変数の名前。

    • getSymbolsの結果を変数に割り当てる。

  • chartSeries関数:取得したデータのチャートをプロットする。

    • get(varname):変数名を使用してデータを取得する。

    • theme:チャートのテーマ(“white”)。

    • TA:テクニカル指標(ここではNULL)。

    • name:チャートのタイトルとして使用する銘柄名。

以上のコードは、指定した日経225銘柄の過去1年間のデータを取得し、各銘柄についてグラフを生成する。