|
| 1 | +""" |
| 2 | +You need a additional files to run this example. Save the following |
| 3 | +in the same dir as this file |
| 4 | +
|
| 5 | + http://matplotlib.sourceforge.net/screenshots/helpers.py |
| 6 | +
|
| 7 | + http://matplotlib.sourceforge.net/screenshots/msft_nasdaq_d.csv |
| 8 | +
|
| 9 | + http://matplotlib.sourceforge.net/screenshots/__init__.py |
| 10 | +
|
| 11 | +""" |
| 12 | + |
| 13 | +import time, os, sys, datetime |
| 14 | +from matplotlib import rcParams |
| 15 | +from matplotlib.ticker import IndexLocator, FuncFormatter, NullFormatter, MultipleLocator |
| 16 | +from matplotlib.dates import IndexDateFormatter, date2num |
| 17 | +from matplotlib.finance import candlestick2, plot_day_summary2, \ |
| 18 | + volume_overlay, index_bar |
| 19 | +from pylab import * |
| 20 | + |
| 21 | +rcParams['timezone'] = 'US/Eastern' |
| 22 | +rc('grid', color='0.75', linestyle='-', linewidth=0.5) |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +def load_quotes(fname, maxq=None): |
| 27 | + """ |
| 28 | + Load quotes from the representative data files vineet sent If any |
| 29 | + of the values are missing I force all missing. Quotes are sorted |
| 30 | + in increasing time. Return value is a list of tuples |
| 31 | +
|
| 32 | + (epoch, open, high, low, close, volume ) |
| 33 | + """ |
| 34 | + quotes = [] |
| 35 | + |
| 36 | + for i, line in enumerate(file(fname)): |
| 37 | + if maxq is not None and i>maxq: break |
| 38 | + ts,o,h,l,c,v = line.split(',') |
| 39 | + |
| 40 | + dt = datetime.datetime(*time.strptime(ts.strip('"'), '%Y%m%d%H%M%S')[:6]) # convert to float days |
| 41 | + d = date2num(dt) |
| 42 | + o,h,l,c,v = [float(val) for val in o,h,l,c,v] |
| 43 | + |
| 44 | + if o==-1 or h==-1 or l==-1 or c==-1 or v==-1: |
| 45 | + o,h,l,c,v = -1, -1, -1, -1,-1 |
| 46 | + quotes.append((d,o,h,l,c,v)) |
| 47 | + |
| 48 | + quotes.sort() # increasing time |
| 49 | + return quotes |
| 50 | + |
| 51 | + |
| 52 | +def ema(s, n): |
| 53 | + """ |
| 54 | + returns an n period exponential moving average for |
| 55 | + the time series s |
| 56 | +
|
| 57 | + s is a list ordered from oldest (index 0) to most recent (index |
| 58 | + -1) n is an integer |
| 59 | +
|
| 60 | + returns a numeric array of the exponential moving average |
| 61 | + """ |
| 62 | + s = array(s) |
| 63 | + ema = [] |
| 64 | + j = 1 |
| 65 | + #get n sma first and calculate the next n period ema |
| 66 | + sma = sum(s[:n]) / n |
| 67 | + multiplier = 2 / float(1 + n) |
| 68 | + ema.append(sma) |
| 69 | + #EMA(current) = ( (Price(current) - EMA(prev) ) xMultiplier) + EMA(prev) |
| 70 | + ema.append(( (s[n] - sma) * multiplier) + sma) |
| 71 | + #now calculate the rest of the values |
| 72 | + for i in s[n+1:]: |
| 73 | + tmp = ( (i - ema[j]) * multiplier) + ema[j] |
| 74 | + j = j + 1 |
| 75 | + ema.append(tmp) |
| 76 | + return ema |
| 77 | + |
| 78 | +def movavg(s, n): |
| 79 | + """ |
| 80 | + returns an n period moving average for the time series s |
| 81 | + |
| 82 | + s is a list ordered from oldest (index 0) to most recent (index -1) |
| 83 | + n is an integer |
| 84 | +
|
| 85 | + returns a numeric array of the moving average |
| 86 | +
|
| 87 | + See also ema in this module for the exponential moving average. |
| 88 | + """ |
| 89 | + s = array(s) |
| 90 | + c = cumsum(s) |
| 91 | + return (c[n-1:] - c[:-n+1]) / float(n-1) |
| 92 | + |
| 93 | +def fill_over(ax, x, y, val, color, over=True): |
| 94 | + """ |
| 95 | + Plot filled x,y for all y over val |
| 96 | + if over = False, fill all areas < val |
| 97 | + """ |
| 98 | + ybase = asarray(y)-val |
| 99 | + crossings = nonzero(less(ybase[:-1] * ybase[1:],0)) |
| 100 | + |
| 101 | + if ybase[0]>=0: fillon = over |
| 102 | + else: fillon = not over |
| 103 | + |
| 104 | + |
| 105 | + indLast = 0 |
| 106 | + for ind in crossings: |
| 107 | + if fillon: |
| 108 | + thisX = x[indLast:ind+1] |
| 109 | + thisY = y[indLast:ind+1] |
| 110 | + thisY[0] = val |
| 111 | + thisY[-1] = val |
| 112 | + ax.fill(thisX, thisY, facecolor=color) |
| 113 | + fillon = not fillon |
| 114 | + indLast = ind |
| 115 | + |
| 116 | + |
| 117 | +def random_signal(N, tau): |
| 118 | + 'generate a length N random signal with time constant tau' |
| 119 | + t = arange(float(N)) |
| 120 | + filter = exp(-t/tau) |
| 121 | + return convolve( randn(N), filter, mode=2)[:len(t)] |
| 122 | + |
| 123 | + |
| 124 | + |
| 125 | + |
| 126 | +fname = '../data/msft_nasdaq_d.csv' |
| 127 | +quotes = load_quotes(fname, 200) |
| 128 | +times, opens, highs, lows, closes, volumes = zip(*quotes) |
| 129 | + |
| 130 | +def get_valid(x): |
| 131 | + return array([thisx for thisx in x if thisx!=-1]) |
| 132 | +#valid opens, etc |
| 133 | +vopens = get_valid(opens) |
| 134 | +vcloses = get_valid(closes) |
| 135 | +vlows = get_valid(lows) |
| 136 | +vhighs = get_valid(highs) |
| 137 | +vvolumes = get_valid(volumes) |
| 138 | +vind = array([i for i, o in enumerate(opens) if o!=-1]) |
| 139 | + |
| 140 | +assert(len(vopens)==len(vcloses)==len(vlows)==len(vhighs)==len(vvolumes)) |
| 141 | + |
| 142 | +N = len(vopens) |
| 143 | + |
| 144 | + |
| 145 | + |
| 146 | +figBG = 'w' # the figure background color |
| 147 | +axesBG = '#f6f6f6' # the axies background color |
| 148 | +textsize = 8 # size for axes text |
| 149 | + |
| 150 | +# the demo data are intc from (2003, 9, 1) to (2004, 4, 12 ) with |
| 151 | +# dates as epoch; I saved these to a file for ease of debugginh |
| 152 | +ticker = 'MSFT' |
| 153 | + |
| 154 | + |
| 155 | +figure(1, facecolor=figBG) |
| 156 | + |
| 157 | +def get_locator(): |
| 158 | + """ |
| 159 | + the axes cannot share the same locator, so this is a helper |
| 160 | + function to generate locators that have identical functionality |
| 161 | + """ |
| 162 | + |
| 163 | + return IndexLocator(10, 1) |
| 164 | + |
| 165 | + |
| 166 | +formatter = IndexDateFormatter(times, '%b %d %y') |
| 167 | + |
| 168 | +nullfmt = NullFormatter() # no labels |
| 169 | + |
| 170 | +def fmt_vol(x,pos): |
| 171 | + if pos>3: return '' # only label the first 3 ticks |
| 172 | + return '%dM' % int(x*1e-6) |
| 173 | + |
| 174 | +volumeFmt = FuncFormatter(fmt_vol) |
| 175 | + |
| 176 | +left, width = 0.1, 0.8 |
| 177 | +rect1 = [left, 0.7, width, 0.2] |
| 178 | +rect2 = [left, 0.3, width, 0.4] |
| 179 | +rect3 = [left, 0.1, width, 0.2] |
| 180 | +axUpper = axes(rect1, axisbg=axesBG) #left, bottom, width, height |
| 181 | +axMiddle = axes(rect2, axisbg=axesBG, sharex=axUpper) |
| 182 | +axMiddleVol = axes(rect2, axisbg=axesBG, frameon=False, sharex=axUpper) # the volume overlay |
| 183 | +axLower = axes(rect3, axisbg=axesBG, sharex=axUpper) |
| 184 | + |
| 185 | + |
| 186 | +axUpper.xaxis.set_major_locator( get_locator() ) |
| 187 | +axUpper.xaxis.set_major_formatter(nullfmt) |
| 188 | +axUpper.grid(True) |
| 189 | + |
| 190 | +# set up two scales on middle axes with left and right ticks |
| 191 | +axMiddle.yaxis.tick_left() |
| 192 | +axMiddle.xaxis.set_major_locator( get_locator() ) |
| 193 | +axMiddle.yaxis.set_major_locator( MultipleLocator(5) ) |
| 194 | +axMiddle.xaxis.set_major_formatter(nullfmt) |
| 195 | + |
| 196 | +axMiddleVol.yaxis.tick_right() |
| 197 | +axMiddleVol.xaxis.set_major_locator( get_locator() ) |
| 198 | +axMiddleVol.xaxis.set_major_formatter(nullfmt) |
| 199 | +axMiddleVol.yaxis.set_major_formatter(volumeFmt) |
| 200 | +axMiddle.grid(True) |
| 201 | + |
| 202 | +axLower.xaxis.set_major_locator( get_locator() ) |
| 203 | +axLower.xaxis.set_major_formatter( formatter ) |
| 204 | +axLower.grid(True) |
| 205 | + |
| 206 | +if 1: ############### Upper axes ################# |
| 207 | + |
| 208 | + # make up a pseudo signal |
| 209 | + purple = '#660033' |
| 210 | + s = random_signal(len(vind), tau=20) |
| 211 | + thresh = 4 |
| 212 | + axUpper.plot(s, color=purple) |
| 213 | + # upper horiz line |
| 214 | + |
| 215 | + |
| 216 | + |
| 217 | + axUpper.plot( (0, N), [thresh, thresh], color=purple, linewidth=1) |
| 218 | + # lower horiz line |
| 219 | + axUpper.plot( (0, N), [-thresh, -thresh], color=purple, linewidth=1) |
| 220 | + |
| 221 | + |
| 222 | + # fill above threshold |
| 223 | + fill_over(axUpper, vind, s, thresh, purple, over=True) |
| 224 | + fill_over(axUpper, vind, s, -thresh, purple, over=False) |
| 225 | + |
| 226 | + t = axUpper.set_title('Microsoft Corp (MSFT)', |
| 227 | + fontsize=12) |
| 228 | + t.set_y(1.05) # move it up a bit higher than the default |
| 229 | + t.set_x(0) # align the title left, axes coords |
| 230 | + t.set_horizontalalignment('left') # align the title left, axes coords |
| 231 | + axUpper.yaxis.set_major_locator( MultipleLocator(5) ) |
| 232 | + |
| 233 | + |
| 234 | + |
| 235 | + # now add some text |
| 236 | + left, height, top = 0.025, 0.06, 0.85 |
| 237 | + t = axUpper.text(left, top, 'RSI(14) 51.0', fontsize=textsize, |
| 238 | + transform=axUpper.transAxes) |
| 239 | + |
| 240 | + |
| 241 | +if 1: ############### Middle axes ################# |
| 242 | + |
| 243 | + #plot_day_summary2(axMiddle, opens, closes, highs, lows) |
| 244 | + candlestick2(axMiddle, opens, closes, highs, lows, width=0.9) |
| 245 | + |
| 246 | + # specify the text in axes (0,1) coords. 0,0 is lower left and 1,1 is |
| 247 | + # upper right |
| 248 | + |
| 249 | + left, height, top = 0.025, 0.06, 0.9 |
| 250 | + t1 = axMiddle.text(left, top, '%s daily'%ticker, fontsize=textsize, |
| 251 | + transform=axMiddle.transAxes) |
| 252 | + t2 = axMiddle.text(left, top-height, 'MA(5)', color='b', fontsize=textsize, |
| 253 | + transform=axMiddle.transAxes) |
| 254 | + t3 = axMiddle.text(left, top-2*height, 'MA(20)', color='r', fontsize=textsize, |
| 255 | + transform=axMiddle.transAxes) |
| 256 | + |
| 257 | + s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' %( |
| 258 | + time.strftime('%d-%b-%Y'), |
| 259 | + vopens[-1], vhighs[-1], |
| 260 | + vlows[-1], vcloses[-1], |
| 261 | + vvolumes[-1]*1e-6, |
| 262 | + vcloses[-1]-vopens[-1]) |
| 263 | + t4 = axMiddle.text(0.4, top, s, fontsize=textsize, |
| 264 | + transform=axMiddle.transAxes) |
| 265 | + |
| 266 | + |
| 267 | + # now do the moviing average. I'll use a convolution to simulate a |
| 268 | + # real moving average |
| 269 | + ma5 = movavg(vopens, 5) |
| 270 | + ma20 = movavg(vopens, 20) |
| 271 | + axMiddle.plot(vind[5-1:], ma5, 'b', linewidth=1) |
| 272 | + axMiddle.plot(vind[20-1:], ma20, 'r', linewidth=1) |
| 273 | + |
| 274 | + axMiddle.set_ylim((20, 32)) |
| 275 | + axMiddle.set_yticks((25,30)) |
| 276 | + |
| 277 | + # Now do the volume overlay |
| 278 | + |
| 279 | + bars = volume_overlay(axMiddleVol, opens, closes, volumes, alpha=0.5) |
| 280 | + axMiddleVol.set_ylim((0, 3*max(vvolumes))) # use only a third of the viewlim |
| 281 | + |
| 282 | + |
| 283 | +if 1: ############### Lower axes ################# |
| 284 | + |
| 285 | + # make up two signals; I don't know what the signals are in real life |
| 286 | + # so I'll just illustrate the plotting stuff |
| 287 | + s1 = random_signal(len(vind), 10) |
| 288 | + s2 = random_signal(len(vind), 20) |
| 289 | + |
| 290 | + axLower.plot(vind, s1, color=purple) |
| 291 | + axLower.plot(vind, s2, color='k', linewidth=1.0) |
| 292 | + s3 = s2-s1 |
| 293 | + axLower.plot(vind, s3, color='#cccc99') # wheat |
| 294 | + bars = index_bar(axLower, s3, width=2, alpha=0.5, |
| 295 | + facecolor='#3087c7', edgecolor='#cccc99') |
| 296 | + axLower.yaxis.set_major_locator(MultipleLocator(5)) |
| 297 | + |
| 298 | + |
| 299 | + # now add some text |
| 300 | + left, height, top = 0.025, 0.06, 0.85 |
| 301 | + |
| 302 | + t = axLower.text(left, top, 'MACD(12,26,9) -0.26', fontsize=textsize, |
| 303 | + transform=axLower.transAxes) |
| 304 | + |
| 305 | + # make sure everyone has the same axes limits |
| 306 | + |
| 307 | + setp(axLower.get_xticklabels(), 'rotation', 45, |
| 308 | + 'horizontalalignment', 'right', fontsize=8) |
| 309 | + |
| 310 | +# force all the axes to have the same x data limits |
| 311 | +allAxes = (axUpper, axMiddle, axMiddleVol, axLower) |
| 312 | +xlim = 0, len(quotes) |
| 313 | +for a in allAxes: |
| 314 | + #a.dataLim.intervalx = xlim |
| 315 | + a.set_xlim(xlim) |
| 316 | + |
| 317 | +for ax in axUpper, axMiddle: |
| 318 | + for ticklabel in ax.get_xticklabels(): |
| 319 | + ticklabel.set_visible(False) |
| 320 | + |
| 321 | +show() |
0 commit comments