Skip to content

Instantly share code, notes, and snippets.

@boersmamarcel
Created May 5, 2012 17:55
Show Gist options
  • Save boersmamarcel/2604367 to your computer and use it in GitHub Desktop.
Save boersmamarcel/2604367 to your computer and use it in GitHub Desktop.
R: Stock density plot with finance.yahoo.com as source
##Requires a data frame with column "Name" (type as.character) and "Tags"
library(tseries)
library(ggplot2)
# get all the quotes for the stocks and put it in a dataframe
get.quotes.df <- function(stocks.df, start){
stock.values <- NULL
#Download all the closing values for each stock
for(index in 1: length(stocks.df$Tags)){
print(stocks.df[index,1])
stock.prices <- get.hist.quote(stocks.df[index, 2], as.Date(start), quote=c("Close"), , , , retclass = c("zoo"))
if(class(stock.values) == "NULL"){
stock.values <- stock.prices
}else{
stock.values <- merge(stock.values, stock.prices)
}
}
#Add stockname as column name
column.names <- c()
for(index in 1:length(stocks.df$Name)){
column.names <- c(column.names, stocks.df[index, 1])
}
names(stock.values) <- column.names
return(stock.values)
}
#returns a dataframe of one stock and removes the NA values
get.stock.df <- function(stock){
stock <- stock[which(!is.na(stock))]
x <- 1:length(stock)
df <- data.frame(x, stock)
return(df)
}
#create a density plot of the stock values
get.stock.density <- function(stock.df){
plot <- qplot(stock.df$stock, data=stock.df, geom='density')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment