From 272e15b56ced3e706c5ba5de746d7af9dadbdcdc Mon Sep 17 00:00:00 2001 From: "Nicolas P. Rougier" Date: Wed, 7 Sep 2016 16:51:55 +0100 Subject: [PATCH 1/3] FIX: Removed financial demos that stalled because of yahoo requests that never end (timeout way too long) --- examples/misc/longshort.py | 46 ----- examples/pylab_examples/date_demo1.py | 52 ------ examples/pylab_examples/date_demo2.py | 46 ----- examples/pylab_examples/finance_demo.py | 35 ---- examples/pylab_examples/finance_work2.py | 207 ----------------------- 5 files changed, 386 deletions(-) delete mode 100644 examples/misc/longshort.py delete mode 100644 examples/pylab_examples/date_demo1.py delete mode 100755 examples/pylab_examples/date_demo2.py delete mode 100644 examples/pylab_examples/finance_demo.py delete mode 100644 examples/pylab_examples/finance_work2.py diff --git a/examples/misc/longshort.py b/examples/misc/longshort.py deleted file mode 100644 index 8e2a4367c903..000000000000 --- a/examples/misc/longshort.py +++ /dev/null @@ -1,46 +0,0 @@ -""" -Illustrate the rec array utility funcitons by loading prices from a -csv file, computing the daily returns, appending the results to the -record arrays, joining on date -""" -from six.moves import urllib -import numpy as np -import matplotlib.pyplot as plt -import matplotlib.mlab as mlab - -# grab the price data off yahoo -u1 = urllib.request.urlretrieve('http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=9&e=14&f=2008&g=d&a=8&b=7&c=1984&ignore=.csv') -u2 = urllib.request.urlretrieve('http://ichart.finance.yahoo.com/table.csv?s=GOOG&d=9&e=14&f=2008&g=d&a=8&b=7&c=1984&ignore=.csv') - -# load the CSV files into record arrays -r1 = mlab.csv2rec(open(u1[0])) -r2 = mlab.csv2rec(open(u2[0])) - -# compute the daily returns and add these columns to the arrays -gains1 = np.zeros_like(r1.adj_close) -gains2 = np.zeros_like(r2.adj_close) -gains1[1:] = np.diff(r1.adj_close)/r1.adj_close[:-1] -gains2[1:] = np.diff(r2.adj_close)/r2.adj_close[:-1] -r1 = mlab.rec_append_fields(r1, 'gains', gains1) -r2 = mlab.rec_append_fields(r2, 'gains', gains2) - -# now join them by date; the default postfixes are 1 and 2. The -# default jointype is inner so it will do an intersection of dates and -# drop the dates in AAPL which occurred before GOOG started trading in -# 2004. r1 and r2 are reverse ordered by date since Yahoo returns -# most recent first in the CSV files, but rec_join will sort by key so -# r below will be properly sorted -r = mlab.rec_join('date', r1, r2) - - -# long appl, short goog -g = r.gains1 - r.gains2 -tr = (1 + g).cumprod() # the total return - -# plot the return -fig, ax = plt.subplots() -ax.plot(r.date, tr) -ax.set_title('total return: long APPL, short GOOG') -ax.grid() -fig.autofmt_xdate() -plt.show() diff --git a/examples/pylab_examples/date_demo1.py b/examples/pylab_examples/date_demo1.py deleted file mode 100644 index 87b1d658981a..000000000000 --- a/examples/pylab_examples/date_demo1.py +++ /dev/null @@ -1,52 +0,0 @@ -""" -Show how to make date plots in matplotlib using date tick locators and -formatters. See major_minor_demo1.py for more information on -controlling major and minor ticks - -All matplotlib date plotting is done by converting date instances into -days since the 0001-01-01 UTC. The conversion, tick locating and -formatting is done behind the scenes so this is most transparent to -you. The dates module provides several converter functions date2num -and num2date - -This example requires an active internet connection since it uses -yahoo finance to get the data for plotting -""" - -import matplotlib.pyplot as plt -from matplotlib.finance import quotes_historical_yahoo_ochl -from matplotlib.dates import YearLocator, MonthLocator, DateFormatter -import datetime -date1 = datetime.date(1995, 1, 1) -date2 = datetime.date(2004, 4, 12) - -years = YearLocator() # every year -months = MonthLocator() # every month -yearsFmt = DateFormatter('%Y') - -quotes = quotes_historical_yahoo_ochl('INTC', date1, date2) -if len(quotes) == 0: - raise SystemExit - -dates = [q[0] for q in quotes] -opens = [q[1] for q in quotes] - -fig, ax = plt.subplots() -ax.plot_date(dates, opens, '-') - -# format the ticks -ax.xaxis.set_major_locator(years) -ax.xaxis.set_major_formatter(yearsFmt) -ax.xaxis.set_minor_locator(months) -ax.autoscale_view() - - -# format the coords message box -def price(x): - return '$%1.2f' % x -ax.fmt_xdata = DateFormatter('%Y-%m-%d') -ax.fmt_ydata = price -ax.grid(True) - -fig.autofmt_xdate() -plt.show() diff --git a/examples/pylab_examples/date_demo2.py b/examples/pylab_examples/date_demo2.py deleted file mode 100755 index e7a5c270399e..000000000000 --- a/examples/pylab_examples/date_demo2.py +++ /dev/null @@ -1,46 +0,0 @@ -""" -Show how to make date plots in matplotlib using date tick locators and -formatters. See major_minor_demo1.py for more information on -controlling major and minor ticks -""" - -from __future__ import print_function -import datetime -import matplotlib.pyplot as plt -from matplotlib.dates import MONDAY -from matplotlib.finance import quotes_historical_yahoo_ochl -from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter - - -date1 = datetime.date(2002, 1, 5) -date2 = datetime.date(2003, 12, 1) - -# every monday -mondays = WeekdayLocator(MONDAY) - -# every 3rd month -months = MonthLocator(range(1, 13), bymonthday=1, interval=3) -monthsFmt = DateFormatter("%b '%y") - - -quotes = quotes_historical_yahoo_ochl('INTC', date1, date2) -if len(quotes) == 0: - print('Found no quotes') - raise SystemExit - -dates = [q[0] for q in quotes] -opens = [q[1] for q in quotes] - -fig, ax = plt.subplots() -ax.plot_date(dates, opens, '-') -ax.xaxis.set_major_locator(months) -ax.xaxis.set_major_formatter(monthsFmt) -ax.xaxis.set_minor_locator(mondays) -ax.autoscale_view() -#ax.xaxis.grid(False, 'major') -#ax.xaxis.grid(True, 'minor') -ax.grid(True) - -fig.autofmt_xdate() - -plt.show() diff --git a/examples/pylab_examples/finance_demo.py b/examples/pylab_examples/finance_demo.py deleted file mode 100644 index 94f1a3c1b467..000000000000 --- a/examples/pylab_examples/finance_demo.py +++ /dev/null @@ -1,35 +0,0 @@ -import matplotlib.pyplot as plt -from matplotlib.dates import DateFormatter, WeekdayLocator,\ - DayLocator, MONDAY -from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc - - -# (Year, month, day) tuples suffice as args for quotes_historical_yahoo -date1 = (2004, 2, 1) -date2 = (2004, 4, 12) - - -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_ohlc('INTC', 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_ohlc(ax, quotes, width=0.6) - -ax.xaxis_date() -ax.autoscale_view() -plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') - -plt.show() diff --git a/examples/pylab_examples/finance_work2.py b/examples/pylab_examples/finance_work2.py deleted file mode 100644 index 6fa0f3244e58..000000000000 --- a/examples/pylab_examples/finance_work2.py +++ /dev/null @@ -1,207 +0,0 @@ -import datetime -import numpy as np -import matplotlib.colors as colors -import matplotlib.finance as finance -import matplotlib.dates as mdates -import matplotlib.ticker as mticker -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt -import matplotlib.font_manager as font_manager - - -startdate = datetime.date(2006, 1, 1) -today = enddate = datetime.date.today() -ticker = 'SPY' - - -fh = finance.fetch_historical_yahoo(ticker, startdate, enddate) -# a numpy record array with fields: date, open, high, low, close, volume, adj_close) - -r = mlab.csv2rec(fh) -fh.close() -r.sort() - - -def moving_average(x, n, type='simple'): - """ - compute an n period moving average. - - type is 'simple' | 'exponential' - - """ - x = np.asarray(x) - if type == 'simple': - weights = np.ones(n) - else: - weights = np.exp(np.linspace(-1., 0., n)) - - weights /= weights.sum() - - a = np.convolve(x, weights, mode='full')[:len(x)] - a[:n] = a[n] - return a - - -def relative_strength(prices, n=14): - """ - compute the n period relative strength indicator - http://stockcharts.com/school/doku.php?id=chart_school:glossary_r#relativestrengthindex - http://www.investopedia.com/terms/r/rsi.asp - """ - - deltas = np.diff(prices) - seed = deltas[:n+1] - up = seed[seed >= 0].sum()/n - down = -seed[seed < 0].sum()/n - rs = up/down - rsi = np.zeros_like(prices) - rsi[:n] = 100. - 100./(1. + rs) - - for i in range(n, len(prices)): - delta = deltas[i - 1] # cause the diff is 1 shorter - - if delta > 0: - upval = delta - downval = 0. - else: - upval = 0. - downval = -delta - - up = (up*(n - 1) + upval)/n - down = (down*(n - 1) + downval)/n - - rs = up/down - rsi[i] = 100. - 100./(1. + rs) - - return rsi - - -def moving_average_convergence(x, nslow=26, nfast=12): - """ - compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg' - return value is emaslow, emafast, macd which are len(x) arrays - """ - emaslow = moving_average(x, nslow, type='exponential') - emafast = moving_average(x, nfast, type='exponential') - return emaslow, emafast, emafast - emaslow - - -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.7, width, 0.2] -rect2 = [left, 0.3, width, 0.4] -rect3 = [left, 0.1, width, 0.2] - - -fig = plt.figure(facecolor='white') -axescolor = '#f6f6f6' # the axes background color - -ax1 = fig.add_axes(rect1, facecolor=axescolor) # left, bottom, width, height -ax2 = fig.add_axes(rect2, facecolor=axescolor, sharex=ax1) -ax2t = ax2.twinx() -ax3 = fig.add_axes(rect3, facecolor=axescolor, sharex=ax1) - - -# plot the relative strength indicator -prices = r.adj_close -rsi = relative_strength(prices) -fillcolor = 'darkgoldenrod' - -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 (14)', va='top', transform=ax1.transAxes, fontsize=textsize) -ax1.set_title('%s daily' % ticker) - -# plot the price and volume data -dx = r.adj_close - r.close -low = r.low + dx -high = r.high + dx - -deltas = np.zeros_like(prices) -deltas[1:] = np.diff(prices) -up = deltas > 0 -ax2.vlines(r.date[up], low[up], high[up], color='black', label='_nolegend_') -ax2.vlines(r.date[~up], low[~up], high[~up], color='black', label='_nolegend_') -ma20 = moving_average(prices, 20, type='simple') -ma200 = moving_average(prices, 200, type='simple') - -linema20, = ax2.plot(r.date, ma20, color='blue', lw=2, label='MA (20)') -linema200, = ax2.plot(r.date, ma200, color='red', lw=2, label='MA (200)') - - -last = r[-1] -s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' % ( - today.strftime('%d-%b-%Y'), - 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) - -props = font_manager.FontProperties(size=10) -leg = ax2.legend(loc='center left', shadow=True, fancybox=True, prop=props) -leg.get_frame().set_alpha(0.5) - - -volume = (r.close*r.volume)/1e6 # dollar volume in millions -vmax = volume.max() -poly = ax2t.fill_between(r.date, volume, 0, label='Volume', facecolor=fillcolor, edgecolor=fillcolor) -ax2t.set_ylim(0, 5*vmax) -ax2t.set_yticks([]) - - -# compute the MACD indicator -fillcolor = 'darkslategrey' -nslow = 26 -nfast = 12 -nema = 9 -emaslow, emafast, macd = moving_average_convergence(prices, nslow=nslow, nfast=nfast) -ema9 = moving_average(macd, nema, type='exponential') -ax3.plot(r.date, macd, color='black', lw=2) -ax3.plot(r.date, ema9, color='blue', lw=1) -ax3.fill_between(r.date, macd - ema9, 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor) - - -ax3.text(0.025, 0.95, 'MACD (%d, %d, %d)' % (nfast, nslow, nema), 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() From 9192204154e5abbfb34468d1654550a74b3b1cfb Mon Sep 17 00:00:00 2001 From: "Nicolas P. Rougier" Date: Thu, 8 Sep 2016 00:29:27 +0100 Subject: [PATCH 2/3] Removed financial screenshosts --- doc/users/screenshots.rst | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/doc/users/screenshots.rst b/doc/users/screenshots.rst index acc5bd76e47e..9c11c9b5ea42 100644 --- a/doc/users/screenshots.rst +++ b/doc/users/screenshots.rst @@ -102,9 +102,7 @@ command, which includes customizations such as error bars: It's also simple to create stacked bars (`bar_stacked.py <../examples/pylab_examples/bar_stacked.html>`_), -candlestick bars -(`finance_demo.py <../examples/pylab_examples/finance_demo.html>`_), -and horizontal bar charts +or horizontal bar charts (`barh_demo.py <../examples/lines_bars_and_markers/barh_demo.html>`_). .. _screenshots_pie_demo: @@ -184,18 +182,6 @@ for both. See :mod:`matplotlib.ticker` and :mod:`matplotlib.dates` for details and usage. -.. _screenshots_jdh_demo: - -Financial charts -================ - -You can make sophisticated financial plots by combining the various -plot functions, layout commands, and labeling tools provided by matplotlib. -The following example emulates one of the financial plots in -`ChartDirector `_: - - -.. plot:: mpl_examples/pylab_examples/finance_work2.py .. _screenshots_basemap_demo: From 2a5017ac6351139913ce2e76008c6d218b8fe2ee Mon Sep 17 00:00:00 2001 From: "Nicolas P. Rougier" Date: Thu, 8 Sep 2016 09:15:44 +0100 Subject: [PATCH 3/3] Remove reference to the finance demo --- doc/users/legend_guide.rst | 1 - 1 file changed, 1 deletion(-) diff --git a/doc/users/legend_guide.rst b/doc/users/legend_guide.rst index a44bd20a5360..3c204a640e90 100644 --- a/doc/users/legend_guide.rst +++ b/doc/users/legend_guide.rst @@ -293,5 +293,4 @@ being used in various ways: * :ref:`api-legend_demo` * :ref:`pylab_examples-contourf_hatching` * :ref:`pylab_examples-figlegend_demo` -* :ref:`pylab_examples-finance_work2` * :ref:`pylab_examples-scatter_symbol`