Advertisement
Guest User

Untitled

a guest
Jul 29th, 2014
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.73 KB | None | 0 0
  1. import time
  2. import datetime
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import matplotlib.ticker as mticker
  6. import matplotlib.dates as mdates
  7. from matplotlib.finance import candlestick
  8. import matplotlib
  9. import pylab
  10. matplotlib.rcParams.update({'font.size': 9})
  11.  
  12.  
  13. eachStock = 'EBAY','TSLA','AAPL'
  14.  
  15. def rsiFunc(prices, n=14):
  16. deltas = np.diff(prices)
  17. seed = deltas[:n+1]
  18. up = seed[seed>=0].sum()/n
  19. down = -seed[seed<0].sum()/n
  20. rs = up/down
  21. rsi = np.zeros_like(prices)
  22. rsi[:n] = 100. - 100./(1.+rs)
  23.  
  24. for i in range(n, len(prices)):
  25. delta = deltas[i-1]
  26. if delta > 0:
  27. upval = delta
  28. downval = 0.
  29.  
  30. else:
  31. upval = 0
  32. downval = -delta
  33.  
  34. up = (up*(n-1)+upval)/n
  35. down = (down*(n-1)+downval)/n
  36.  
  37. rs = up/down
  38. rsi[i] = 100. - 100./(1.+rs)
  39. return rsi
  40.  
  41.  
  42. def movingaverage(values,window):
  43. weights = np.repeat(1.0, window)/window
  44. smas = np.convolve(values, weights, 'valid')
  45. return smas
  46.  
  47. def ExpMovingAverage(values,window):
  48. weights = np.exp(np.linspace(-1., 0., window))
  49. weights /= weights.sum()
  50. a = np.convolve(values, weights, mode='full')[:len(values)]
  51. a[:window] = a[window]
  52. return a
  53.  
  54. def computeMACD(x, slow=26, fast=12):
  55. '''
  56. macd line = 12ema - 26 ema
  57. signal line = 9ema of the macd line
  58. histogram = macd line - signal line
  59. '''
  60. emaslow = ExpMovingAverage(x, slow)
  61. emafast = ExpMovingAverage(x, fast)
  62. return emaslow, emafast, emafast-emaslow
  63.  
  64.  
  65.  
  66. def graphData(stock,MA1,MA2):
  67. try:
  68. try:
  69. print 'pulling data on',stock
  70. urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=3y/csv'
  71. stockFile = []
  72. try:
  73. sourceCode = urllib2.urlopen(urlToVisit).read()
  74. splitSource = sourceCode.split('\n')
  75. for eachLine in splitSource:
  76. splitLine = eachLine.split(',')
  77. if len(splitLine)==6:
  78. if 'values' not in eachLine:
  79. stockFile.append(eachLine)
  80.  
  81.  
  82. except Exception, e:
  83. print str(e),'failed to organize pulled data'
  84.  
  85.  
  86. except Exception, e:
  87. print str(e),'failed to pull price data'
  88.  
  89. date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile,delimiter=',',unpack=True,
  90.  
  91. converters={ 0: mdates.strpdate2num('%Y%m%d')})
  92. x = 0
  93. y = len(date)
  94. newAr = []
  95. while x < y:
  96. appendLine = date[x],openp[x],closep[x],highp[x],lowp[x],volume[x]
  97. newAr.append(appendLine)
  98. x+=1
  99.  
  100.  
  101. Av1 = movingaverage(closep, MA1)
  102. Av2 = movingaverage(closep, MA2)
  103.  
  104. SP = len(date[MA2-1:])
  105.  
  106. fig = plt.figure(facecolor='#07000d')
  107.  
  108.  
  109.  
  110.  
  111.  
  112. ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
  113. candlestick(ax1, newAr[-SP:], width=.6, colorup='#53C156', colordown='#ff1717')
  114.  
  115. Label1 = str(MA1)+' SMA'
  116. Label2 = str(MA2)+' SMA'
  117. ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=Label1, linewidth=1.5)
  118. ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5)
  119.  
  120.  
  121. ax1.grid(True, color='w')
  122. ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
  123. ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
  124. plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
  125. ax1.yaxis.label.set_color('w')
  126. ax1.spines['bottom'].set_color('#5998ff')
  127. ax1.spines['top'].set_color('#5998ff')
  128. ax1.spines['left'].set_color('#5998ff')
  129. ax1.spines['right'].set_color('#5998ff')
  130. ax1.tick_params(axis='y', colors='w')
  131. ax1.tick_params(axis='x', colors='w')
  132. plt.ylabel('Stock Price and Volume')
  133.  
  134.  
  135.  
  136.  
  137.  
  138. maLeg = plt.legend(loc=9, ncol=2, prop={'size':7},
  139. fancybox=True, borderaxespad=0.)
  140. maLeg.get_frame().set_alpha(0.4)
  141. textEd = pylab.gca().get_legend().get_texts()
  142. pylab.setp(textEd[0:5], color = 'w')
  143.  
  144.  
  145. ax0 = plt.subplot2grid((6,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
  146. rsi = rsiFunc(closep)
  147. rsiCol = '#c1f9f7'
  148. posCol = '#386d13'
  149. negCol = '#8f2020'
  150. ax0.plot(date[-SP:],rsi[-SP:],rsiCol,linewidth=1.5)
  151. ax0.axhline(70, color = negCol)
  152. ax0.axhline(30, color = posCol)
  153. ax0.fill_between(date[-SP:],rsi[-SP:], 70, where=(rsi[-SP:]>=70), facecolor=negCol, edgecolor=negCol)
  154. ax0.fill_between(date[-SP:],rsi[-SP:], 30, where=(rsi[-SP:]<=30), facecolor=posCol, edgecolor=posCol)
  155. ax0.spines['bottom'].set_color('#5998ff')
  156. ax0.spines['top'].set_color('#5998ff')
  157. ax0.spines['left'].set_color('#5998ff')
  158. ax0.spines['right'].set_color('#5998ff')
  159. ax0.text(0.015, 0.95, 'RSI (14)', va='top', color='w', transform=ax0.transAxes)
  160. ax0.tick_params(axis='x', colors='w')
  161. ax0.tick_params(axis='y', colors='w')
  162. ax0.set_yticks([30,70])
  163. ax0.yaxis.label.set_color('w')
  164. #plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='lower'))
  165.  
  166.  
  167.  
  168. volumeMin = 0
  169.  
  170. ax1v = ax1.twinx()
  171. ax1v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor='#00ffe8', alpha=.5)
  172. ax1v.axes.yaxis.set_ticklabels([])
  173. ax1v.grid(False)
  174. ax1v.spines['bottom'].set_color('#5998ff')
  175. ax1v.spines['top'].set_color('#5998ff')
  176. ax1v.spines['left'].set_color('#5998ff')
  177. ax1v.spines['right'].set_color('#5998ff')
  178. ax1v.set_ylim(0, 2*volume.max())
  179. ax1v.tick_params(axis='x', colors='w')
  180. ax1v.tick_params(axis='y', colors='w')
  181.  
  182.  
  183.  
  184. ax2 = plt.subplot2grid((6,4), (5,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
  185. fillcolor = '#00ffe8'
  186. nslow = 26
  187. nfast = 12
  188. nema = 9
  189.  
  190. emaslow, emafast, macd = computeMACD(closep)
  191. ema9 = ExpMovingAverage(macd, nema)
  192.  
  193. ax2.plot(date[-SP:], macd[-SP:], color='#4ee6fd', lw=2)
  194. ax2.plot(date[-SP:], ema9[-SP:], color='#e1edf9', lw=1)
  195. ax2.text(0.015, 0.95, 'MACD 12,26,9', va='top', color='w', transform=ax2.transAxes)
  196. ax2.fill_between(date[-SP:], macd[-SP]-ema9[-SP:], 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor)
  197. ax2.spines['bottom'].set_color('#5998ff')
  198. ax2.spines['top'].set_color('#5998ff')
  199. ax2.spines['left'].set_color('#5998ff')
  200. ax2.spines['right'].set_color('#5998ff')
  201. ax2.tick_params(axis='x', colors='w')
  202. ax2.tick_params(axis='y', colors='w')
  203. plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
  204. ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))
  205.  
  206.  
  207. for label in ax2.xaxis.get_ticklabels():
  208. label.set_rotation(45)
  209.  
  210.  
  211.  
  212.  
  213.  
  214. plt.suptitle(stock,color='w')
  215.  
  216. plt.setp(ax0.get_xticklabels(), visible=False)
  217. plt.setp(ax1.get_xticklabels(), visible=False)
  218.  
  219. plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0)
  220. plt.show()
  221. fig.savefig('example.png',facecolor=fig.get_facecolor())
  222.  
  223.  
  224.  
  225.  
  226. except Exception, e:
  227. print 'failed main loop',str(e)
  228.  
  229. while True:
  230. stockToUse = raw_input('Stock to chart: ')
  231. graphData(stockToUse,20,200)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement