From 2c4727a0df3feb304f4c04f3e47c0b5531896588 Mon Sep 17 00:00:00 2001 From: kramer65 Date: Mon, 25 Feb 2013 13:55:58 +0100 Subject: [PATCH 01/29] Update of finance.py to (O,H,L,C) instead of (O,C,H,L) In the financial world, a bar-chart is commonly called an OHLC-chart or "Open-High-Low-Close chart". Also see http://en.wikipedia.org/wiki/Open-high-low-close_chart or simply google around. To my surprise this library uses a sequence of OCHL instead of OHLC. Although it changes the API, I found it important to comply with financial industry standards. This makes it easier to implement this library in existing financial software and thus more likely to be used in the future. --- lib/matplotlib/finance.py | 48 +++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index c9a6358a6a35..72ae3be09594 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -43,9 +43,9 @@ ('day', np.int8), ('d', np.float), # mpl datenum ('open', np.float), - ('close', np.float), ('high', np.float), ('low', np.float), + ('close', np.float), ('volume', np.float), ('aclose', np.float)]) @@ -55,7 +55,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): Parse the historical data in file handle fh from yahoo finance. *adjusted* - If True (default) replace open, close, high, and low prices with + If True (default) replace open, high, low, close prices with their adjusted values. The adjustment is by a scale factor, S = adjusted_close/close. Adjusted prices are actual prices multiplied by S. @@ -70,15 +70,15 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): If False (default for compatibility with earlier versions) return a list of tuples containing - d, open, close, high, low, volume + d, open, high, low, close, volume If None (preferred alternative to False), return a 2-D ndarray corresponding to the list of tuples. Otherwise return a numpy recarray with - date, year, month, day, d, open, close, high, low, - volume, aclose + date, year, month, day, d, open, high, low, close, + volume, adjusted_close where d is a floating poing representation of date, as returned by date2num, and date is a python standard @@ -113,25 +113,25 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): aclose = float(vals[6]) results.append((dt, dt.year, dt.month, dt.day, - dnum, open, close, high, low, volume, aclose)) + dnum, open, high, low, close, volume, aclose)) results.reverse() d = np.array(results, dtype=stock_dt) if adjusted: scale = d['aclose'] / d['close'] scale[np.isinf(scale)] = np.nan d['open'] *= scale - d['close'] *= scale d['high'] *= scale d['low'] *= scale + d['close'] *= scale if not asobject: # 2-D sequence; formerly list of tuples, now ndarray ret = np.zeros((len(d), 6), dtype=np.float) ret[:,0] = d['d'] ret[:,1] = d['open'] - ret[:,2] = d['close'] ret[:,3] = d['high'] ret[:,4] = d['low'] + ret[:,2] = d['close'] ret[:,5] = d['volume'] if asobject is None: return ret @@ -250,9 +250,9 @@ def plot_day_summary(ax, quotes, ticksize=3, colorup='k', colordown='r', ): """ - quotes is a sequence of (time, open, close, high, low, ...) sequences + quotes is a sequence of (time, open, high, low, close, ...) sequences - Represent the time, open, close, high, low as a vertical line + Represent the time, open, high, low, close as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. @@ -268,7 +268,7 @@ def plot_day_summary(ax, quotes, ticksize=3, lines = [] for q in quotes: - t, open, close, high, low = q[:5] + t, open, high, low, close = q[:5] if close>=open : color = colorup else : color = colordown @@ -310,13 +310,13 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', """ - quotes is a sequence of (time, open, close, high, low, ...) sequences. + quotes is a sequence of (time, open, high, low, close, ...) sequences. As long as the first 5 elements are these values, the record can be as long as you want (eg it may store volume). time must be in float days format - see date2num - Plot the time, open, close, high, low as a vertical line ranging + Plot the time, open, high, low, close as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, otherwise use colordown @@ -337,7 +337,7 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', lines = [] patches = [] for q in quotes: - t, open, close, high, low = q[:5] + t, open, high, low, close = q[:5] if close>=open : color = colorup @@ -374,12 +374,12 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', return lines, patches -def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, +def plot_day_summary2(ax, opens, highs, lows, closes ticksize=4, colorup='k', colordown='r', ): """ - Represent the time, open, close, high, low as a vertical line + Represent the time, open, high, low, close as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. @@ -391,7 +391,7 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, return value is a list of lines added """ - # note this code assumes if any value open, close, low, high is + # note this code assumes if any value open, low, high, close is # missing they all are missing rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1 ] @@ -467,7 +467,7 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, return rangeCollection, openCollection, closeCollection -def candlestick2(ax, opens, closes, highs, lows, width=4, +def candlestick2(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75, ): @@ -486,7 +486,7 @@ def candlestick2(ax, opens, closes, highs, lows, width=4, return value is lineCollection, barCollection """ - # note this code assumes if any value open, close, low, high is + # note this code assumes if any value open, low, high, close is # missing they all are missing delta = width/2. @@ -609,7 +609,7 @@ def volume_overlay3(ax, quotes, width=4, alpha=1.0): """ Add a volume overlay to the current axes. quotes is a list of (d, - open, close, high, low, volume) and close-open is used to + open, high, low, close, volume) and close-open is used to determine the color of the bar kwarg @@ -629,7 +629,7 @@ def volume_overlay3(ax, quotes, False : colordown, } - dates, opens, closes, highs, lows, volumes = zip(*quotes) + dates, opens, highs, lows, closes, volumes = zip(*quotes) colors = [colord[close1>=close0] for close0, close1 in zip(closes[:-1], closes[1:]) if close0!=-1 and close1 !=-1] colors.insert(0,colord[closes[0]>=opens[0]]) @@ -637,14 +637,14 @@ def volume_overlay3(ax, quotes, left = -width/2.0 - bars = [ ( (left, 0), (left, volume), (right, volume), (right, 0)) for d, open, close, high, low, volume in quotes] + bars = [ ( (left, 0), (left, volume), (right, volume), (right, 0)) for d, open, high, low, close, volume in quotes] sx = ax.figure.dpi * (1.0/72.0) # scale for points sy = ax.bbox.height / ax.viewLim.height barTransform = Affine2D().scale(sx,sy) - dates = [d for d, open, close, high, low, volume in quotes] + dates = [d for d, open, high, low, close, volume in quotes] offsetsBars = [(d, 0) for d in dates] useAA = 0, # use tuple here @@ -666,7 +666,7 @@ def volume_overlay3(ax, quotes, minpy, maxx = (min(dates), max(dates)) miny = 0 - maxy = max([volume for d, open, close, high, low, volume in quotes]) + maxy = max([volume for d, open, high, low, close, volume in quotes]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) #print 'datalim', ax.dataLim.bounds From 8745e3afb8ae40ccb1c4ae62d64f024fba26141c Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Thu, 18 Apr 2013 00:17:54 -0500 Subject: [PATCH 02/29] implemented the wrappers discussed in #1783. Added deprecation warning to `plot_day_summary2` and returned call signature to what it was. Added alias `plot_day_summary_ochl` with same call signature as `plot_day_summary2`. renamed the modified function to `plot_day_summary_ohlc`. The first two functions simply call the third with the arguments re-ordered. --- lib/matplotlib/finance.py | 54 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 72ae3be09594..2bd9b9b3be5c 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -26,6 +26,7 @@ from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D +from matplotlib import MatplotlibDeprecationWarning as mplDeprecation cachedir = get_cachedir() # cachedir will be None if there is no writable directory. @@ -374,11 +375,62 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', return lines, patches -def plot_day_summary2(ax, opens, highs, lows, closes ticksize=4, +def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, colorup='k', colordown='r', ): """ + Represent the time, open, close, high, low, as a vertical line + ranging from low to high. The left tick is the open and the right + tick is the close. + + ax : an Axes instance to plot to + ticksize : size of open and close ticks in points + colorup : the color of the lines where close >= open + colordown : the color of the lines where close < open + + return value is a list of lines added + """ + + warnings.warn("This function has been deprecated in 1.3 in favor" + "of `plot_day_summary_ochl`," + "which maintains the natural argument order," + "or `plot_day_summary_ohlc`," + "which uses the open-high-low-close order." + "This function will be removed in 1.4", mplDeprecation) + return plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize, + colorup, colordown) + + +def plot_day_summary_ochl(ax, opens, closes, highs, lows, ticksize=4, + colorup='k', colordown='r', + ): + + """ + + Represent the time, open, close, high, low, as a vertical line + ranging from low to high. The left tick is the open and the right + tick is the close. + + ax : an Axes instance to plot to + ticksize : size of open and close ticks in points + colorup : the color of the lines where close >= open + colordown : the color of the lines where close < open + + return value is a list of lines added + """ + + return plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize, + colorup, colordown) + + + +def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, + colorup='k', colordown='r', + ): + + """ + Represent the time, open, high, low, close as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. From f16dc477868e0e9787c2ceaf669eed6ae33c4e47 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 24 Apr 2013 15:52:26 -0500 Subject: [PATCH 03/29] import and pep8 changes --- lib/matplotlib/finance.py | 370 +++++++++++++++++++------------------- 1 file changed, 182 insertions(+), 188 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 2bd9b9b3be5c..7f750ecb2f3e 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -4,7 +4,10 @@ """ from __future__ import division, print_function -import contextlib, os, sys, warnings +import contextlib +import os +import sys +import warnings from urllib2 import urlopen if sys.version_info[0] < 3: @@ -26,7 +29,7 @@ from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D -from matplotlib import MatplotlibDeprecationWarning as mplDeprecation +from cbook import mplDeprecation cachedir = get_cachedir() # cachedir will be None if there is no writable directory. @@ -101,7 +104,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): for line in lines[1:]: vals = line.split(',') - if len(vals)!=7: + if len(vals) != 7: continue # add warning? datestr = vals[0] #dt = datetime.date(*time.strptime(datestr, datefmt)[:3]) @@ -109,7 +112,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): # format, we don't need it. dt = datetime.date(*[int(val) for val in datestr.split('-')]) dnum = date2num(dt) - open, high, low, close = [float(val) for val in vals[1:5]] + open, high, low, close = [float(val) for val in vals[1:5]] volume = float(vals[5]) aclose = float(vals[6]) @@ -128,12 +131,12 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): if not asobject: # 2-D sequence; formerly list of tuples, now ndarray ret = np.zeros((len(d), 6), dtype=np.float) - ret[:,0] = d['d'] - ret[:,1] = d['open'] - ret[:,3] = d['high'] - ret[:,4] = d['low'] - ret[:,2] = d['close'] - ret[:,5] = d['volume'] + ret[:, 0] = d['d'] + ret[:, 1] = d['open'] + ret[:, 3] = d['high'] + ret[:, 4] = d['low'] + ret[:, 2] = d['close'] + ret[:, 5] = d['volume'] if asobject is None: return ret return [tuple(row) for row in ret] @@ -141,7 +144,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): return d.view(np.recarray) # Close enough to former Bunch return -def fetch_historical_yahoo(ticker, date1, date2, cachename=None,dividends=False): +def fetch_historical_yahoo(ticker, date1, date2, cachename=None, dividends=False): """ Fetch historical data for ticker between date1 and date2. date1 and date2 are date or datetime instances, or (year, month, day) sequences. @@ -161,29 +164,25 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None,dividends=False) ticker = ticker.upper() - if iterable(date1): - d1 = (date1[1]-1, date1[2], date1[0]) + d1 = (date1[1] - 1, date1[2], date1[0]) else: - d1 = (date1.month-1, date1.day, date1.year) + d1 = (date1.month - 1, date1.day, date1.year) if iterable(date2): - d2 = (date2[1]-1, date2[2], date2[0]) + d2 = (date2[1] - 1, date2[2], date2[0]) else: - d2 = (date2.month-1, date2.day, date2.year) - + d2 = (date2.month - 1, date2.day, date2.year) if dividends: - g='v' + g = 'v' verbose.report('Retrieving dividends instead of prices') else: - g='d' + g = 'd' urlFmt = 'http://ichart.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv' - - url = urlFmt % (d1[0], d1[1], d1[2], - d2[0], d2[1], d2[2], ticker, g) - + url = urlFmt % (d1[0], d1[1], d1[2], + d2[0], d2[1], d2[2], ticker, g) # Cache the finance data if cachename is supplied, or there is a writable # cache directory. @@ -207,7 +206,7 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None,dividends=False) def quotes_historical_yahoo(ticker, date1, date2, asobject=False, - adjusted=True, cachename=None): + adjusted=True, cachename=None): """ Get historical data for ticker between date1 and date2. date1 and date2 are datetime instances or (year, month, day) sequences. @@ -238,7 +237,7 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, try: ret = parse_yahoo_historical(fh, asobject=asobject, - adjusted=adjusted) + adjusted=adjusted) if len(ret) == 0: return None except IOError as exc: @@ -247,6 +246,7 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, return ret + def plot_day_summary(ax, quotes, ticksize=3, colorup='k', colordown='r', ): @@ -271,36 +271,34 @@ def plot_day_summary(ax, quotes, ticksize=3, t, open, high, low, close = q[:5] - if close>=open : color = colorup - else : color = colordown + if close >= open: + color = colorup + else: + color = colordown - vline = Line2D( - xdata=(t, t), ydata=(low, high), - color=color, - antialiased=False, # no need to antialias vert lines - ) - - oline = Line2D( - xdata=(t, t), ydata=(open, open), - color=color, - antialiased=False, - marker=TICKLEFT, - markersize=ticksize, - ) - - cline = Line2D( - xdata=(t, t), ydata=(close, close), - color=color, - antialiased=False, - markersize=ticksize, - marker=TICKRIGHT) + vline = Line2D(xdata=(t, t), ydata=(low, high), + color=color, + antialiased=False, # no need to antialias vert lines + ) + + oline = Line2D(xdata=(t, t), ydata=(open, open), + color=color, + antialiased=False, + marker=TICKLEFT, + markersize=ticksize, + ) + + cline = Line2D(xdata=(t, t), ydata=(close, close), + color=color, + antialiased=False, + markersize=ticksize, + marker=TICKRIGHT) lines.extend((vline, oline, cline)) ax.add_line(vline) ax.add_line(oline) ax.add_line(cline) - ax.autoscale_view() return lines @@ -333,39 +331,38 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', """ - OFFSET = width/2.0 + OFFSET = width / 2.0 lines = [] patches = [] for q in quotes: t, open, high, low, close = q[:5] - if close>=open : + if close >= open: color = colorup lower = open - height = close-open - else : + height = close - open + else: color = colordown lower = close - height = open-close + height = open - close vline = Line2D( xdata=(t, t), ydata=(low, high), color='k', linewidth=0.5, antialiased=True, - ) + ) rect = Rectangle( - xy = (t-OFFSET, lower), + xy=(t - OFFSET, lower), width = width, height = height, facecolor = color, edgecolor = color, - ) + ) rect.set_alpha(alpha) - lines.append(vline) patches.append(rect) ax.add_line(vline) @@ -377,7 +374,7 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, colorup='k', colordown='r', - ): + ): """ Represent the time, open, close, high, low, as a vertical line @@ -399,12 +396,12 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, "which uses the open-high-low-close order." "This function will be removed in 1.4", mplDeprecation) return plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize, - colorup, colordown) + colorup, colordown) def plot_day_summary_ochl(ax, opens, closes, highs, lows, ticksize=4, - colorup='k', colordown='r', - ): + colorup='k', colordown='r', + ): """ @@ -421,13 +418,12 @@ def plot_day_summary_ochl(ax, opens, closes, highs, lows, ticksize=4, """ return plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize, - colorup, colordown) - + colorup, colordown) def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, - colorup='k', colordown='r', - ): + colorup='k', colordown='r', + ): """ @@ -446,67 +442,65 @@ def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, # note this code assumes if any value open, low, high, close is # missing they all are missing - rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1 ] + rangeSegments = [((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1] # the ticks will be from ticksize to 0 in points at the origin and # we'll translate these to the i, close location - openSegments = [ ((-ticksize, 0), (0, 0)) ] + openSegments = [((-ticksize, 0), (0, 0))] # the ticks will be from 0 to ticksize in points at the origin and # we'll translate these to the i, close location - closeSegments = [ ((0, 0), (ticksize, 0)) ] - + closeSegments = [((0, 0), (ticksize, 0))] - offsetsOpen = [ (i, open) for i, open in zip(xrange(len(opens)), opens) if open != -1 ] + offsetsOpen = [(i, open) for i, open in zip(xrange(len(opens)), opens) if open != -1] - offsetsClose = [ (i, close) for i, close in zip(xrange(len(closes)), closes) if close != -1 ] + offsetsClose = [(i, close) for i, close in zip(xrange(len(closes)), closes) if close != -1] - - scale = ax.figure.dpi * (1.0/72.0) + scale = ax.figure.dpi * (1.0 / 72.0) tickTransform = Affine2D().scale(scale, 0.0) - r,g,b = colorConverter.to_rgb(colorup) - colorup = r,g,b,1 - r,g,b = colorConverter.to_rgb(colordown) - colordown = r,g,b,1 - colord = { True : colorup, - False : colordown, - } - colors = [colord[open=close0] for close0, close1 in zip(closes[:-1], closes[1:]) if close0!=-1 and close1 !=-1] - colors.insert(0,colord[closes[0]>=opens[0]]) - - right = width/2.0 - left = -width/2.0 + colors = [colord[close1 >= close0] + for close0, close1 in zip(closes[:-1], closes[1:]) + if close0 != -1 and close1 != -1] + colors.insert(0, colord[closes[0] >= opens[0]]) + right = width / 2.0 + left = -width / 2.0 - bars = [ ( (left, 0), (left, volume), (right, volume), (right, 0)) for d, open, high, low, close, volume in quotes] + bars = [((left, 0), (left, volume), (right, volume), (right, 0)) + for d, open, high, low, close, volume in quotes] - sx = ax.figure.dpi * (1.0/72.0) # scale for points + sx = ax.figure.dpi * (1.0 / 72.0) # scale for points sy = ax.bbox.height / ax.viewLim.height - barTransform = Affine2D().scale(sx,sy) + barTransform = Affine2D().scale(sx, sy) dates = [d for d, open, high, low, close, volume in quotes] offsetsBars = [(d, 0) for d in dates] @@ -702,20 +705,15 @@ def volume_overlay3(ax, quotes, useAA = 0, # use tuple here lw = 0.5, # and here barCollection = PolyCollection(bars, - facecolors = colors, - edgecolors = ( (0,0,0,1), ), - antialiaseds = useAA, - linewidths = lw, - offsets = offsetsBars, - transOffset = ax.transData, + facecolors=colors, + edgecolors=((0, 0, 0, 1),), + antialiaseds=useAA, + linewidths=lw, + offsets=offsetsBars, + transOffset=ax.transData, ) barCollection.set_transform(barTransform) - - - - - minpy, maxx = (min(dates), max(dates)) miny = 0 maxy = max([volume for d, open, high, low, close, volume in quotes]) @@ -729,6 +727,7 @@ def volume_overlay3(ax, quotes, return barCollection + def index_bar(ax, vals, facecolor='b', edgecolor='l', width=4, alpha=1.0, ): @@ -745,37 +744,32 @@ def index_bar(ax, vals, facecolors = (colorConverter.to_rgba(facecolor, alpha),) edgecolors = (colorConverter.to_rgba(edgecolor, alpha),) - right = width/2.0 - left = -width/2.0 + right = width / 2.0 + left = -width / 2.0 + bars = [((left, 0), (left, v), (right, v), (right, 0)) + for v in vals if v != -1] - bars = [ ( (left, 0), (left, v), (right, v), (right, 0)) for v in vals if v != -1 ] - - sx = ax.figure.dpi * (1.0/72.0) # scale for points + sx = ax.figure.dpi * (1.0 / 72.0) # scale for points sy = ax.bbox.height / ax.viewLim.height - barTransform = Affine2D().scale(sx,sy) + barTransform = Affine2D().scale(sx, sy) - offsetsBars = [ (i, 0) for i,v in enumerate(vals) if v != -1 ] + offsetsBars = [(i, 0) for i, v in enumerate(vals) if v != -1] barCollection = PolyCollection(bars, - facecolors = facecolors, - edgecolors = edgecolors, - antialiaseds = (0,), - linewidths = (0.5,), - offsets = offsetsBars, - transOffset = ax.transData, + facecolors=facecolors, + edgecolors=edgecolors, + antialiaseds=(0,), + linewidths=(0.5,), + offsets=offsetsBars, + transOffset=ax.transData, ) barCollection.set_transform(barTransform) - - - - - minpy, maxx = (0, len(offsetsBars)) miny = 0 - maxy = max([v for v in vals if v!=-1]) + maxy = max([v for v in vals if v != -1]) corners = (minpy, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() From ffb2074ff33c9880cff153e5ec54b9648fafd950 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sat, 11 May 2013 16:13:53 -0500 Subject: [PATCH 04/29] tweaked wording of documentation --- lib/matplotlib/finance.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 7f750ecb2f3e..c1aa1c679463 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -391,7 +391,7 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, warnings.warn("This function has been deprecated in 1.3 in favor" "of `plot_day_summary_ochl`," - "which maintains the natural argument order," + "which maintains the original argument order," "or `plot_day_summary_ohlc`," "which uses the open-high-low-close order." "This function will be removed in 1.4", mplDeprecation) From 35d70d8fcefe0b6f0b475a9274ac62b36f9d57d6 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sat, 11 May 2013 16:17:54 -0500 Subject: [PATCH 05/29] wrapped candlestick2 to have new argument order --- lib/matplotlib/finance.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index c1aa1c679463..dba7237f10c9 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -512,8 +512,33 @@ def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, ax.add_collection(closeCollection) return rangeCollection, openCollection, closeCollection +def candlestick_ochl(ax, opens, closes, highs, lows, width=4, + colorup='k', colordown='r', + alpha=0.75, + ): + """ + + Represent the open, close as a bar line and high low range as a + vertical line. + + Preserves the original argument order. + + ax : an Axes instance to plot to + width : the bar width in points + colorup : the color of the lines where close >= open + colordown : the color of the lines where close < open + alpha : bar transparency + + return value is lineCollection, barCollection + """ + + candlestick_ohlc(ax, opens, closes, highs, lows, width=width, + colorup=colorup, colordown=colordown, + alpha=alpha) + +candlestick2 = candlestick_ochl -def candlestick2(ax, opens, highs, lows, closes, width=4, +def candlestick_ohlc(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75, ): From 4ab6b956b314a8ac4ff07ea850e16a65876107a1 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sat, 11 May 2013 16:26:00 -0500 Subject: [PATCH 06/29] minor documentation tweak --- lib/matplotlib/finance.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index dba7237f10c9..734390aef01d 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -439,7 +439,7 @@ def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, return value is a list of lines added """ - # note this code assumes if any value open, low, high, close is + # note this code assumes if any value open, high, low, close is # missing they all are missing rangeSegments = [((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1] From 4ee6d2eab675bc3d074c6c136b2bae7bfe265c00 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sat, 11 May 2013 16:29:41 -0500 Subject: [PATCH 07/29] added depreciation warning + fixed error is function call argument order --- lib/matplotlib/finance.py | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 734390aef01d..b53f34fd366a 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -532,11 +532,43 @@ def candlestick_ochl(ax, opens, closes, highs, lows, width=4, return value is lineCollection, barCollection """ - candlestick_ohlc(ax, opens, closes, highs, lows, width=width, + candlestick_ohlc(ax, opens, highs, closes, lows, width=width, colorup=colorup, colordown=colordown, alpha=alpha) -candlestick2 = candlestick_ochl + +def candlestick2(ax, opens, closes, highs, lows, width=4, + colorup='k', colordown='r', + alpha=0.75, + ): + """ + + Represent the open, close as a bar line and high low range as a + vertical line. + + Preserves the original argument order. + + ax : an Axes instance to plot to + width : the bar width in points + colorup : the color of the lines where close >= open + colordown : the color of the lines where close < open + alpha : bar transparency + + return value is lineCollection, barCollection + """ + + + warnings.warn("This function has been deprecated in 1.3 in favor" + "of `candlestick_ochl`," + "which maintains the original argument order," + "or `candlestick_ohlc`," + "which uses the open-high-low-close order." + "This function will be removed in 1.4", mplDeprecation) + + + candlestick_ohlc(ax, opens, highs, lows, closes, width=width, + colorup=colorup, colordown=colordown, + alpha=alpha) def candlestick_ohlc(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', From 428333dc80708fe78c93cda39fda09c39456f976 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sun, 12 May 2013 23:51:52 -0500 Subject: [PATCH 08/29] converted all the docstrings numpydoc format --- lib/matplotlib/finance.py | 475 +++++++++++++++++++++++++++----------- 1 file changed, 344 insertions(+), 131 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index b53f34fd366a..026dc8113c3f 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -55,10 +55,12 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): - """ - Parse the historical data in file handle fh from yahoo finance. + """Parse the historical data in file handle fh from yahoo finance. + + Parameters + ---------- - *adjusted* + adjusted : `bool` If True (default) replace open, high, low, close prices with their adjusted values. The adjustment is by a scale factor, S = adjusted_close/close. Adjusted prices are actual prices @@ -70,7 +72,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): = True|False. - *asobject* + asobject : `bool` or :class:`None` If False (default for compatibility with earlier versions) return a list of tuples containing @@ -152,14 +154,29 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, dividends=False Ex: fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31)) - cachename is the name of the local file cache. If None, will - default to the md5 hash or the url (which incorporates the ticker - and date range) - - set dividends=True to return dividends instead of price data. With - this option set, parse functions will not work - - a file handle is returned + Parameters + ---------- + ticker : str + ticker + + date1 : sequence of form (year, month, day), `datetime`, or `date` + start date + date2 : sequence of form (year, month, day), `datetime`, or `date` + end date + + cachename : str + cachename is the name of the local file cache. If None, will + default to the md5 hash or the url (which incorporates the ticker + and date range) + + dividends : `bool` + set dividends=True to return dividends instead of price data. With + this option set, parse functions will not work + + Returns + ------- + file_handle : file handle + a file handle is returned """ ticker = ticker.upper() @@ -207,9 +224,7 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, dividends=False def quotes_historical_yahoo(ticker, date1, date2, asobject=False, adjusted=True, cachename=None): - """ - Get historical data for ticker between date1 and date2. date1 and - date2 are datetime instances or (year, month, day) sequences. + """ Get historical data for ticker between date1 and date2. See :func:`parse_yahoo_historical` for explanation of output formats and the *asobject* and *adjusted* kwargs. @@ -224,9 +239,21 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, x = normpdf(bins, mu, sigma) plot(bins, x, color='red', lw=2) - cachename is the name of the local file cache. If None, will - default to the md5 hash or the url (which incorporates the ticker - and date range) + Parameters + ---------- + ticker : str + stock ticker + + date1 : sequence of form (year, month, day), `datetime`, or `date` + start date + + date2 : sequence of form (year, month, day), `datetime`, or `date` + end date + + cachename : str or `None` + is the name of the local file cache. If None, will + default to the md5 hash or the url (which incorporates the ticker + and date range) """ # Maybe enable a warning later as part of a slow transition # to using None instead of False. @@ -250,20 +277,30 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, def plot_day_summary(ax, quotes, ticksize=3, colorup='k', colordown='r', ): - """ - quotes is a sequence of (time, open, high, low, close, ...) sequences - - Represent the time, open, high, low, close as a vertical line - ranging from low to high. The left tick is the open and the right - tick is the close. - - time must be in float date format - see date2num - - ax : an Axes instance to plot to - ticksize : open/close tick marker in points - colorup : the color of the lines where close >= open - colordown : the color of the lines where close < open - return value is a list of lines added + """Plots day summary + + Represent the time, open, high, low, close as a vertical line + ranging from low to high. The left tick is the open and the right + tick is the close. + + + Parameters + ---------- + ax : `Axes` + an `Axes` instance to plot to + quotes : sequence of (time, open, high, low, close, ...) sequences + data to plot. time must be in float date format - see date2num + ticksize : int + open/close tick marker in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + + Returns + ------- + lines : list + list of lines added """ lines = [] @@ -309,25 +346,35 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', """ - quotes is a sequence of (time, open, high, low, close, ...) sequences. - As long as the first 5 elements are these values, - the record can be as long as you want (eg it may store volume). - - time must be in float days format - see date2num - Plot the time, open, high, low, close as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, otherwise use colordown - ax : an Axes instance to plot to - width : fraction of a day for the rectangle width - colorup : the color of the rectangle where close >= open - colordown : the color of the rectangle where close < open - alpha : the rectangle alpha level - - return value is lines, patches where lines is a list of lines - added and patches is a list of the rectangle patches added + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + quotes : sequence of (time, open, high, low, close, ...) sequences + As long as the first 5 elements are these values, + the record can be as long as you want (eg it may store volume). + + time must be in float days format - see date2num + + width : float + fraction of a day for the rectangle width + colorup : color + the color of the rectangle where close >= open + colordown : color + the color of the rectangle where close < open + alpha : float + the rectangle alpha level + + Returns + ------- + ret : tuple + returns (lines, patches) where lines is a list of lines + added and patches is a list of the rectangle patches added """ @@ -375,18 +422,40 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, colorup='k', colordown='r', ): - """ - - Represent the time, open, close, high, low, as a vertical line + """Represent the time, open, close, high, low, as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. - ax : an Axes instance to plot to - ticksize : size of open and close ticks in points - colorup : the color of the lines where close >= open - colordown : the color of the lines where close < open - return value is a list of lines added + This function has been deprecated in 1.3 in favor of + `plot_day_summary_ochl`, which maintains the original argument + order, or `plot_day_summary_ohlc`, which uses the + open-high-low-close order. This function will be removed in 1.4 + + + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + opens : sequence + sequence of opening values + closes : sequence + sequence of closing values + highs : sequence + sequence of high values + lows : sequence + sequence of low values + ticksize : int + size of open and close ticks in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + + Returns + ------- + ret : list + a list of lines added to the axes """ warnings.warn("This function has been deprecated in 1.3 in favor" @@ -403,18 +472,33 @@ def plot_day_summary_ochl(ax, opens, closes, highs, lows, ticksize=4, colorup='k', colordown='r', ): - """ - - Represent the time, open, close, high, low, as a vertical line + """Represent the time, open, close, high, low, as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. - ax : an Axes instance to plot to - ticksize : size of open and close ticks in points - colorup : the color of the lines where close >= open - colordown : the color of the lines where close < open - - return value is a list of lines added + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + opens : sequence + sequence of opening values + closes : sequence + sequence of closing values + highs : sequence + sequence of high values + lows : sequence + sequence of low values + ticksize : int + size of open and close ticks in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + + Returns + ------- + ret : list + a list of lines added to the axes """ return plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize, @@ -425,20 +509,36 @@ def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, colorup='k', colordown='r', ): - """ - - Represent the time, open, high, low, close as a vertical line + """Represent the time, open, high, low, close as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. - ax : an Axes instance to plot to - ticksize : size of open and close ticks in points - colorup : the color of the lines where close >= open - colordown : the color of the lines where close < open - - return value is a list of lines added + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + opens : sequence + sequence of opening values + highs : sequence + sequence of high values + lows : sequence + sequence of low values + closes : sequence + sequence of closing values + ticksize : int + size of open and close ticks in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + + Returns + ------- + ret : list + a list of lines added to the axes """ + # note this code assumes if any value open, high, low, close is # missing they all are missing @@ -516,20 +616,37 @@ def candlestick_ochl(ax, opens, closes, highs, lows, width=4, colorup='k', colordown='r', alpha=0.75, ): - """ - - Represent the open, close as a bar line and high low range as a + """Represent the open, close as a bar line and high low range as a vertical line. Preserves the original argument order. - ax : an Axes instance to plot to - width : the bar width in points - colorup : the color of the lines where close >= open - colordown : the color of the lines where close < open - alpha : bar transparency - return value is lineCollection, barCollection + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + opens : sequence + sequence of opening values + closes : sequence + sequence of closing values + highs : sequence + sequence of high values + lows : sequence + sequence of low values + ticksize : int + size of open and close ticks in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + alpha : float + bar transparency + + Returns + ------- + ret : tuple + (lineCollection, barCollection) """ candlestick_ohlc(ax, opens, highs, closes, lows, width=width, @@ -541,20 +658,40 @@ def candlestick2(ax, opens, closes, highs, lows, width=4, colorup='k', colordown='r', alpha=0.75, ): - """ - - Represent the open, close as a bar line and high low range as a + """Represent the open, close as a bar line and high low range as a vertical line. - Preserves the original argument order. - - ax : an Axes instance to plot to - width : the bar width in points - colorup : the color of the lines where close >= open - colordown : the color of the lines where close < open - alpha : bar transparency - - return value is lineCollection, barCollection + This function has been deprecated in 1.3 in favor of + `candlestick_ochl`, which maintains the original argument order, + or `candlestick_ohlc`, which uses the open-high-low-close order. + This function will be removed in 1.4 + + + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + opens : sequence + sequence of opening values + closes : sequence + sequence of closing values + highs : sequence + sequence of high values + lows : sequence + sequence of low values + ticksize : int + size of open and close ticks in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + alpha : float + bar transparency + + Returns + ------- + ret : tuple + (lineCollection, barCollection) """ @@ -574,19 +711,35 @@ def candlestick_ohlc(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75, ): - """ - - Represent the open, close as a bar line and high low range as a + """Represent the open, close as a bar line and high low range as a vertical line. - ax : an Axes instance to plot to - width : the bar width in points - colorup : the color of the lines where close >= open - colordown : the color of the lines where close < open - alpha : bar transparency - - return value is lineCollection, barCollection + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + opens : sequence + sequence of opening values + closes : sequence + sequence of closing values + highs : sequence + sequence of high values + lows : sequence + sequence of low values + ticksize : int + size of open and close ticks in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + alpha : float + bar transparency + + Returns + ------- + ret : tuple + (lineCollection, barCollection) """ # note this code assumes if any value open, low, high, close is @@ -646,17 +799,33 @@ def candlestick_ohlc(ax, opens, highs, lows, closes, width=4, def volume_overlay(ax, opens, closes, volumes, colorup='k', colordown='r', width=4, alpha=1.0): - """ - Add a volume overlay to the current axes. The opens and closes + """Add a volume overlay to the current axes. The opens and closes are used to determine the color of the bar. -1 is missing. If a value is missing on one it must be missing on all - ax : an Axes instance to plot to - width : the bar width in points - colorup : the color of the lines where close >= open - colordown : the color of the lines where close < open - alpha : bar transparency - + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + opens : sequence + a sequence of opens + closes : sequence + a sequence of closes + volumes : sequence + a sequence of volumes + width : int + the bar width in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + alpha : float + bar transparency + + Returns + ------- + ret : `barCollection` + The `barrCollection` added to the axes """ @@ -700,15 +869,32 @@ def volume_overlay2(ax, closes, volumes, determine the color of the bar. -1 is missing. If a value is missing on one it must be missing on all - ax : an Axes instance to plot to - width : the bar width in points - colorup : the color of the lines where close >= open - colordown : the color of the lines where close < open - alpha : bar transparency - nb: first point is not displayed - it is used only for choosing the right color + + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + closes : sequence + a sequence of closes + volumes : sequence + a sequence of volumes + width : int + the bar width in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + alpha : float + bar transparency + + Returns + ------- + ret : `barCollection` + The `barrCollection` added to the axes + """ return volume_overlay(ax, closes[:-1], closes[1:], volumes[1:], colorup, colordown, width, alpha) @@ -717,16 +903,29 @@ def volume_overlay2(ax, closes, volumes, def volume_overlay3(ax, quotes, colorup='k', colordown='r', width=4, alpha=1.0): - """ - Add a volume overlay to the current axes. quotes is a list of (d, + """Add a volume overlay to the current axes. quotes is a list of (d, open, high, low, close, volume) and close-open is used to determine the color of the bar - kwarg - width : the bar width in points - colorup : the color of the lines where close1 >= close0 - colordown : the color of the lines where close1 < close0 - alpha : bar transparency + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + quotes : sequence of (time, open, high, low, close, ...) sequences + data to plot. time must be in float date format - see date2num + width : int + the bar width in points + colorup : color + the color of the lines where close1 >= close0 + colordown : color + the color of the lines where close1 < close0 + alpha : float + bar transparency + + Returns + ------- + ret : `barCollection` + The `barrCollection` added to the axes """ @@ -788,13 +987,27 @@ def volume_overlay3(ax, quotes, def index_bar(ax, vals, facecolor='b', edgecolor='l', width=4, alpha=1.0, ): - """ - Add a bar collection graph with height vals (-1 is missing). - - ax : an Axes instance to plot to - width : the bar width in points - alpha : bar transparency - + """Add a bar collection graph with height vals (-1 is missing). + + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + vals : sequence + a sequence of values + facecolor : color + the color of the bar face + edgecolor : color + the color of the bar edges + width : int + the bar width in points + alpha : float + bar transparency + + Returns + ------- + ret : `barCollection` + The `barrCollection` added to the axes """ From e509cd2417d531ec335a5292e2e7d9cc1ca72f18 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 22:18:47 -0500 Subject: [PATCH 09/29] wrapped and depreciated parse_yahoo_historical fixed bug in original patch --- lib/matplotlib/finance.py | 165 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 157 insertions(+), 8 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 026dc8113c3f..1fe374e0ff91 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -41,7 +41,7 @@ cachedir = None -stock_dt = np.dtype([('date', object), +stock_dt_ohlc = np.dtype([('date', object), ('year', np.int16), ('month', np.int8), ('day', np.int8), @@ -54,9 +54,144 @@ ('aclose', np.float)]) -def parse_yahoo_historical(fh, adjusted=True, asobject=False): +stock_dt_ochl = np.dtype([('date', object), + ('year', np.int16), + ('month', np.int8), + ('day', np.int8), + ('d', np.float), # mpl datenum + ('open', np.float), + ('close', np.float), + ('high', np.float), + ('low', np.float), + ('volume', np.float), + ('aclose', np.float)]) + + +def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): + """Parse the historical data in file handle fh from yahoo finance. + + + This function has been deprecated in 1.4 in favor of + `parse_yahoo_historical_ochl`, which maintains the original argument + order, or `parse_yahoo_historical_ohlc`, which uses the + open-high-low-close order. This function will be removed in 1.5 + + + Parameters + ---------- + + adjusted : `bool` + If True (default) replace open, high, low, close prices with + their adjusted values. The adjustment is by a scale factor, S = + adjusted_close/close. Adjusted prices are actual prices + multiplied by S. + + Volume is not adjusted as it is already backward split adjusted + by Yahoo. If you want to compute dollars traded, multiply volume + by the adjusted close, regardless of whether you choose adjusted + = True|False. + + + asobject : `bool` or :class:`None` + If False (default for compatibility with earlier versions) + return a list of tuples containing + + d, open, close, high, low, volume + + If None (preferred alternative to False), return + a 2-D ndarray corresponding to the list of tuples. + + Otherwise return a numpy recarray with + + date, year, month, day, d, open, close, high, low, + volume, adjusted_close + + where d is a floating poing representation of date, + as returned by date2num, and date is a python standard + library datetime.date instance. + + The name of this kwarg is a historical artifact. Formerly, + True returned a cbook Bunch + holding 1-D ndarrays. The behavior of a numpy recarray is + very similar to the Bunch. + + stock_dt : `np.dtype` + The data type to be used for the returned array. This is a + temporary argument to easy the transition from ochl -> ohlc + + """ + parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, + oclh=True) + + +def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): """Parse the historical data in file handle fh from yahoo finance. + + This function has been deprecated in 1.4 in favor of + `parse_yahoo_historical_ochl`, which maintains the original argument + order, or `parse_yahoo_historical_ohlc`, which uses the + open-high-low-close order. This function will be removed in 1.5 + + + Parameters + ---------- + + adjusted : `bool` + If True (default) replace open, high, low, close prices with + their adjusted values. The adjustment is by a scale factor, S = + adjusted_close/close. Adjusted prices are actual prices + multiplied by S. + + Volume is not adjusted as it is already backward split adjusted + by Yahoo. If you want to compute dollars traded, multiply volume + by the adjusted close, regardless of whether you choose adjusted + = True|False. + + + asobject : `bool` or :class:`None` + If False (default for compatibility with earlier versions) + return a list of tuples containing + + d, open, high, low, close, volume + + If None (preferred alternative to False), return + a 2-D ndarray corresponding to the list of tuples. + + Otherwise return a numpy recarray with + + date, year, month, day, d, open, high, low, close, + volume, adjusted_close + + where d is a floating poing representation of date, + as returned by date2num, and date is a python standard + library datetime.date instance. + + The name of this kwarg is a historical artifact. Formerly, + True returned a cbook Bunch + holding 1-D ndarrays. The behavior of a numpy recarray is + very similar to the Bunch. + + stock_dt : `np.dtype` + The data type to be used for the returned array. This is a + temporary argument to easy the transition from ochl -> ohlc + + """ + parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, + ochl=False) + + +def parse_yahoo_historical(fh, adjusted=True, asobject=False, + ochl=True): + """Parse the historical data in file handle fh from yahoo finance. + + + This function has been deprecated in 1.4 in favor of + `parse_yahoo_historical_ochl`, which maintains the original argument + order, or `parse_yahoo_historical_ohlc`, which uses the + open-high-low-close order. This function will be removed in 1.5 + + Parameters ---------- @@ -95,7 +230,15 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): holding 1-D ndarrays. The behavior of a numpy recarray is very similar to the Bunch. + stock_dt : `np.dtype` + The data type to be used for the returned array. This is a + temporary argument to easy the transition from ochl -> ohlc + """ + if ochl: + stock_dt = stock_dt_ochl + else: + stock_dt = stock_dt_ohlc lines = fh.readlines() @@ -134,10 +277,16 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): # 2-D sequence; formerly list of tuples, now ndarray ret = np.zeros((len(d), 6), dtype=np.float) ret[:, 0] = d['d'] - ret[:, 1] = d['open'] - ret[:, 3] = d['high'] - ret[:, 4] = d['low'] - ret[:, 2] = d['close'] + if ochl: + ret[:, 1] = d['open'] + ret[:, 2] = d['close'] + ret[:, 3] = d['high'] + ret[:, 4] = d['low'] + else: + ret[:, 1] = d['open'] + ret[:, 2] = d['high'] + ret[:, 3] = d['low'] + ret[:, 4] = d['close'] ret[:, 5] = d['volume'] if asobject is None: return ret @@ -427,10 +576,10 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, tick is the close. - This function has been deprecated in 1.3 in favor of + This function has been deprecated in 1.4 in favor of `plot_day_summary_ochl`, which maintains the original argument order, or `plot_day_summary_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.4 + open-high-low-close order. This function will be removed in 1.5 Parameters From 9c5e1c3146fdbed9e5fb1963988531ed56af1ffe Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 22:19:46 -0500 Subject: [PATCH 10/29] commented out unused line --- lib/matplotlib/finance.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 1fe374e0ff91..c0958768caea 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -244,7 +244,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False, results = [] - datefmt = '%Y-%m-%d' + # datefmt = '%Y-%m-%d' for line in lines[1:]: From ca8845e239b615c1e5c9741ad4e91c0b3f4268a8 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 22:23:51 -0500 Subject: [PATCH 11/29] fixed pep8, updated depreciation messages because this missed 1.3 --- lib/matplotlib/finance.py | 49 ++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index c0958768caea..2042eb16ecb3 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -295,7 +295,9 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False, return d.view(np.recarray) # Close enough to former Bunch return -def fetch_historical_yahoo(ticker, date1, date2, cachename=None, dividends=False): +def fetch_historical_yahoo(ticker, date1, date2, cachename=None, + dividends=False, + ochl=True): """ Fetch historical data for ticker between date1 and date2. date1 and date2 are date or datetime instances, or (year, month, day) sequences. @@ -357,13 +359,15 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, dividends=False if cachename is not None: if os.path.exists(cachename): fh = open(cachename) - verbose.report('Using cachefile %s for %s'%(cachename, ticker)) + verbose.report('Using cachefile %s for ' + '%s' % (cachename, ticker)) else: mkdirs(os.path.abspath(os.path.dirname(cachename))) with contextlib.closing(urlopen(url)) as urlfh: with open(cachename, 'wb') as fh: fh.write(urlfh.read()) - verbose.report('Saved %s data to cache file %s'%(ticker, cachename)) + verbose.report('Saved %s data to cache file ' + '%s' % (ticker, cachename)) fh = open(cachename, 'r') return fh @@ -417,7 +421,7 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, if len(ret) == 0: return None except IOError as exc: - warnings.warn('fh failure\n%s'%(exc.strerror[1])) + warnings.warn('fh failure\n%s' % (exc.strerror[1])) return None return ret @@ -607,12 +611,12 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, a list of lines added to the axes """ - warnings.warn("This function has been deprecated in 1.3 in favor" + warnings.warn("This function has been deprecated in 1.4 in favor" "of `plot_day_summary_ochl`," "which maintains the original argument order," "or `plot_day_summary_ohlc`," "which uses the open-high-low-close order." - "This function will be removed in 1.4", mplDeprecation) + "This function will be removed in 1.5", mplDeprecation) return plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize, colorup, colordown) @@ -691,7 +695,8 @@ def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, # note this code assumes if any value open, high, low, close is # missing they all are missing - rangeSegments = [((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1] + rangeSegments = [((i, low), (i, high)) for i, low, high in + zip(xrange(len(lows)), lows, highs) if low != -1] # the ticks will be from ticksize to 0 in points at the origin and # we'll translate these to the i, close location @@ -701,9 +706,11 @@ def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, # we'll translate these to the i, close location closeSegments = [((0, 0), (ticksize, 0))] - offsetsOpen = [(i, open) for i, open in zip(xrange(len(opens)), opens) if open != -1] + offsetsOpen = [(i, open) for i, open in + zip(xrange(len(opens)), opens) if open != -1] - offsetsClose = [(i, close) for i, close in zip(xrange(len(closes)), closes) if close != -1] + offsetsClose = [(i, close) for i, close in + zip(xrange(len(closes)), closes) if close != -1] scale = ax.figure.dpi * (1.0 / 72.0) @@ -716,7 +723,8 @@ def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, colord = {True: colorup, False: colordown, } - colors = [colord[open < close] for open, close in zip(opens, closes) if open != -1 and close != -1] + colors = [colord[open < close] for open, close in + zip(opens, closes) if open != -1 and close != -1] assert(len(rangeSegments) == len(offsetsOpen)) assert(len(offsetsOpen) == len(offsetsClose)) @@ -761,6 +769,7 @@ def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, ax.add_collection(closeCollection) return rangeCollection, openCollection, closeCollection + def candlestick_ochl(ax, opens, closes, highs, lows, width=4, colorup='k', colordown='r', alpha=0.75, @@ -810,10 +819,10 @@ def candlestick2(ax, opens, closes, highs, lows, width=4, """Represent the open, close as a bar line and high low range as a vertical line. - This function has been deprecated in 1.3 in favor of + This function has been deprecated in 1.4 in favor of `candlestick_ochl`, which maintains the original argument order, or `candlestick_ohlc`, which uses the open-high-low-close order. - This function will be removed in 1.4 + This function will be removed in 1.5 Parameters @@ -842,20 +851,18 @@ def candlestick2(ax, opens, closes, highs, lows, width=4, ret : tuple (lineCollection, barCollection) """ - - - warnings.warn("This function has been deprecated in 1.3 in favor" + warnings.warn("This function has been deprecated in 1.4 in favor" "of `candlestick_ochl`," "which maintains the original argument order," "or `candlestick_ohlc`," "which uses the open-high-low-close order." - "This function will be removed in 1.4", mplDeprecation) - + "This function will be removed in 1.5", mplDeprecation) candlestick_ohlc(ax, opens, highs, lows, closes, width=width, colorup=colorup, colordown=colordown, alpha=alpha) + def candlestick_ohlc(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75, @@ -895,7 +902,10 @@ def candlestick_ohlc(ax, opens, highs, lows, closes, width=4, # missing they all are missing delta = width / 2. - barVerts = [((i - delta, open), (i - delta, close), (i + delta, close), (i + delta, open)) + barVerts = [((i - delta, open), + (i - delta, close), + (i + delta, close), + (i + delta, open)) for i, open, close in zip(xrange(len(opens)), opens, closes) if open != -1 and close != -1] @@ -1046,7 +1056,8 @@ def volume_overlay2(ax, closes, volumes, """ - return volume_overlay(ax, closes[:-1], closes[1:], volumes[1:], colorup, colordown, width, alpha) + return volume_overlay(ax, closes[:-1], closes[1:], volumes[1:], + colorup, colordown, width, alpha) def volume_overlay3(ax, quotes, From 45eea6e191f91fe7abf755b643cc363a9e368ee7 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 22:24:27 -0500 Subject: [PATCH 12/29] fixed documentation --- lib/matplotlib/finance.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 2042eb16ecb3..5e1289f9da15 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -115,10 +115,6 @@ def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): holding 1-D ndarrays. The behavior of a numpy recarray is very similar to the Bunch. - stock_dt : `np.dtype` - The data type to be used for the returned array. This is a - temporary argument to easy the transition from ochl -> ohlc - """ parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, oclh=True) @@ -171,11 +167,6 @@ def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): True returned a cbook Bunch holding 1-D ndarrays. The behavior of a numpy recarray is very similar to the Bunch. - - stock_dt : `np.dtype` - The data type to be used for the returned array. This is a - temporary argument to easy the transition from ochl -> ohlc - """ parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, ochl=False) From 10adeb2b53e1337875f1a96ff209f08d8dc2fe29 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 22:37:45 -0500 Subject: [PATCH 13/29] wrapped and deprecated plot_day_summary fixed naming on plot_day_summary2_* --- lib/matplotlib/finance.py | 96 +++++++++++++++++++++++++++++++++++---- 1 file changed, 86 insertions(+), 10 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 5e1289f9da15..38243ec7a48e 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -418,16 +418,51 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, return ret -def plot_day_summary(ax, quotes, ticksize=3, +def plot_day_summary_oclh(ax, quotes, ticksize=3, colorup='k', colordown='r', ): """Plots day summary + Represent the time, open, close, high, low as a vertical line + ranging from low to high. The left tick is the open and the right + tick is the close. + + + + Parameters + ---------- + ax : `Axes` + an `Axes` instance to plot to + quotes : sequence of (time, open, close, high, low, ...) sequences + data to plot. time must be in float date format - see date2num + ticksize : int + open/close tick marker in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + + Returns + ------- + lines : list + list of tuples of the lines added (one tuple per quote) + """ + plot_day_summary(ax, quotes, ticksize=ticksize, + colorup=colorup, colordown=colordown, + ochl=True) + + +def plot_day_summary_ohlc(ax, quotes, ticksize=3, + colorup='k', colordown='r', + ): + """Plots day summary + Represent the time, open, high, low, close as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. + Parameters ---------- ax : `Axes` @@ -444,13 +479,56 @@ def plot_day_summary(ax, quotes, ticksize=3, Returns ------- lines : list - list of lines added + list of tuples of the lines added (one tuple per quote) """ + plot_day_summary(ax, quotes, ticksize=ticksize, + colorup=colorup, colordown=colordown, + ochl=False) + + +def plot_day_summary(ax, quotes, ticksize=3, + colorup='k', colordown='r', + ochl=True + ): + """Plots day summary + This function has been deprecated in 1.4 in favor of + `plot_day_summary_ochl`, which maintains the original argument + order, or `plot_day_summary_ohlc`, which uses the + open-high-low-close order. This function will be removed in 1.5 + + + Represent the time, open, high, low, close as a vertical line + ranging from low to high. The left tick is the open and the right + tick is the close. + + + + Parameters + ---------- + ax : `Axes` + an `Axes` instance to plot to + quotes : sequence of (time, open, high, low, close, ...) sequences + data to plot. time must be in float date format - see date2num + ticksize : int + open/close tick marker in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + + Returns + ------- + lines : list + list of tuples of the lines added (one tuple per quote) + """ + # unfortunately this has a different return type than plot_day_summary2_* lines = [] for q in quotes: - - t, open, high, low, close = q[:5] + if ochl: + t, open, close, high, low = q[:5] + else: + t, open, high, low, close = q[:5] if close >= open: color = colorup @@ -572,8 +650,8 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, This function has been deprecated in 1.4 in favor of - `plot_day_summary_ochl`, which maintains the original argument - order, or `plot_day_summary_ohlc`, which uses the + `plot_day_summary2_ochl`, which maintains the original argument + order, or `plot_day_summary2_ohlc`, which uses the open-high-low-close order. This function will be removed in 1.5 @@ -612,7 +690,7 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, colorup, colordown) -def plot_day_summary_ochl(ax, opens, closes, highs, lows, ticksize=4, +def plot_day_summary2_ochl(ax, opens, closes, highs, lows, ticksize=4, colorup='k', colordown='r', ): @@ -649,7 +727,7 @@ def plot_day_summary_ochl(ax, opens, closes, highs, lows, ticksize=4, colorup, colordown) -def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, +def plot_day_summary2_ohlc(ax, opens, highs, lows, closes, ticksize=4, colorup='k', colordown='r', ): @@ -681,8 +759,6 @@ def plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize=4, ret : list a list of lines added to the axes """ - - # note this code assumes if any value open, high, low, close is # missing they all are missing From 96b859f9472540967ebb5c425b8ba88ab6319853 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 22:46:45 -0500 Subject: [PATCH 14/29] fixed documentation wrapped candlestick --- lib/matplotlib/finance.py | 100 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 95 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 38243ec7a48e..dfd478fd8cd6 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -221,9 +221,9 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False, holding 1-D ndarrays. The behavior of a numpy recarray is very similar to the Bunch. - stock_dt : `np.dtype` - The data type to be used for the returned array. This is a - temporary argument to easy the transition from ochl -> ohlc + ochl : `bool` + Temporary argument to select between ochl and ohlc ordering. + Defaults to True to preserve original functionality. """ if ochl: @@ -516,6 +516,8 @@ def plot_day_summary(ax, quotes, ticksize=3, the color of the lines where close >= open colordown : color the color of the lines where close < open + ochl: bool + temporary argument to select between ochl and ohlc ordering Returns ------- @@ -563,11 +565,49 @@ def plot_day_summary(ax, quotes, ticksize=3, return lines -def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', +def candlestick_ochl(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0): """ + Plot the time, open, close, high, low as a vertical line ranging + from low to high. Use a rectangular bar to represent the + open-close span. If close >= open, use colorup to color the bar, + otherwise use colordown + + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + quotes : sequence of (time, open, high, low, close, ...) sequences + As long as the first 5 elements are these values, + the record can be as long as you want (eg it may store volume). + + time must be in float days format - see date2num + + width : float + fraction of a day for the rectangle width + colorup : color + the color of the rectangle where close >= open + colordown : color + the color of the rectangle where close < open + alpha : float + the rectangle alpha level + + Returns + ------- + ret : tuple + returns (lines, patches) where lines is a list of lines + added and patches is a list of the rectangle patches added + + """ + candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, + alpha=alpha, ochl=True) + +def candlestick_ohlc(ax, quotes, width=0.2, colorup='k', colordown='r', + alpha=1.0): + + """ Plot the time, open, high, low, close as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, @@ -598,6 +638,53 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', returns (lines, patches) where lines is a list of lines added and patches is a list of the rectangle patches added + """ + candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, + alpha=alpha, ochl=False) + + +def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', + alpha=1.0, ochl=True): + + """ + + This function has been deprecated in 1.4 in favor of + `candlestick_ochl`, which maintains the original argument + order, or `candlestick_ohlc`, which uses the + open-high-low-close order. This function will be removed in 1.5 + + Plot the time, open, high, low, close as a vertical line ranging + from low to high. Use a rectangular bar to represent the + open-close span. If close >= open, use colorup to color the bar, + otherwise use colordown + + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + quotes : sequence of (time, open, high, low, close, ...) sequences + As long as the first 5 elements are these values, + the record can be as long as you want (eg it may store volume). + + time must be in float days format - see date2num + + width : float + fraction of a day for the rectangle width + colorup : color + the color of the rectangle where close >= open + colordown : color + the color of the rectangle where close < open + alpha : float + the rectangle alpha level + ochl: bool + temporary argument to select between ochl and ohlc ordering + + Returns + ------- + ret : tuple + returns (lines, patches) where lines is a list of lines + added and patches is a list of the rectangle patches added + """ OFFSET = width / 2.0 @@ -605,7 +692,10 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', lines = [] patches = [] for q in quotes: - t, open, high, low, close = q[:5] + if ochl: + t, open, close, high, low = q[:5] + else: + t, open, high, low, close = q[:5] if close >= open: color = colorup From f4dcc2f31ae69015b5f00505e1201889db48931f Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 23:07:35 -0500 Subject: [PATCH 15/29] re-factored to actually raise depreciation warnings --- lib/matplotlib/finance.py | 223 ++++++++++++++++++++++++++++++-------- 1 file changed, 180 insertions(+), 43 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index dfd478fd8cd6..9ffa036aee3b 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -66,17 +66,17 @@ ('volume', np.float), ('aclose', np.float)]) +_warn_str = ("This function has been deprecated in 1.4 in favor " + "of `{fun}_ochl`, " + "which maintains the original argument order, " + "or `{fun}_ohlc`, " + "which uses the open-high-low-close order. " + "This function will be removed in 1.5") + def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): """Parse the historical data in file handle fh from yahoo finance. - - This function has been deprecated in 1.4 in favor of - `parse_yahoo_historical_ochl`, which maintains the original argument - order, or `parse_yahoo_historical_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.5 - - Parameters ---------- @@ -116,12 +116,56 @@ def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): very similar to the Bunch. """ - parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, + _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, oclh=True) def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): """Parse the historical data in file handle fh from yahoo finance. + Parameters + ---------- + + adjusted : `bool` + If True (default) replace open, high, low, close prices with + their adjusted values. The adjustment is by a scale factor, S = + adjusted_close/close. Adjusted prices are actual prices + multiplied by S. + + Volume is not adjusted as it is already backward split adjusted + by Yahoo. If you want to compute dollars traded, multiply volume + by the adjusted close, regardless of whether you choose adjusted + = True|False. + + + asobject : `bool` or :class:`None` + If False (default for compatibility with earlier versions) + return a list of tuples containing + + d, open, high, low, close, volume + + If None (preferred alternative to False), return + a 2-D ndarray corresponding to the list of tuples. + + Otherwise return a numpy recarray with + + date, year, month, day, d, open, high, low, close, + volume, adjusted_close + + where d is a floating poing representation of date, + as returned by date2num, and date is a python standard + library datetime.date instance. + + The name of this kwarg is a historical artifact. Formerly, + True returned a cbook Bunch + holding 1-D ndarrays. The behavior of a numpy recarray is + very similar to the Bunch. + """ + _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, + ochl=False) + + +def parse_yahoo_historical(fh, adjusted=True, asobject=False): + """Parse the historical data in file handle fh from yahoo finance. This function has been deprecated in 1.4 in favor of @@ -156,7 +200,7 @@ def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): Otherwise return a numpy recarray with - date, year, month, day, d, open, high, low, close, + date, year, month, day, d, open, high, low, close, volume, adjusted_close where d is a floating poing representation of date, @@ -167,12 +211,20 @@ def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): True returned a cbook Bunch holding 1-D ndarrays. The behavior of a numpy recarray is very similar to the Bunch. + + ochl : `bool` + Temporary argument to select between ochl and ohlc ordering. + Defaults to True to preserve original functionality. + """ - parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, - ochl=False) + warnings.warn(_warn_str.format(fun='parse_yahoo_historical'), + mplDeprecation) + + _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, + oclh=True) -def parse_yahoo_historical(fh, adjusted=True, asobject=False, +def _parse_yahoo_historical(fh, adjusted=True, asobject=False, ochl=True): """Parse the historical data in file handle fh from yahoo finance. @@ -287,8 +339,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False, def fetch_historical_yahoo(ticker, date1, date2, cachename=None, - dividends=False, - ochl=True): + dividends=False): """ Fetch historical data for ticker between date1 and date2. date1 and date2 are date or datetime instances, or (year, month, day) sequences. @@ -366,8 +417,9 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, return urlopen(url) -def quotes_historical_yahoo(ticker, date1, date2, asobject=False, - adjusted=True, cachename=None): +def _quotes_historical_yahoo(ticker, date1, date2, asobject=False, + adjusted=True, cachename=None, + ochl=True): """ Get historical data for ticker between date1 and date2. See :func:`parse_yahoo_historical` for explanation of output formats @@ -398,6 +450,11 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, is the name of the local file cache. If None, will default to the md5 hash or the url (which incorporates the ticker and date range) + + ochl: bool + temporary argument to select between ochl and ohlc ordering + + """ # Maybe enable a warning later as part of a slow transition # to using None instead of False. @@ -408,7 +465,7 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, try: ret = parse_yahoo_historical(fh, asobject=asobject, - adjusted=adjusted) + adjusted=adjusted, ochl=ochl) if len(ret) == 0: return None except IOError as exc: @@ -418,6 +475,48 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, return ret +def plot_day_summary(ax, quotes, ticksize=3, + colorup='k', colordown='r', + ): + """Plots day summary + + Represent the time, open, close, high, low as a vertical line + ranging from low to high. The left tick is the open and the right + tick is the close. + + + This function has been deprecated in 1.4 in favor of + `plot_day_summary_ochl`, which maintains the original argument + order, or `plot_day_summary_ohlc`, which uses the + open-high-low-close order. This function will be removed in 1.5 + + + Parameters + ---------- + ax : `Axes` + an `Axes` instance to plot to + quotes : sequence of (time, open, close, high, low, ...) sequences + data to plot. time must be in float date format - see date2num + ticksize : int + open/close tick marker in points + colorup : color + the color of the lines where close >= open + colordown : color + the color of the lines where close < open + + Returns + ------- + lines : list + list of tuples of the lines added (one tuple per quote) + """ + warnings.warn(_warn_str.format(fun='plot_day_summary'), + mplDeprecation) + + _plot_day_summary(ax, quotes, ticksize=ticksize, + colorup=colorup, colordown=colordown, + ochl=True) + + def plot_day_summary_oclh(ax, quotes, ticksize=3, colorup='k', colordown='r', ): @@ -447,7 +546,7 @@ def plot_day_summary_oclh(ax, quotes, ticksize=3, lines : list list of tuples of the lines added (one tuple per quote) """ - plot_day_summary(ax, quotes, ticksize=ticksize, + _plot_day_summary(ax, quotes, ticksize=ticksize, colorup=colorup, colordown=colordown, ochl=True) @@ -481,22 +580,17 @@ def plot_day_summary_ohlc(ax, quotes, ticksize=3, lines : list list of tuples of the lines added (one tuple per quote) """ - plot_day_summary(ax, quotes, ticksize=ticksize, + _plot_day_summary(ax, quotes, ticksize=ticksize, colorup=colorup, colordown=colordown, ochl=False) -def plot_day_summary(ax, quotes, ticksize=3, +def _plot_day_summary(ax, quotes, ticksize=3, colorup='k', colordown='r', ochl=True ): """Plots day summary - This function has been deprecated in 1.4 in favor of - `plot_day_summary_ochl`, which maintains the original argument - order, or `plot_day_summary_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.5 - Represent the time, open, high, low, close as a vertical line ranging from low to high. The left tick is the open and the right @@ -565,6 +659,55 @@ def plot_day_summary(ax, quotes, ticksize=3, return lines +def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', + alpha=1.0): + + """ + Plot the time, open, close, high, low as a vertical line ranging + from low to high. Use a rectangular bar to represent the + open-close span. If close >= open, use colorup to color the bar, + otherwise use colordown + + + This function has been deprecated in 1.4 in favor of + `candlestick_ochl`, which maintains the original argument + order, or `candlestick_ohlc`, which uses the + open-high-low-close order. This function will be removed in 1.5 + + + Parameters + ---------- + ax : `Axes` + an Axes instance to plot to + quotes : sequence of (time, open, high, low, close, ...) sequences + As long as the first 5 elements are these values, + the record can be as long as you want (eg it may store volume). + + time must be in float days format - see date2num + + width : float + fraction of a day for the rectangle width + colorup : color + the color of the rectangle where close >= open + colordown : color + the color of the rectangle where close < open + alpha : float + the rectangle alpha level + + Returns + ------- + ret : tuple + returns (lines, patches) where lines is a list of lines + added and patches is a list of the rectangle patches added + + """ + warnings.warn(_warn_str.format(fun='candlestick'), + mplDeprecation) + + _candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, + alpha=alpha, ochl=True) + + def candlestick_ochl(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0): @@ -600,7 +743,7 @@ def candlestick_ochl(ax, quotes, width=0.2, colorup='k', colordown='r', added and patches is a list of the rectangle patches added """ - candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, + _candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, alpha=alpha, ochl=True) @@ -639,20 +782,14 @@ def candlestick_ohlc(ax, quotes, width=0.2, colorup='k', colordown='r', added and patches is a list of the rectangle patches added """ - candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, + _candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, alpha=alpha, ochl=False) -def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', +def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0, ochl=True): """ - - This function has been deprecated in 1.4 in favor of - `candlestick_ochl`, which maintains the original argument - order, or `candlestick_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.5 - Plot the time, open, high, low, close as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, @@ -770,11 +907,11 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, a list of lines added to the axes """ - warnings.warn("This function has been deprecated in 1.4 in favor" - "of `plot_day_summary_ochl`," - "which maintains the original argument order," - "or `plot_day_summary_ohlc`," - "which uses the open-high-low-close order." + warnings.warn("This function has been deprecated in 1.4 in favor " + "of `plot_day_summary2_ochl`, " + "which maintains the original argument order, " + "or `plot_day_summary2_ohlc`, " + "which uses the open-high-low-close order. " "This function will be removed in 1.5", mplDeprecation) return plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize, colorup, colordown) @@ -927,7 +1064,7 @@ def plot_day_summary2_ohlc(ax, opens, highs, lows, closes, ticksize=4, return rangeCollection, openCollection, closeCollection -def candlestick_ochl(ax, opens, closes, highs, lows, width=4, +def candlestick2_ochl(ax, opens, closes, highs, lows, width=4, colorup='k', colordown='r', alpha=0.75, ): @@ -977,8 +1114,8 @@ def candlestick2(ax, opens, closes, highs, lows, width=4, vertical line. This function has been deprecated in 1.4 in favor of - `candlestick_ochl`, which maintains the original argument order, - or `candlestick_ohlc`, which uses the open-high-low-close order. + `candlestick2_ochl`, which maintains the original argument order, + or `candlestick2_ohlc`, which uses the open-high-low-close order. This function will be removed in 1.5 @@ -1020,7 +1157,7 @@ def candlestick2(ax, opens, closes, highs, lows, width=4, alpha=alpha) -def candlestick_ohlc(ax, opens, highs, lows, closes, width=4, +def candlestick2_ohlc(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75, ): From c8fcc1a6759f5558ebb8cecefd3b2144408b7001 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 23:09:56 -0500 Subject: [PATCH 16/29] wrapped and deprecated quotes_historical_yahoo --- lib/matplotlib/finance.py | 127 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 9ffa036aee3b..49b90e29ea52 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -417,6 +417,133 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, return urlopen(url) +def quotes_historical_yahoo(ticker, date1, date2, asobject=False, + adjusted=True, cachename=None): + """ Get historical data for ticker between date1 and date2. + + + This function has been deprecated in 1.4 in favor of + `quotes_yahoo_historical_ochl`, which maintains the original argument + order, or `quotes_yahoo_historical_ohlc`, which uses the + open-high-low-close order. This function will be removed in 1.5 + + See :func:`parse_yahoo_historical` for explanation of output formats + and the *asobject* and *adjusted* kwargs. + + Ex: + sp = f.quotes_historical_yahoo('^GSPC', d1, d2, + asobject=True, adjusted=True) + returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] + [n,bins,patches] = hist(returns, 100) + mu = mean(returns) + sigma = std(returns) + x = normpdf(bins, mu, sigma) + plot(bins, x, color='red', lw=2) + + Parameters + ---------- + ticker : str + stock ticker + + date1 : sequence of form (year, month, day), `datetime`, or `date` + start date + + date2 : sequence of form (year, month, day), `datetime`, or `date` + end date + + cachename : str or `None` + is the name of the local file cache. If None, will + default to the md5 hash or the url (which incorporates the ticker + and date range) + """ + warnings.warn(_warn_str.format(fun='quotes_historical_yahoo'), + mplDeprecation) + + _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, + adjusted=adjusted, cachename=cachename, + ochl=True) + + +def quotes_historical_yahoo_ochl(ticker, date1, date2, asobject=False, + adjusted=True, cachename=None): + """ Get historical data for ticker between date1 and date2. + + + See :func:`parse_yahoo_historical` for explanation of output formats + and the *asobject* and *adjusted* kwargs. + + Ex: + sp = f.quotes_historical_yahoo('^GSPC', d1, d2, + asobject=True, adjusted=True) + returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] + [n,bins,patches] = hist(returns, 100) + mu = mean(returns) + sigma = std(returns) + x = normpdf(bins, mu, sigma) + plot(bins, x, color='red', lw=2) + + Parameters + ---------- + ticker : str + stock ticker + + date1 : sequence of form (year, month, day), `datetime`, or `date` + start date + + date2 : sequence of form (year, month, day), `datetime`, or `date` + end date + + cachename : str or `None` + is the name of the local file cache. If None, will + default to the md5 hash or the url (which incorporates the ticker + and date range) + """ + + _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, + adjusted=adjusted, cachename=cachename, + ochl=True) + + +def quotes_historical_yahoo_ohlc(ticker, date1, date2, asobject=False, + adjusted=True, cachename=None): + """ Get historical data for ticker between date1 and date2. + + + See :func:`parse_yahoo_historical` for explanation of output formats + and the *asobject* and *adjusted* kwargs. + + Ex: + sp = f.quotes_historical_yahoo('^GSPC', d1, d2, + asobject=True, adjusted=True) + returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] + [n,bins,patches] = hist(returns, 100) + mu = mean(returns) + sigma = std(returns) + x = normpdf(bins, mu, sigma) + plot(bins, x, color='red', lw=2) + + Parameters + ---------- + ticker : str + stock ticker + + date1 : sequence of form (year, month, day), `datetime`, or `date` + start date + + date2 : sequence of form (year, month, day), `datetime`, or `date` + end date + + cachename : str or `None` + is the name of the local file cache. If None, will + default to the md5 hash or the url (which incorporates the ticker + and date range) + """ + + _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, + adjusted=adjusted, cachename=cachename, + ochl=True) + + def _quotes_historical_yahoo(ticker, date1, date2, asobject=False, adjusted=True, cachename=None, ochl=True): From a92039bf8fb0b130c3fa86d3a8fad0f6975ec102 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 23:11:23 -0500 Subject: [PATCH 17/29] fixed naming bugs --- lib/matplotlib/finance.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 49b90e29ea52..6b454d24c6e6 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -1040,7 +1040,7 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, "or `plot_day_summary2_ohlc`, " "which uses the open-high-low-close order. " "This function will be removed in 1.5", mplDeprecation) - return plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize, + return plot_day_summary2_ohlc(ax, opens, highs, lows, closes, ticksize, colorup, colordown) @@ -1077,7 +1077,7 @@ def plot_day_summary2_ochl(ax, opens, closes, highs, lows, ticksize=4, a list of lines added to the axes """ - return plot_day_summary_ohlc(ax, opens, highs, lows, closes, ticksize, + return plot_day_summary2_ohlc(ax, opens, highs, lows, closes, ticksize, colorup, colordown) @@ -1228,7 +1228,7 @@ def candlestick2_ochl(ax, opens, closes, highs, lows, width=4, (lineCollection, barCollection) """ - candlestick_ohlc(ax, opens, highs, closes, lows, width=width, + candlestick2_ohlc(ax, opens, highs, closes, lows, width=width, colorup=colorup, colordown=colordown, alpha=alpha) @@ -1279,7 +1279,7 @@ def candlestick2(ax, opens, closes, highs, lows, width=4, "which uses the open-high-low-close order." "This function will be removed in 1.5", mplDeprecation) - candlestick_ohlc(ax, opens, highs, lows, closes, width=width, + candlestick2_ohlc(ax, opens, highs, lows, closes, width=width, colorup=colorup, colordown=colordown, alpha=alpha) From 1def45945243b17eafd471496a71553ebdf5e2fe Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 29 May 2013 23:49:22 -0500 Subject: [PATCH 18/29] fixed a collection of stupid bugs (like not returning from wrapper functions). --- lib/matplotlib/finance.py | 52 ++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 6b454d24c6e6..d466371e1e3b 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -116,8 +116,8 @@ def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): very similar to the Bunch. """ - _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, - oclh=True) + return _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, + ochl=True) def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): @@ -160,7 +160,7 @@ def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): holding 1-D ndarrays. The behavior of a numpy recarray is very similar to the Bunch. """ - _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, + return _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, ochl=False) @@ -217,11 +217,12 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): Defaults to True to preserve original functionality. """ + warnings.warn(_warn_str.format(fun='parse_yahoo_historical'), mplDeprecation) - _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, - oclh=True) + return _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, + ochl=True) def _parse_yahoo_historical(fh, adjusted=True, asobject=False, @@ -283,13 +284,11 @@ def _parse_yahoo_historical(fh, adjusted=True, asobject=False, else: stock_dt = stock_dt_ohlc - lines = fh.readlines() - results = [] # datefmt = '%Y-%m-%d' - - for line in lines[1:]: + fh.readline() # discard heading + for line in fh: vals = line.split(',') if len(vals) != 7: @@ -303,9 +302,13 @@ def _parse_yahoo_historical(fh, adjusted=True, asobject=False, open, high, low, close = [float(val) for val in vals[1:5]] volume = float(vals[5]) aclose = float(vals[6]) + if ochl: + results.append((dt, dt.year, dt.month, dt.day, + dnum, open, close, high, low, volume, aclose)) - results.append((dt, dt.year, dt.month, dt.day, - dnum, open, high, low, close, volume, aclose)) + else: + results.append((dt, dt.year, dt.month, dt.day, + dnum, open, high, low, close, volume, aclose)) results.reverse() d = np.array(results, dtype=stock_dt) if adjusted: @@ -459,7 +462,7 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, warnings.warn(_warn_str.format(fun='quotes_historical_yahoo'), mplDeprecation) - _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, + return _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, adjusted=adjusted, cachename=cachename, ochl=True) @@ -499,7 +502,7 @@ def quotes_historical_yahoo_ochl(ticker, date1, date2, asobject=False, and date range) """ - _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, + return _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, adjusted=adjusted, cachename=cachename, ochl=True) @@ -539,7 +542,7 @@ def quotes_historical_yahoo_ohlc(ticker, date1, date2, asobject=False, and date range) """ - _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, + return _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, adjusted=adjusted, cachename=cachename, ochl=True) @@ -639,7 +642,7 @@ def plot_day_summary(ax, quotes, ticksize=3, warnings.warn(_warn_str.format(fun='plot_day_summary'), mplDeprecation) - _plot_day_summary(ax, quotes, ticksize=ticksize, + return _plot_day_summary(ax, quotes, ticksize=ticksize, colorup=colorup, colordown=colordown, ochl=True) @@ -673,7 +676,7 @@ def plot_day_summary_oclh(ax, quotes, ticksize=3, lines : list list of tuples of the lines added (one tuple per quote) """ - _plot_day_summary(ax, quotes, ticksize=ticksize, + return _plot_day_summary(ax, quotes, ticksize=ticksize, colorup=colorup, colordown=colordown, ochl=True) @@ -707,7 +710,7 @@ def plot_day_summary_ohlc(ax, quotes, ticksize=3, lines : list list of tuples of the lines added (one tuple per quote) """ - _plot_day_summary(ax, quotes, ticksize=ticksize, + return _plot_day_summary(ax, quotes, ticksize=ticksize, colorup=colorup, colordown=colordown, ochl=False) @@ -831,8 +834,9 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', warnings.warn(_warn_str.format(fun='candlestick'), mplDeprecation) - _candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, - alpha=alpha, ochl=True) + return _candlestick(ax, quotes, width=width, colorup=colorup, + colordown=colordown, + alpha=alpha, ochl=True) def candlestick_ochl(ax, quotes, width=0.2, colorup='k', colordown='r', @@ -870,8 +874,9 @@ def candlestick_ochl(ax, quotes, width=0.2, colorup='k', colordown='r', added and patches is a list of the rectangle patches added """ - _candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, - alpha=alpha, ochl=True) + return _candlestick(ax, quotes, width=width, colorup=colorup, + colordown=colordown, + alpha=alpha, ochl=True) def candlestick_ohlc(ax, quotes, width=0.2, colorup='k', colordown='r', @@ -909,8 +914,9 @@ def candlestick_ohlc(ax, quotes, width=0.2, colorup='k', colordown='r', added and patches is a list of the rectangle patches added """ - _candlestick(ax, quotes, width=width, colorup=colorup, colordown=colordown, - alpha=alpha, ochl=False) + return _candlestick(ax, quotes, width=width, colorup=colorup, + colordown=colordown, + alpha=alpha, ochl=False) def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', From e4fab5d478654d423ba4beae5295c82687b2637d Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Thu, 30 May 2013 00:00:41 -0500 Subject: [PATCH 19/29] added note to api_change.rst --- doc/api/api_changes.rst | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/doc/api/api_changes.rst b/doc/api/api_changes.rst index a17ef4971e52..f51c67edf7b3 100644 --- a/doc/api/api_changes.rst +++ b/doc/api/api_changes.rst @@ -48,8 +48,16 @@ original location: - mstream -> `from matplotlib import stream as mstream` - mtable -> `from matplotlib import table as mtable` + +* In :module:`~matplotlib.finance`, almost all functions have beeen depreciated and + replaced with a pair of functions name `*_ochl` and `*_ohlc`. The former is + 'open-close-high-low' order of quotes, and what the module used and the later + is 'open-high-low-close' order of quotes, which is the standard in finance. + + .. _changes_in_1_3: + Changes in 1.3.x ================ From 469e267a582fcd8c268f36e33f8e2acb2995cbe7 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Thu, 30 May 2013 00:23:11 -0500 Subject: [PATCH 20/29] documentation corrections --- lib/matplotlib/finance.py | 65 +++++++++++++++++---------------------- 1 file changed, 29 insertions(+), 36 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index d466371e1e3b..da4b3e856dd5 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -81,7 +81,7 @@ def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): ---------- adjusted : `bool` - If True (default) replace open, high, low, close prices with + If True (default) replace open, close, high, low prices with their adjusted values. The adjustment is by a scale factor, S = adjusted_close/close. Adjusted prices are actual prices multiplied by S. @@ -178,7 +178,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): ---------- adjusted : `bool` - If True (default) replace open, high, low, close prices with + If True (default) replace open, close, high, low prices with their adjusted values. The adjustment is by a scale factor, S = adjusted_close/close. Adjusted prices are actual prices multiplied by S. @@ -193,14 +193,14 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): If False (default for compatibility with earlier versions) return a list of tuples containing - d, open, high, low, close, volume + d, open, close, high, low, volume If None (preferred alternative to False), return a 2-D ndarray corresponding to the list of tuples. Otherwise return a numpy recarray with - date, year, month, day, d, open, high, low, close, + date, year, month, day, d, open, close, high, low, volume, adjusted_close where d is a floating poing representation of date, @@ -230,12 +230,6 @@ def _parse_yahoo_historical(fh, adjusted=True, asobject=False, """Parse the historical data in file handle fh from yahoo finance. - This function has been deprecated in 1.4 in favor of - `parse_yahoo_historical_ochl`, which maintains the original argument - order, or `parse_yahoo_historical_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.5 - - Parameters ---------- @@ -257,6 +251,12 @@ def _parse_yahoo_historical(fh, adjusted=True, asobject=False, d, open, high, low, close, volume + or + + d, open, close, high, low, volume + + depending on `ochl` + If None (preferred alternative to False), return a 2-D ndarray corresponding to the list of tuples. @@ -275,7 +275,7 @@ def _parse_yahoo_historical(fh, adjusted=True, asobject=False, very similar to the Bunch. ochl : `bool` - Temporary argument to select between ochl and ohlc ordering. + Selects between ochl and ohlc ordering. Defaults to True to preserve original functionality. """ @@ -732,8 +732,11 @@ def _plot_day_summary(ax, quotes, ticksize=3, ---------- ax : `Axes` an `Axes` instance to plot to - quotes : sequence of (time, open, high, low, close, ...) sequences + quotes : sequence of quote sequences data to plot. time must be in float date format - see date2num + (time, open, high, low, close, ...) vs + (time, open, close, high, low, ...) + set by `ochl` ticksize : int open/close tick marker in points colorup : color @@ -741,7 +744,7 @@ def _plot_day_summary(ax, quotes, ticksize=3, colordown : color the color of the lines where close < open ochl: bool - temporary argument to select between ochl and ohlc ordering + argument to select between ochl and ohlc ordering of quotes Returns ------- @@ -809,7 +812,7 @@ def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', ---------- ax : `Axes` an Axes instance to plot to - quotes : sequence of (time, open, high, low, close, ...) sequences + quotes : sequence of (time, open, close, high, low, ...) sequences As long as the first 5 elements are these values, the record can be as long as you want (eg it may store volume). @@ -852,7 +855,7 @@ def candlestick_ochl(ax, quotes, width=0.2, colorup='k', colordown='r', ---------- ax : `Axes` an Axes instance to plot to - quotes : sequence of (time, open, high, low, close, ...) sequences + quotes : sequence of (time, open, close, high, low, ...) sequences As long as the first 5 elements are these values, the record can be as long as you want (eg it may store volume). @@ -932,12 +935,11 @@ def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', ---------- ax : `Axes` an Axes instance to plot to - quotes : sequence of (time, open, high, low, close, ...) sequences - As long as the first 5 elements are these values, - the record can be as long as you want (eg it may store volume). - - time must be in float days format - see date2num - + quotes : sequence of quote sequences + data to plot. time must be in float date format - see date2num + (time, open, high, low, close, ...) vs + (time, open, close, high, low, ...) + set by `ochl` width : float fraction of a day for the rectangle width colorup : color @@ -947,7 +949,7 @@ def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', alpha : float the rectangle alpha level ochl: bool - temporary argument to select between ochl and ohlc ordering + argument to select between ochl and ohlc ordering of quotes Returns ------- @@ -1040,12 +1042,7 @@ def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, a list of lines added to the axes """ - warnings.warn("This function has been deprecated in 1.4 in favor " - "of `plot_day_summary2_ochl`, " - "which maintains the original argument order, " - "or `plot_day_summary2_ohlc`, " - "which uses the open-high-low-close order. " - "This function will be removed in 1.5", mplDeprecation) + warnings.warn(_warn_str.format(fun='plot_day_summary2'), mplDeprecation) return plot_day_summary2_ohlc(ax, opens, highs, lows, closes, ticksize, colorup, colordown) @@ -1278,12 +1275,8 @@ def candlestick2(ax, opens, closes, highs, lows, width=4, ret : tuple (lineCollection, barCollection) """ - warnings.warn("This function has been deprecated in 1.4 in favor" - "of `candlestick_ochl`," - "which maintains the original argument order," - "or `candlestick_ohlc`," - "which uses the open-high-low-close order." - "This function will be removed in 1.5", mplDeprecation) + warnings.warn(_warn_str.format(fun='candlestick2'), + mplDeprecation) candlestick2_ohlc(ax, opens, highs, lows, closes, width=width, colorup=colorup, colordown=colordown, @@ -1304,12 +1297,12 @@ def candlestick2_ohlc(ax, opens, highs, lows, closes, width=4, an Axes instance to plot to opens : sequence sequence of opening values - closes : sequence - sequence of closing values highs : sequence sequence of high values lows : sequence sequence of low values + closes : sequence + sequence of closing values ticksize : int size of open and close ticks in points colorup : color From 007754c58ac3d123e55ae5bfcceb2fd0add3c636 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Fri, 31 May 2013 13:55:55 -0500 Subject: [PATCH 21/29] minor pep8 fix --- lib/matplotlib/finance.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index da4b3e856dd5..b915fd21936a 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -392,7 +392,8 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, else: g = 'd' - urlFmt = 'http://ichart.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv' + urlFmt = ('http://ichart.yahoo.com/table.csv?a=%d&b=%d&' + + 'c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv') url = urlFmt % (d1[0], d1[1], d1[2], d2[0], d2[1], d2[2], ticker, g) From 58d741fe8f84569c9f54d120002cb834eedea56a Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Tue, 16 Jul 2013 13:00:05 -0500 Subject: [PATCH 22/29] minor formatting changes to doc-strings tweaked import --- lib/matplotlib/finance.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index b915fd21936a..2086aa716426 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -29,7 +29,7 @@ from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D -from cbook import mplDeprecation +from matplotlb.cbook import mplDeprecation cachedir = get_cachedir() # cachedir will be None if there is no writable directory. @@ -122,6 +122,7 @@ def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): """Parse the historical data in file handle fh from yahoo finance. + Parameters ---------- @@ -347,7 +348,8 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, Fetch historical data for ticker between date1 and date2. date1 and date2 are date or datetime instances, or (year, month, day) sequences. - Ex: + Examples + fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31)) Parameters From 62f4e19b945f2bd961809cba646b83e63f775f1e Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sun, 21 Jul 2013 16:46:24 -0500 Subject: [PATCH 23/29] spelling + formatting fixes --- doc/api/api_changes.rst | 2 +- lib/matplotlib/finance.py | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/doc/api/api_changes.rst b/doc/api/api_changes.rst index f51c67edf7b3..721e0549117c 100644 --- a/doc/api/api_changes.rst +++ b/doc/api/api_changes.rst @@ -49,7 +49,7 @@ original location: - mtable -> `from matplotlib import table as mtable` -* In :module:`~matplotlib.finance`, almost all functions have beeen depreciated and +* In :module:`~matplotlib.finance`, almost all functions have been deprecated and replaced with a pair of functions name `*_ochl` and `*_ohlc`. The former is 'open-close-high-low' order of quotes, and what the module used and the later is 'open-high-low-close' order of quotes, which is the standard in finance. diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 2086aa716426..b6ea24aa7f3d 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -80,7 +80,7 @@ def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): Parameters ---------- - adjusted : `bool` + adjusted : bool If True (default) replace open, close, high, low prices with their adjusted values. The adjustment is by a scale factor, S = adjusted_close/close. Adjusted prices are actual prices @@ -92,7 +92,7 @@ def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): = True|False. - asobject : `bool` or :class:`None` + asobject : bool or None If False (default for compatibility with earlier versions) return a list of tuples containing @@ -126,7 +126,7 @@ def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): Parameters ---------- - adjusted : `bool` + adjusted : bool If True (default) replace open, high, low, close prices with their adjusted values. The adjustment is by a scale factor, S = adjusted_close/close. Adjusted prices are actual prices @@ -138,7 +138,7 @@ def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): = True|False. - asobject : `bool` or :class:`None` + asobject : bool or None If False (default for compatibility with earlier versions) return a list of tuples containing @@ -178,7 +178,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): Parameters ---------- - adjusted : `bool` + adjusted : bool If True (default) replace open, close, high, low prices with their adjusted values. The adjustment is by a scale factor, S = adjusted_close/close. Adjusted prices are actual prices @@ -190,7 +190,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): = True|False. - asobject : `bool` or :class:`None` + asobject : bool or None If False (default for compatibility with earlier versions) return a list of tuples containing @@ -213,7 +213,7 @@ def parse_yahoo_historical(fh, adjusted=True, asobject=False): holding 1-D ndarrays. The behavior of a numpy recarray is very similar to the Bunch. - ochl : `bool` + ochl : bool Temporary argument to select between ochl and ohlc ordering. Defaults to True to preserve original functionality. @@ -234,7 +234,7 @@ def _parse_yahoo_historical(fh, adjusted=True, asobject=False, Parameters ---------- - adjusted : `bool` + adjusted : bool If True (default) replace open, high, low, close prices with their adjusted values. The adjustment is by a scale factor, S = adjusted_close/close. Adjusted prices are actual prices @@ -246,7 +246,7 @@ def _parse_yahoo_historical(fh, adjusted=True, asobject=False, = True|False. - asobject : `bool` or :class:`None` + asobject : bool or None If False (default for compatibility with earlier versions) return a list of tuples containing @@ -275,7 +275,7 @@ def _parse_yahoo_historical(fh, adjusted=True, asobject=False, holding 1-D ndarrays. The behavior of a numpy recarray is very similar to the Bunch. - ochl : `bool` + ochl : bool Selects between ochl and ohlc ordering. Defaults to True to preserve original functionality. @@ -367,7 +367,7 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, default to the md5 hash or the url (which incorporates the ticker and date range) - dividends : `bool` + dividends : bool set dividends=True to return dividends instead of price data. With this option set, parse functions will not work From 4ef8ac9b3ac312d6c75803549f71f463a67f40fe Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sun, 4 Aug 2013 09:43:16 -0500 Subject: [PATCH 24/29] Added Examples section to `parse_yahoo_historical*`. Fixed bug in `parse_yahoo_historical_ohlc` --- lib/matplotlib/finance.py | 99 +++++++++++++++++++++------------------ 1 file changed, 54 insertions(+), 45 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index b6ea24aa7f3d..38b6a97c9ab6 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -348,10 +348,6 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, Fetch historical data for ticker between date1 and date2. date1 and date2 are date or datetime instances, or (year, month, day) sequences. - Examples - - fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31)) - Parameters ---------- ticker : str @@ -375,6 +371,12 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, ------- file_handle : file handle a file handle is returned + + + Examples + -------- + >>> fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31)) + """ ticker = ticker.upper() @@ -436,16 +438,6 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, See :func:`parse_yahoo_historical` for explanation of output formats and the *asobject* and *adjusted* kwargs. - Ex: - sp = f.quotes_historical_yahoo('^GSPC', d1, d2, - asobject=True, adjusted=True) - returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] - [n,bins,patches] = hist(returns, 100) - mu = mean(returns) - sigma = std(returns) - x = normpdf(bins, mu, sigma) - plot(bins, x, color='red', lw=2) - Parameters ---------- ticker : str @@ -461,6 +453,18 @@ def quotes_historical_yahoo(ticker, date1, date2, asobject=False, is the name of the local file cache. If None, will default to the md5 hash or the url (which incorporates the ticker and date range) + + Examples + -------- + >>> sp = f.quotes_historical_yahoo('^GSPC', d1, d2, + asobject=True, adjusted=True) + >>> returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] + >>> [n,bins,patches] = hist(returns, 100) + >>> mu = mean(returns) + >>> sigma = std(returns) + >>> x = normpdf(bins, mu, sigma) + >>> plot(bins, x, color='red', lw=2) + """ warnings.warn(_warn_str.format(fun='quotes_historical_yahoo'), mplDeprecation) @@ -478,16 +482,6 @@ def quotes_historical_yahoo_ochl(ticker, date1, date2, asobject=False, See :func:`parse_yahoo_historical` for explanation of output formats and the *asobject* and *adjusted* kwargs. - Ex: - sp = f.quotes_historical_yahoo('^GSPC', d1, d2, - asobject=True, adjusted=True) - returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] - [n,bins,patches] = hist(returns, 100) - mu = mean(returns) - sigma = std(returns) - x = normpdf(bins, mu, sigma) - plot(bins, x, color='red', lw=2) - Parameters ---------- ticker : str @@ -503,6 +497,18 @@ def quotes_historical_yahoo_ochl(ticker, date1, date2, asobject=False, is the name of the local file cache. If None, will default to the md5 hash or the url (which incorporates the ticker and date range) + + Examples + -------- + >>> sp = f.quotes_historical_yahoo('^GSPC', d1, d2, + asobject=True, adjusted=True) + >>> returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] + >>> [n,bins,patches] = hist(returns, 100) + >>> mu = mean(returns) + >>> sigma = std(returns) + >>> x = normpdf(bins, mu, sigma) + >>> plot(bins, x, color='red', lw=2) + """ return _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, @@ -518,16 +524,6 @@ def quotes_historical_yahoo_ohlc(ticker, date1, date2, asobject=False, See :func:`parse_yahoo_historical` for explanation of output formats and the *asobject* and *adjusted* kwargs. - Ex: - sp = f.quotes_historical_yahoo('^GSPC', d1, d2, - asobject=True, adjusted=True) - returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] - [n,bins,patches] = hist(returns, 100) - mu = mean(returns) - sigma = std(returns) - x = normpdf(bins, mu, sigma) - plot(bins, x, color='red', lw=2) - Parameters ---------- ticker : str @@ -543,11 +539,23 @@ def quotes_historical_yahoo_ohlc(ticker, date1, date2, asobject=False, is the name of the local file cache. If None, will default to the md5 hash or the url (which incorporates the ticker and date range) + + Examples + -------- + >>> sp = f.quotes_historical_yahoo('^GSPC', d1, d2, + asobject=True, adjusted=True) + >>> returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] + >>> [n,bins,patches] = hist(returns, 100) + >>> mu = mean(returns) + >>> sigma = std(returns) + >>> x = normpdf(bins, mu, sigma) + >>> plot(bins, x, color='red', lw=2) + """ return _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, adjusted=adjusted, cachename=cachename, - ochl=True) + ochl=False) def _quotes_historical_yahoo(ticker, date1, date2, asobject=False, @@ -558,16 +566,6 @@ def _quotes_historical_yahoo(ticker, date1, date2, asobject=False, See :func:`parse_yahoo_historical` for explanation of output formats and the *asobject* and *adjusted* kwargs. - Ex: - sp = f.quotes_historical_yahoo('^GSPC', d1, d2, - asobject=True, adjusted=True) - returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] - [n,bins,patches] = hist(returns, 100) - mu = mean(returns) - sigma = std(returns) - x = normpdf(bins, mu, sigma) - plot(bins, x, color='red', lw=2) - Parameters ---------- ticker : str @@ -588,6 +586,17 @@ def _quotes_historical_yahoo(ticker, date1, date2, asobject=False, temporary argument to select between ochl and ohlc ordering + Examples + -------- + >>> sp = f.quotes_historical_yahoo('^GSPC', d1, d2, + asobject=True, adjusted=True) + >>> returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] + >>> [n,bins,patches] = hist(returns, 100) + >>> mu = mean(returns) + >>> sigma = std(returns) + >>> x = normpdf(bins, mu, sigma) + >>> plot(bins, x, color='red', lw=2) + """ # Maybe enable a warning later as part of a slow transition # to using None instead of False. From 4c76044db72d558ba8935705cd6d0843a23e5a6d Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sun, 4 Aug 2013 10:01:15 -0500 Subject: [PATCH 25/29] fixed typos --- lib/matplotlib/finance.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 38b6a97c9ab6..a6abc8db9ded 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -29,7 +29,7 @@ from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D -from matplotlb.cbook import mplDeprecation +from matplotlib.cbook import mplDeprecation cachedir = get_cachedir() # cachedir will be None if there is no writable directory. @@ -606,7 +606,7 @@ def _quotes_historical_yahoo(ticker, date1, date2, asobject=False, fh = fetch_historical_yahoo(ticker, date1, date2, cachename) try: - ret = parse_yahoo_historical(fh, asobject=asobject, + ret = _parse_yahoo_historical(fh, asobject=asobject, adjusted=adjusted, ochl=ochl) if len(ret) == 0: return None From 1e39c0c9b59006499cd57d7419cd727e2cf561b6 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sun, 4 Aug 2013 10:02:08 -0500 Subject: [PATCH 26/29] updated `finance_demo.py` code to use new api --- examples/pylab_examples/finance_demo.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/examples/pylab_examples/finance_demo.py b/examples/pylab_examples/finance_demo.py index 9d0318e2f234..409b8cdd9a80 100644 --- a/examples/pylab_examples/finance_demo.py +++ b/examples/pylab_examples/finance_demo.py @@ -1,21 +1,21 @@ #!/usr/bin/env python import matplotlib.pyplot as plt -from matplotlib.dates import DateFormatter, WeekdayLocator, HourLocator, \ +from matplotlib.dates import DateFormatter, WeekdayLocator,\ DayLocator, MONDAY -from matplotlib.finance import quotes_historical_yahoo, candlestick,\ - plot_day_summary, candlestick2 +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 ) +date1 = (2004, 2, 1) +date2 = (2004, 4, 12) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays -alldays = DayLocator() # minor ticks on the days +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('INTC', date1, date2) +quotes = quotes_historical_yahoo_ohlc('INTC', date1, date2) if len(quotes) == 0: raise SystemExit @@ -27,11 +27,10 @@ #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) -candlestick(ax, quotes, width=0.6) +candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() -plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') +plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show() - From ca81f1612fef92be755b6757f10353ce18a64687 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sun, 4 Aug 2013 10:20:53 -0500 Subject: [PATCH 27/29] added the finance module to api list so the documentation gets generated. --- doc/api/finance_api.rst | 12 ++++++++++++ doc/api/index.rst | 1 + 2 files changed, 13 insertions(+) create mode 100644 doc/api/finance_api.rst diff --git a/doc/api/finance_api.rst b/doc/api/finance_api.rst new file mode 100644 index 000000000000..9b2c5021c675 --- /dev/null +++ b/doc/api/finance_api.rst @@ -0,0 +1,12 @@ +******* +finance +******* + + +:mod:`matplotlib.finance` +========================= + +.. automodule:: matplotlib.finance + :members: + :undoc-members: + :show-inheritance: diff --git a/doc/api/index.rst b/doc/api/index.rst index 1713b439c411..061aff6ac1cd 100644 --- a/doc/api/index.rst +++ b/doc/api/index.rst @@ -28,6 +28,7 @@ colors_api.rst dates_api.rst figure_api.rst + finance_api.rst font_manager_api.rst gridspec_api.rst legend_api.rst From e772ac4e4f9100f1cbf743ed08e66255e9aab7e4 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Mon, 5 Aug 2013 10:22:40 -0500 Subject: [PATCH 28/29] added depreciation warning to module doc-string tweaked examples --- lib/matplotlib/finance.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index a6abc8db9ded..106822d64caf 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -1,7 +1,10 @@ """ -A collection of modules for collecting, analyzing and plotting +A collection of functions for collecting, analyzing and plotting financial data. User contributions welcome! +This module is deprecated in 1.4 and will be moved to `mpl_toolkits` +or it's own project in the future. + """ from __future__ import division, print_function import contextlib @@ -500,7 +503,7 @@ def quotes_historical_yahoo_ochl(ticker, date1, date2, asobject=False, Examples -------- - >>> sp = f.quotes_historical_yahoo('^GSPC', d1, d2, + >>> sp = f.quotes_historical_yahoo_ochl('^GSPC', d1, d2, asobject=True, adjusted=True) >>> returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] >>> [n,bins,patches] = hist(returns, 100) @@ -542,7 +545,7 @@ def quotes_historical_yahoo_ohlc(ticker, date1, date2, asobject=False, Examples -------- - >>> sp = f.quotes_historical_yahoo('^GSPC', d1, d2, + >>> sp = f.quotes_historical_yahoo_ohlc('^GSPC', d1, d2, asobject=True, adjusted=True) >>> returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] >>> [n,bins,patches] = hist(returns, 100) From c4819c29173f7ba52a6127d4b469fdd368d082bd Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Mon, 5 Aug 2013 10:27:44 -0500 Subject: [PATCH 29/29] cleaned up usage of `quotes_historical_yahoo` in demos --- examples/pylab_examples/date_demo1.py | 12 ++++++------ examples/pylab_examples/date_demo2.py | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/examples/pylab_examples/date_demo1.py b/examples/pylab_examples/date_demo1.py index 51b852a4951e..fbd61356578b 100644 --- a/examples/pylab_examples/date_demo1.py +++ b/examples/pylab_examples/date_demo1.py @@ -15,17 +15,17 @@ """ import matplotlib.pyplot as plt -from matplotlib.finance import quotes_historical_yahoo +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 ) +date1 = datetime.date(1995, 1, 1) +date2 = datetime.date(2004, 4, 12) -years = YearLocator() # every year -months = MonthLocator() # every month +years = YearLocator() # every year +months = MonthLocator() # every month yearsFmt = DateFormatter('%Y') -quotes = quotes_historical_yahoo( +quotes = quotes_historical_yahoo_ochl( 'INTC', date1, date2) if len(quotes) == 0: raise SystemExit diff --git a/examples/pylab_examples/date_demo2.py b/examples/pylab_examples/date_demo2.py index d6420f97674c..8794447acdb1 100755 --- a/examples/pylab_examples/date_demo2.py +++ b/examples/pylab_examples/date_demo2.py @@ -9,22 +9,22 @@ import datetime import matplotlib.pyplot as plt from matplotlib.dates import MONDAY -from matplotlib.finance import quotes_historical_yahoo +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 ) +date1 = datetime.date(2002, 1, 5) +date2 = datetime.date(2003, 12, 1) # every monday -mondays = WeekdayLocator(MONDAY) +mondays = WeekdayLocator(MONDAY) # every 3rd month -months = MonthLocator(range(1,13), bymonthday=1, interval=3) +months = MonthLocator(range(1, 13), bymonthday=1, interval=3) monthsFmt = DateFormatter("%b '%y") -quotes = quotes_historical_yahoo('INTC', date1, date2) +quotes = quotes_historical_yahoo_ochl('INTC', date1, date2) if len(quotes) == 0: print ('Found no quotes') raise SystemExit