December 23, 2024

How to get stock prices in R

Stock prices from Yahoo finance

Analyzing daily data on various assets is one of the most significant responsibilities in financial markets. We need past data for the assets to complete this analysis. There are several data suppliers, some of them are free while the majority are not. In this chapter, we will use data from Yahoo Finance.

# CRAN (stable)
install.packages('tidyverse')
install.packages('tidyquant')

# load libraries
library(tidyverse)
library(tidyquant)

# input tickers and date
stock_ticker <- c("0823.HK", "0778.HK")
start_from <- "2019-01-01"
end_to <- "2022-01-01"

###
# download stock data
stk_data <- tq_get(x=stock_ticker, get="stock.prices", from=start_from, to=end_to)

# split into list by symbol
stk_list <- split(stk_data, f=as.factor(stk_data$symbol))

# output csv file
for(i in names(stk_list)) {
  write.csv(stk_list[[i]], paste0(i,".csv"),row.names=F)
  print(paste0(i, ' csv is generated.'))
}
###

# put them into a function
stockdata2csv <- function(ticker,start_date="2019-01-01",end_date=Sys.Date()) {
  stk_list <- tq_get(x=ticker, get="stock.prices", from=start_date, to=end_date) %>% 
    split(f=as.factor(.$symbol))
  for(i in names(stk_list)) {
    write.csv(stk_list[[i]], paste0(i,".csv"),row.names=F)
    print(paste0(i, ' csv is generated.'))
  }
}

# e.g. HK REITs tickers
# https://reitsinvestors.com/hong-kong-reits/
hk_reits <- c("0823.HK","0778.HK","1503.HK","0405.HK","2778.HK","0808.HK",
             "0435.HK","1881.HK","1426.HK","2191.HK","87001.HK")

stockdata2csv(hk_reits)

# e.g. NZ reits tickers
# https://reitsinvestors.com/new-zealand-reits/
nz_reits <- c("KPG.NZ","GMT.NZ","PCT.NZ","ARG.NZ","PFI.NZ","VHP.NZ","SPG.NZ","IPL.NZ")

stockdata2csv(nz_reits, from="2015-01-01")


Now you have CSV files with stock prices to do further analysis !