Skip to content

Instantly share code, notes, and snippets.

@boersmamarcel
Created May 30, 2012 19:05
Show Gist options
  • Save boersmamarcel/2838323 to your computer and use it in GitHub Desktop.
Save boersmamarcel/2838323 to your computer and use it in GitHub Desktop.
Directed Stock Correlation Graph
##Requires a data frame with column "Name" (type as.character) and "Tags"
library(tseries)
library(igraph)
# 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, as.character(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')
}
#command for markt correlation (AEX)
#Name of stocks
Name <- c("AEX", "AEGON", "AHOLD", "AIRFRANCE", "AKZONOBEL", "APERAM", "ARCELORMITTAL", "ASML", "BOSKALIS", "DSM", "FUGRO", "HEINEKEN", "INGGROEP", "KPN", "PHILIPS", "POSTNL", "RANDSTAD", "RDSHELL", "REEDELSEVIER", "SBMOFFSHORE", "TNTEXPRESS", "TOMTOM", "UNIBAILRODAMCO", "UNILEVER", "WOLTERSKLUWERS");
#Yahoo finance tags
Tags <- c("^AEX", "AGN.AS", "AH.AS", "AF.AS", "AKZA.AS", "APAM.AS", "MT.AS", "ASML.AS", "BOKA.AS", "DSM.AS", "FUR.AS", "HEIA.AS", "INGA.AS", "KPN.AS", "PHIA.AS", "PNL.AS", "RAND.AS", "RDSA.AS", "REN.AS", "SBMO.AS", "TNTE.AS", "TOM2.AS", "UL.AS", "UNA.AS", "WKL.AS");
#data frame with stock info
aandelen.df <- data.frame(Name, Tags);
#download stock info from yahoo.finance.com
aandelen.quotes.df <- get.quotes.df(aandelen.df, "2001-01-01");
#replace all the NA values with 0
aandelen.quotes.df[is.na(aandelen.quotes.df)] <- 0;
#calculate the correlations
cor.df <- cor(aandelen.quotes.df);
cor.df[which(cor.df <= 0.8 | cor.df == 1)] <- 0;
cor.graph <- graph.adjacency(cor.df, mode=c("undirected"), weighted=TRUE);
write.graph(cor.graph, "correlationgraph.graphml", format=c("graphml"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment