How might you apply the code to a different stock?
-
Simple but sloppy answer: replace
IBM <- tail(get.hist.quote("IBM"),1000)
with
IBM <- tail(get.hist.quote("AAPL"),1000)
The term in the "get.hist.quotes" function specifying the stock is the only IBM-specific code in the snippet, even though for explanatory purposes the objects generated by the code were named after IBM. It'll be confusing to keep calling things IBM if they're not, but you'll get the same data regardless of what you call the output variables.
-
A better approach would be to make a function. Here's a suggestion. One shortfall of this that others might be able to fix is that your code produces two outputs (IBM and IBM_max), while as far as I know, R functions return a single object. My kludge here is to return a list combining those two objects, and you can request either the first or second object in that list.
# Generalized function for getting stock peaks
get_stock_peaks <- function(stock_name,
history_length = 1000,
max_window = 100) {
library(tseries)
library(tidyverse)
data <- tail(get.hist.quote(stock_name), history_length)
data <- data.frame(data)
which_max_in_window = function(x, size){
out = vector(mode = "numeric", length = length(x))
win = seq(1, size)
out[win] = which.max(x[win])
for( i in seq(size + 1, length(x)) ){
first = i - size + 1
last = i
win = seq(first, last)
out[i] = which.max(x[win]) + first - 1
}
return(out)
}
data <-
data %>%
mutate(Serial = seq(1, nrow(.)),
Max_Val_Serial_No =
which_max_in_window(x = Close, size = max_window))
data_max <- tibble(x = data %>%
select(Max_Val_Serial_No) %>%
distinct %>%
pull,
y = data %>%
select(Close) %>%
slice(x) %>%
pull)
stuff_to_return <- list(data, data_max)
return(stuff_to_return)
}
# These lines aren't great, since they run the same code twice
stock_data <- get_stock_peaks("IBM")[[1]]
stock_data_max <- get_stock_peaks("IBM")[[2]]
# Alternately, we could save both outputs into one object
output <- get_stock_peaks("IBM")
# and then separately extract which part of that first object we want to use
stock_data <- output ("IBM")[[1]]
stock_data_max <- output ("IBM")[[2]]