azmath
azmath

Reputation: 97

How to find a stock price on a particular date?

Using quantmod or tidy quant, it is possible to download stock price from a range of period. However, I am looking to add a stock price column to an existing data frame which has ticker and date in it. In google spreadsheet, there is a simple formula to find the stock price on a particular date.

=GOOGLEFINANCE("AMZN","price",date(2017,2,7))

However, in R, there seems to be no way to do it.

What I have is a data frame:

Date.    Ticker.  Revenue.  Profit...

x.          y        z        i      
...         ...      ...      ...

I need to add an additional column with stock price of y as on x, to get

Date.    Ticker.  Revenue.  Profit...   Price

x.          y        z        I          p (of y on x)
...         ...      ...      ...        ...

Is there anyway to do this?

Upvotes: 0

Views: 1340

Answers (1)

phiver
phiver

Reputation: 23598

You could use tiingo together with quantmod"(or tidyquant). I would expect yahoo to work as well, but when using yahoo I keep running into errors when using 1 day retrievals (shoddy work on the yahoo side of things).

library(quantmod)
my_api <- "my_api" # <- here goes your tiingo api
amzn <- getSymbols("AMZN", auto.assign = FALSE, 
                   src = "tiingo",
                   api = my_api,
                   from = "2017-02-07",
                   to = "2017-02-07")

amzn
           AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
2017-02-07    809.31    816.16    807.5      812.5     3466091

Combining everything in a data.frame:

library(quantmod)
library(dplyr)
library(purrr)

my_api <- "my_api"  # <- here goes your tiingo api


# helper function to just get the close price
get_price <- function(ticker, date) {
  data <- getSymbols(ticker, 
                    auto.assign = FALSE, 
                    src = "tiingo",
                    api = my_api,
                    from = date,
                    to = date)
  
  out <- as.numeric(quantmod::Cl(data))
  out
}


my_data %>% 
  mutate(close = map2(ticker, date, get_price))

        date ticker revenue profit close
1 2017-02-07   AMZN   10000     10 812.5
2 2018-03-05   MSFT   20000     20 93.64

data:

my_data <- data.frame(date = c("2017-02-07", "2018-03-05"),
                      ticker = c("AMZN", "MSFT"),
                      revenue = c(10000, 20000),
                      profit = c(10, 20))

Upvotes: 2

Related Questions