def countdown(ax, signal): bars = [[b['dt'].to_pydatetime(), b['open'], b['close'], b['high'], b['low']] for b in signal['bars']] finance.plot_day_summary(ax, bars) for i, pos in enumerate(signal['signals']): label_bar(ax, i, bars[pos]) return bars
def setup(ax, signal): bars = signal['flip']['bars'] + signal['bars'] bars = [[b['dt'].to_pydatetime(), b['open'], b['close'], b['high'], b['low']] for b in bars] finance.plot_day_summary(ax, bars) flip_end = len(signal['flip']['bars']) - 1 label_bar(ax, 'X', bars[0], True) label_bar(ax, 'Y', bars[1], True) label_bar(ax, "X'", bars[flip_end - 1], True,) label_bar(ax, "Y'", bars[flip_end], True) for i, bar in enumerate(bars[flip_end:], 1): label_bar(ax, i, bar) return bars
plot_day_summary, candlestick2 date1 = (2013, 10, 20) date2 = (2013, 11, 10) ticker = 'IBM' mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 quotes = quotes_historical_yahoo(ticker, date1, date2) if len(quotes) == 0: raise SystemExit fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) ax.xaxis.set_minor_formatter(dayFormatter) plot_day_summary(ax, quotes, ticksize=3) candlestick(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=80, horizontalalignment='right') plt.figtext(0.35, 0.45, '10/29: Open, High, Low, Close') plt.figtext(0.35, 0.42, ' 177.62, 182.32, 177.50, 182.12') plt.figtext(0.35, 0.32, 'Black ==> Close > Open ') plt.figtext(0.35, 0.28, 'Red ==> Close < Open ') plt.title('Candlesticks for IBM from 10/20/2013 to 11/10/2013') plt.ylabel('Price') plt.xlabel('Date') plt.show()
plt.figtext(0.9, 0.075, "$x$") plt.figtext(0.075, 0.9, "$f(x)$") ax.set_xticks((a, b)) ax.set_xticklabels(("$a$", "$b$")) ax.set_yticks([func(a), func(b)]) ax.set_yticklabels(("$f(a)$", "$f(b)$")) plt.grid(True) import matplotlib.finance as mpf start = (2014, 5, 1) end = (2014, 6, 30) quotes = mpf.quotes_historical_yahoo("^GDAXI", start, end) fig, ax = plt.subplots(figsize=(8, 5)) mpf.plot_day_summary(ax, quotes, colorup="b", colordown="r") plt.grid(True) ax.xaxis_date() plt.title("DAX Index") plt.ylabel("index level") plt.setp(plt.gca().get_xticklabels(), rotation=30) quotes = np.array(mpf.quotes_historical_yahoo("YHOO", start, end)) fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(8, 6)) mpf.candlestick(ax1, quotes, width=0.6, colorup="b", colordown="r") ax1.set_title("Yahoo Inc.") ax1.set_ylabel("index level") ax1.grid(True)
# you can specify dates in any format you have a converter for. # matplotlib will convert everything under the hood to seconds since # the epoch, but you shouldn't have to deal with this date1 = datetime.date(2004, 2, 1) date2 = datetime.date(2004, 4, 12) # quotes in Eastern time zone converter = PyDatetimeConverter() mondays = WeekdayLocator(MONDAY) # major ticks on the mondays hours = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # Eg, Jan 12 dayFormatter = DateFormatter('%d') # Eg, 12 quotes = quotes_historical_yahoo('INTC', date1, date2, converter) if not quotes: raise SystemExit ax = subplot(111) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(hours) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) plot_day_summary(ax, quotes, ticksize=3, converter=converter) #candlestick(ax, quotes, width=0.6, converter=converter) set(gca().get_xticklabels(), 'rotation', 45, 'horizontalalignment', 'right') show()
# the epoch, but you shouldn't have to deal with this date1 = datetime.date( 2004, 2, 1 ) date2 = datetime.date( 2004, 4, 12 ) # quotes in Eastern time zone converter = PyDatetimeConverter() mondays = WeekdayLocator(MONDAY) # major ticks on the mondays hours = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # Eg, Jan 12 dayFormatter = DateFormatter('%d') # Eg, 12 quotes = quotes_historical_yahoo( 'INTC', date1, date2, converter) if not quotes: raise SystemExit ax = subplot(111) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(hours) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) plot_day_summary(ax, quotes, ticksize=3, converter=converter) #candlestick(ax, quotes, width=0.6, converter=converter) set( gca().get_xticklabels(), 'rotation', 45, 'horizontalalignment', 'right') show()
plot_day_summary, candlestick2 date1 = ( 2013, 10, 20) date2 = ( 2013, 11, 10 ) ticker='IBM' mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 quotes = quotes_historical_yahoo(ticker, date1, date2) if len(quotes) == 0: raise SystemExit fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) ax.xaxis.set_minor_formatter(dayFormatter) plot_day_summary(ax, quotes, ticksize=3) candlestick(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() plt.setp( plt.gca().get_xticklabels(), rotation=80, horizontalalignment='right') plt.figtext(0.35,0.45, '10/29: Open, High, Low, Close') plt.figtext(0.35,0.42, ' 177.62, 182.32, 177.50, 182.12') plt.figtext(0.35,0.32, 'Black ==> Close > Open ') plt.figtext(0.35,0.28, 'Red ==> Close < Open ') plt.title('Candlesticks for IBM from 10/20/2013 to 11/10/2013') plt.ylabel('Price') plt.xlabel('Date') plt.show()
def plot_ticker(ticker, r, rsi, cmf, macd, ema): prices = r.adj_close dx = r.adj_close - r.close low = r.low + dx high = r.high + dx ma10 = talib.SMA(r.adj_close, 10) ma50 = talib.SMA(r.adj_close, 50) last = r[-1] volume = r.volume vmax = volume.max() prices = [] for row in r: adj_ratio = row.adj_close/row.close # line = dates.date2num(row.date),row.open*adj_ratio,row.close*adj_ratio,row.low*adj_ratio,row.high*adj_ratio,row.volume line = dates.date2num(row.date),row.open*adj_ratio,row.close*adj_ratio,row.high*adj_ratio,row.low*adj_ratio,row.volume prices.append(line) ### plot the figure plt.rc('axes', grid=True) plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5) textsize = 9 left, width = 0.1, 0.8 rect1 = [left, 0.8, width, 0.1] rect2 = [left, 0.3, width, 0.5] rect3 = [left, 0.2, width, 0.1] rect4 = [left, 0.1, width, 0.1] fig = plt.figure(facecolor='white') axescolor = '#f6f6f6' # the axes background color ax1 = fig.add_axes(rect1, axisbg=axescolor) #left, bottom, width, height ax2 = fig.add_axes(rect2, axisbg=axescolor, sharex=ax1) ax2t = ax2.twinx() ax3 = fig.add_axes(rect3, axisbg=axescolor, sharex=ax1) ax4 = fig.add_axes(rect4, axisbg=axescolor, sharex=ax1) ### plot the relative strength indicator fillcolor = 'darkgoldenrod' print len(rsi) print len(cmf) ax1.plot(r.date, rsi, color=fillcolor) ax1.axhline(70, color=fillcolor) ax1.axhline(30, color=fillcolor) ax1.fill_between(r.date, rsi, 70, where=(rsi>=70), facecolor=fillcolor, edgecolor=fillcolor) ax1.fill_between(r.date, rsi, 30, where=(rsi<=30), facecolor=fillcolor, edgecolor=fillcolor) ax1.text(0.6, 0.9, '>70 = overbought', va='top', transform=ax1.transAxes, fontsize=textsize) ax1.text(0.6, 0.1, '<30 = oversold', transform=ax1.transAxes, fontsize=textsize) ax1.set_ylim(0, 100) ax1.set_yticks([30,70]) ax1.text(0.025, 0.95, 'RSI (%d)'%settings['rsi']['timeperiod'], va='top', transform=ax1.transAxes, fontsize=textsize) ax1.set_title('%s daily'%ticker) ### plot the chaikin money flow ax4.plot(r.date, cmf, color=fillcolor) ax4.axhline(0, color=fillcolor) ax4.fill_between(r.date, cmf, 0, where=None, facecolor=fillcolor, edgecolor=fillcolor) ax4.set_yticks([-0.5, 0, 0.5]) ax4.text(0.025, 0.95, 'CMF (%d)'%settings['cmf']['timeperiod'], va='top', transform=ax4.transAxes, fontsize=textsize) ### plot the price and volume data plot_day_summary(ax2, prices, colorup='#53c156', colordown='#ff1717') s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' % ( last.date, last.open, last.high, last.low, last.close, last.volume*1e-6, last.close-last.open ) t4 = ax2.text(0.3, 0.9, s, transform=ax2.transAxes, fontsize=textsize) ax2.plot(r.date, ma10, color='blue', lw=1, label='MA (10)') ax2.plot(r.date, ma50, color='pink', lw=1, label='MA (50)') props = font_manager.FontProperties(size=10) leg = ax2.legend(loc='upper left', shadow=True, fancybox=True, prop=props) leg.get_frame().set_alpha(0.5) poly = ax2t.fill_between(r.date, volume, 0, label='Volume', facecolor=fillcolor, edgecolor=fillcolor) ax2t.set_ylim(0, 5*vmax) ax2t.set_yticks([]) ### plot the MACD indicator fillcolor = 'darkslategrey' ax3.plot(r.date, macd, color='blue', lw=1) ax3.plot(r.date, ema, color='green', lw=1) ax3.fill_between(r.date, macd-ema, 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor) ax3.text(0.025, 0.95, 'MACD (%d, %d, %d)'%(settings['macd']['fastperiod'], settings['macd']['slowperiod'], settings['macd']['signalperiod']), va='top', transform=ax3.transAxes, fontsize=textsize) #ax3.set_yticks([]) # turn off upper axis tick labels, rotate the lower ones, etc for ax in ax1, ax2, ax2t, ax3: if ax!=ax3: for label in ax.get_xticklabels(): label.set_visible(False) else: for label in ax.get_xticklabels(): label.set_rotation(30) label.set_horizontalalignment('right') ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d') class MyLocator(mticker.MaxNLocator): def __init__(self, *args, **kwargs): mticker.MaxNLocator.__init__(self, *args, **kwargs) def __call__(self, *args, **kwargs): return mticker.MaxNLocator.__call__(self, *args, **kwargs) # at most 5 ticks, pruning the upper and lower so they don't overlap # with other ticks #ax2.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both')) #ax3.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both')) ax2.yaxis.set_major_locator(MyLocator(5, prune='both')) ax3.yaxis.set_major_locator(MyLocator(5, prune='both')) plt.show() #ticker='AAPL' #DATA_DIR = 'data/' # #fh = open(DATA_DIR + ticker) ## a numpy record array with fields: date, open, high, low, close, volume, adj_close) #r = mlab.csv2rec(fh) #fh.close() #r.sort() # #### compute everything #rsi = talib.RSI(r.adj_close) #macd, macdsignal, macdhist = talib.MACD(r.adj_close, fastperiod=nfast, slowperiod=nslow) #ema = talib.EMA(macd, nema) # #plot_ticker(ticker, r, rsi, macd, ema)