Created
March 26, 2010 20:34
-
-
Save mjbommar/345359 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
@author Michael J Bommarito II | |
@date Mar 26, 2010 | |
This is just a cute little example of an asset graph with the max and min spanning trees highlighted. | |
''' | |
import dateutil.parser | |
import csv | |
import igraph | |
import numpy | |
import urllib2 | |
def downloadReturn(symbol): | |
''' | |
Download the data for the given symbol and return the log-return from adjusted close. | |
''' | |
url = 'http://ichart.finance.yahoo.com/table.csv?s={0}&a=02&b=1&c=2010&d=02&e=26&f=2010&g=d&ignore=.csv'.format(symbol) | |
buffer = urllib2.urlopen(url).read() | |
A = [float(row.split(',')[6]) for row in buffer.splitlines()[1:]] | |
return numpy.diff(numpy.log(A)) | |
if __name__ == "__main__": | |
# Set the list of symbols | |
symbols = ['MSFT','IBM','YHOO','GOOG','AKAM','ORCL','HPQ','DELL','INTC','AMD', 'C', 'BAC', 'JPM', 'GS'] | |
# Get the return for each symbol | |
returns = map(downloadReturn, symbols) | |
# Graph data | |
edgelist = [] | |
weights = [] | |
# Correlation threshold | |
threshold = 0.2 | |
''' | |
Construct the graph by seeing which pairs meet our threshold. | |
''' | |
for i in range(len(symbols)): | |
for j in range(i): | |
C = numpy.corrcoef(returns[i], returns[j]) | |
if C[0,1] > threshold: | |
edgelist.append((i,j)) | |
weights.append(C[0,1]) | |
''' | |
Create the graph object and label the vertices. | |
''' | |
g = igraph.Graph(edgelist) | |
for i,v in enumerate(g.vs): | |
v['label'] = symbols[i] | |
# Calculate the layout | |
layout = g.layout_fruchterman_reingold(weights = [int(100 * w) for w in weights]) | |
# Calculate the max and min spanning trees | |
g.es["width"] = [10.0 * w for w in weights] | |
maxst = g.spanning_tree([numpy.exp(-w) for w in weights]) | |
minst = g.spanning_tree([w for w in weights]) | |
''' | |
Now plot the original graph and overlay the two spanning trees. | |
''' | |
fig = igraph.Plot(bbox = (800,800)) | |
fig.add(g, layout=layout, opacity=0.25, vertex_label=symbols, margin = 50) | |
fig.add(maxst, layout=layout, opacity=0.5, edge_color="green", vertex_label=symbols, margin = 50) | |
fig.add(minst, layout=layout, opacity=0.5, edge_color="red", vertex_label=symbols, margin = 50) | |
fig.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment