Search code examples
rpurrrquantmod

I'm struggle with ymd function


Objective: I want to pull Price(OHLC) of many stocks from Yahoo finance and then create indicator for creating stock scanning. I use this link for reference. [Link][1]

By: 1. get universe 2. create function for inserting price and indicator 3. Map function

Problem: 1) Date is shown incorrectly.

##### Automate System S1

# 0) Download library
library(rvest)      # web scraping
library(quantmod)   # get stock prices; useful stock analysis functions
library(tidyverse)  # ggplot2, purrr, dplyr, tidyr, readr, tibble
library(stringr)    # working with strings
library(modelr)     # geom_ref_line() function
library(lubridate)  # working with dates 
library(plotly)     # interactive plots

# 1) Get Universe

stocklist <- tibble(
  symbol = c("FLWS","TWOU"),
  company = c("A","B")
)

# 2) Create Function for Price, indicator etc. 

# Wrapper for quantmod::getSymbols()
get_stock_prices <- function(ticker, return_format = "tibble", ...) {
  # Get stock prices
  stock_prices_xts <- getSymbols(Symbols = ticker, auto.assign = FALSE, ...)
  # Rename
  names(stock_prices_xts) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted")
  # Return in xts format if tibble is not specified
  if (return_format == "tibble") {
    stock_prices <- stock_prices_xts %>%
      as_tibble() %>%
      rownames_to_column(var = "Date") %>%
      mutate(Date = ymd(Date,truncated = 2)) # Original verson doesn't has "truncated = 2" 
  } else {
    stock_prices <- stock_prices_xts
  }
  
  stock_prices
}

# Create SMA function
n = 10
sma <- function(x, return_format = "tibble", n = n) {
  x = na.omit(x)  # Original verson doesn't has "x = na.omit(x)" ; I put it because if not it won't work at all.
  # Convert tibble to xts
  if (!is.xts(x)) {
    x <- xts(x[,-1], order.by = x$Date)
  }
  # Get log returns
  sma_xts <- SMA(x = x$Adjusted, n = n)
  # Rename
  names(sma_xts) <- "SMA"
  # Return in xts format if tibble is not specified
  if (return_format == "tibble") {
    sma <- sma_xts %>%
      as_tibble() %>%
      rownames_to_column(var = "Date") %>%
      mutate(Date = ymd(Date,truncated = 2)) # Original verson doesn't has "truncated = 2" 
  } else {
    sma <- sma_xts
  }
  sma
}

# 3) MAP Function

ptm <- proc.time()
from = "2022-01-01"
to =  today()

stocklist <- stocklist %>% 
  mutate(
    stock.prices = map(symbol,
                       function(.x) tryCatch({get_stock_prices(.x,
                                                               return_format = "tibble",
                                                               from = from,
                                                               to = to)},
                                             error = function(e){NA})),
    
    SMA  = map(stock.prices, 
               function(.x) sma(.x, return_format = "tibble", n =10)),
    
    len = map_int(stock.prices, length)
  )

proc.time() - ptm

THANK YOU!!! [1]: https://www.r-bloggers.com/2016/10/quantitative-stock-analysis-tutorial-screening-the-returns-for-every-sampp500-stock-in-less-than-5-minutes/


Solution

  • Your problem lies in this part of your code:

     stock_prices <- stock_prices_xts %>%
      as_tibble() %>%
      tibble::rownames_to_column(var = "Date") %>%
      mutate(Date = lubridate::ymd(Date,truncated = 2))
    

    When using as_tibble on an xts object, you lose the date column.

    You should use:

    stock_prices <-  stock_prices_xts %>%
      fortify.zoo(., names = "Date") # names renames the Index of an xts/zoo object
    

    Or better yet, 4 lines of code into 1:

    stock_prices <- fortify.zoo(stock_prices_xts, names = "Date")