Skip to content

Instantly share code, notes, and snippets.

@ZeccaLehn
Last active July 10, 2023 10:10
Show Gist options
  • Save ZeccaLehn/c49ccc07af115e3dec878ed8a68b21d0 to your computer and use it in GitHub Desktop.
Save ZeccaLehn/c49ccc07af115e3dec878ed8a68b21d0 to your computer and use it in GitHub Desktop.
Py: Adjust Splits and Dividends from Real Prices using Quandl Finance Data
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@ZeccaLehn
Copy link
Author

ZeccaLehn commented Dec 30, 2017

Reproduced in R

library(data.table)

calculateAdjustedPrices <- function(df){  
  
  # Adapted from:
  # https://joshschertz.com/2016/08/27/Vectorizing-Adjusted-Close-with-Python/
  
  df <- df[rev(order(index)),]
  
  adjColumn = 'Adj_Close_Check'
  
  priceCol = df$Close
  splitCol = df$Split
  dividendCol = df$Dividend
  adjPriceCol = NULL 
  adjPriceCol[1] = priceCol[1]
  
  for(i in 2:length(priceCol)){
    adjPriceCol[i] = 
      round((adjPriceCol[i - 1] + adjPriceCol[i - 1] *
               (((priceCol[i] * splitCol[i - 1]) -
                   priceCol[i - 1] -
                   dividendCol[i - 1]) / priceCol[i - 1])), 4)}
  
  df$adj_Test = adjPriceCol
  
  df <- df[order(index),]
  
  return(df)
  
}

ticker <- "AAPL"
securityX <- Quandl(paste0("EOD/",ticker), api_key="xxxxxxx", type = "xts")
securityX <- as.data.table(securityX)
securityX <- securityX[index >= "1980-12-12" & index <= "2016-08-26",]

(securityX <- calculateAdjustedPrices(securityX))
# getSplits("AAPL") # Doesn't include Reverse Splits!
plot(securityX$index, securityX$Close/securityX$adj_Test, type = "l")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment