lolamontes69

Ch10 Ex5(a)- Programming Collective Intelligence

Sep 14th, 2013
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.10 KB | None | 0 0
  1. """ Chapter 10 Exercise 5(a): Alternative display methods.(cont)
  2.  
  3.    Now a trading-volume chart with important dates shown.
  4.    Enter two stock market tickers. First we find some features, then we plot features
  5.    one at a time on graph of trading volumes for the two stocks
  6. """
  7.  
  8. import welcome_to_the_nmf as nmf
  9. import urllib2 as urllib2
  10. from numpy import *
  11. import Gnuplot, Gnuplot.funcutils
  12.  
  13. def volume_chart(tickers,allporder):
  14.     count=0
  15.     coordic={}
  16.     for t in tickers:
  17.         # Open the URL
  18.         print 't=',t
  19.         rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\
  20.                              's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=2005' %t +\
  21.                              '&ignore=.csv').readlines()
  22.         # get coords
  23.         dates={}
  24.         coords=[]
  25.         this=[]
  26.         this=[(r.split(',')) for r in rows if r.strip()!='']
  27.         this.reverse()
  28.         for a in range(len(this)-1):
  29.             dates[this[a][0]]=a
  30.             coord=(a,int(this[a][5]))
  31.             coords.append(coord)
  32.         coordic[count]=coords
  33.         count+=1
  34.     print dates
  35.     for feats in range(len(allporder)):
  36.         g = Gnuplot.Gnuplot(debug=1)
  37.         tittlies='Stock Volume Chart Feature %s' % feats
  38.         g.title(tittlies)
  39.         g('set data style lines')
  40.         g('set grid lt 0 lw 0.5 lc rgb "#ff0000"')
  41.         g('set format y "%f"')
  42.         # g('set arrow from 278,0 to 278,16000000 nohead')
  43.         g('set ylabel "TRADING VOLUME" 2,0')
  44.         labelstocks = 'set xlabel "DATELINE from 03-12-05       %s-Red  %s-Green" 2,0' % (tickers[0], tickers[1])
  45.         g(labelstocks)
  46.         addy=0
  47.         for feat in allporder[feats]:
  48.             addy+=1
  49.             print feat
  50.             # labelfeat = 'set arrow from %d,0 to %d,16000000 nohead' % (dates[feat[1]],dates[feat[1]])
  51.             labelfeat = 'set label "X %s" at %d,2000000*%d textcolor rgb "#000000"' % (feat[1], dates[feat[1]], addy)
  52.             g(labelfeat)
  53.         plot1 = Gnuplot.PlotItems.Data(coordic[0], with_="lines 1", title=None) # 1=red 2=green 3=blue 4=pink...
  54.         plot2 = Gnuplot.PlotItems.Data(coordic[1], with_="lines 2", title=None) # 1=red 2=green 3=blue 4=pink...
  55.         g.plot(plot1,plot2)
  56.         t=raw_input('Press enter to continue')
  57.  
  58.  
  59. def stock_volumes(tickers):
  60.     shortest=300
  61.     prices={}
  62.     dates=None
  63.     allporder=[]
  64.     allols=[]
  65.     for t in tickers:
  66.         # Open the URL
  67.         print 't=',t
  68.         rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\
  69.                              's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=2005' %t +\
  70.                              '&ignore=.csv').readlines()
  71.         # Extract the volume field from every line
  72.         prices[t]=[float(r.split(',')[5]) for r in rows[1:] if r.strip()!='']
  73.         if len(prices[t])<shortest: shortest=len(prices[t])
  74.         if not dates:
  75.             dates=[r.split(',')[0] for r in rows[1:] if r.strip()!='']
  76.     l1=[[prices[tickers[i]][j]
  77.         for i in range(len(tickers))]
  78.        for j in range(shortest)]
  79.     w,h = nmf.factorize(matrix(l1),pc=5)
  80.     # print h
  81.     # print w
  82.     # Loop over all the features
  83.     for i in range(shape(h)[0]):
  84.         print "Feature %d" %i
  85.         # Get the top stocks for this feature
  86.         ol=[(h[i,j],tickers[j]) for j in range(shape(h)[1])]
  87.         ol.sort()
  88.         ol.reverse()
  89.         for j in range(len(tickers)):
  90.             print ol[j]
  91.         allols.append(ol)
  92.         print
  93.         # Show the top dates for this feature
  94.         porder=[(w[d,i],d) for d in range(300)]
  95.         porder.sort()
  96.         porder.reverse()
  97.         f = [(p[0],dates[p[1]]) for p in porder[0:3]]
  98.         print f
  99.         allporder.append(f)
  100.         print
  101.     frog=raw_input('press <ENTER> to continue')
  102.     #return allporder, allols
  103.     return allporder
  104.  
  105. def main():
  106.     tickers=[]
  107.     first=str(raw_input('Enter first ticker >'))
  108.     tickers.append(first)
  109.     second=str(raw_input('Enter first ticker >'))
  110.     tickers.append(second)
  111.     allporder = stock_volumes(tickers)
  112.     volume_chart(tickers, allporder)
  113.  
  114. if __name__ == "__main__":
  115.     main()
Advertisement
Add Comment
Please, Sign In to add comment