SQLServerCentral Article

How to Download Stocks on Schedule Using R

,

Introduction

In order to assess stocks before buying them or to evaluate performance of stocks that you might own, you have to be able to download data about the stocks regularly. This post demonstrates how to schedule stock downloads using R.

Downloading Stocks

To download stock history, we use the package, tidyquant, together with a couple of helper packagesm namely pacman and yaml. The pacman package provides a convenient way of ensuring that the required packages are installed, and if they have not been installed, install them from CRAN. This code will load the packages.

#next line is just to ensure that pacman is installed
if (!require("pacman")) install.packages("pacman")
#function call pacman::p_load() checks if the packages are installed;
#if not it attempts to install them from CRAN
pacman::p_load(yaml, tidyquant)

YAML is a markup language that is often used for making configuration files. In this case our configuration file, named config.yml, looks as follows

VEC_STOCKS: "- ATM.NZ\n- OCA.NZ\n- SPK.NZ\n- FBU.NZ\n- ZEL.NZ\n- EBO.NZ\n- FPH.NZ"

FROM_DATE:  2017-01-01

TO_DATE:        2020-05-15

FILE2SAVE:     "C:/NZStocks/stocks.csv"

APPEND:          FALSE

The first configuration parameter, VEC_STOCKS, contains a list of seven stock symbols listed on the NZ stock exchange, ATM.NZ, OCA.NZ, etc. The second parameter, FROM_DATE, contains the start date of the stocks’ history; the third - TO_DATE, is the end date of the stock history. The fourth parameter, FILE2SAVE, gives a full path and file name for saving the stocks history. Finally, the last parameter indicates whether to append the loaded history to the existing (previously loaded) file or to create a new file or to overwrite the existing file.

Loading the configuration parameters

All the configuration parameters are loaded into a list object with this code. As you can see, this object is named "settings".

settings <- read_yaml("config.yml")
(stocks <- read_yaml(text = settings$VEC_STOCKS))
## [1] "ATM.NZ" "OCA.NZ" "SPK.NZ" "FBU.NZ" "ZEL.NZ" "EBO.NZ" "FPH.NZ"

The second line in the above code chunk parses the settings$VEC_STOCKS list’s element into a character vector, called stocks.

Saving the stocks history

The first line in this code chunk downloads the following data for the stocks symbols listed in the stocks vector from Yahoo Finance for the period from settings $FROM_DATE to $TO_DATE.

  • open
  • high
  • low
  • close
  • volume
  • adjusted stock price

The second statement writes the results into a CSV file, whose name is provided by the settings parameter, $FILE2SAVE.

nzstocks <- tq_get(
   stocks,
   get = "stock.prices",
   from = as.Date(settings$FROM_DATE),
   to = as.Date(settings$TO_DATE)
)
write.table(
   nzstocks,
   file = settings$FILE2SAVE,
   sep = ",",
   row.names = FALSE,
   append = settings$APPEND
)

The statement below prints the top six rows from the downloaded stocks’ historical records.

knitr::kable(head(nzstocks), digits = 3,caption = "Top 6 Rows of Seven NZ Stocks")

Here are the the result from running this code:

Top 6 Rows of Seven NZ Stocks

symboldateopenhighlowclosevolumeadjusted
ATM.NZ2017-01-042.152.152.092.126218552.12
ATM.NZ2017-01-052.122.122.082.099191742.09
ATM.NZ2017-01-062.102.102.072.087845692.08
ATM.NZ2017-01-092.092.122.062.127305372.12
ATM.NZ2017-01-102.132.142.092.134107292.13
ATM.NZ2017-01-112.142.282.122.2844908722.28

Let’s save the tested code in an R script file, named get_nz_stocks.R, and schedule its execution with the taskscheduleR package. Here is the minimum required R script that we about to schedule.

suppressPackageStartupMessages({
   suppressMessages({
      library(yaml)
      library(tidyquant)
   })
})
settings <- read_yaml("C:/NZStocks/config.yml")
stocks <- read_yaml(text = settings$VEC_STOCKS)
nzstocks <- tq_get(
   stocks,
   get = "stock.prices",
   from = as.Date(settings$FROM_DATE),
   to = as.Date(settings$TO_DATE)
)
write.table(
   nzstocks,
   file = settings$FILE2SAVE,
   sep = ",",
   row.names = FALSE,
   append = settings$APPEND
)

Scheduling Stocks Download

If we want to download those stocks every day at 6:00 pm, the following statement will schedule the execution of the get_nz_stocks.R script. You can see that this scheduling was a success in the last line of this code block.

library(taskscheduleR)
   taskscheduler_create(
   taskname = "download_nz_stocks",
   rscript = "C:/NZStocks/get_nz_stocks.R",
   schedule = "DAILY",
   starttime = "18:00"
)
#[1] "SUCCESS: The scheduled task \"download_nz_stocks\" has successfully been created."

To test the scheduling of the script immediately, change the value passed as the last argument of the taskscheduleR::taskscheduler_create() function to format(Sys.time() + 60, ":") expression.

After the scheduled script is ran you can open the Windows Task Scheduler App and see a new entry in the list of the scheduled tasks as shown below.

Here is what you see inside the C:/NZStocks directory after the script’s execution.

It might contain a log file if your script is executed with an error.

Here is a candlestick charts displaying the high, low, open, and closing prices of the Fisher and Paykel security for the 2nd quarter of 2020.

This chart is made using OKViz Candlestick Power BI Custom visual. Note that the time filter that shortens the time series down to the second quarter of 2020 is not displayed on the above picture.

 

Rate

4.5 (2)

You rated this post out of 5. Change rating

Share

Share

Rate

4.5 (2)

You rated this post out of 5. Change rating