在matplotlib中的日期时间轴上绘制矩形?

时间:2018-04-28 02:54:14

标签: python datetime matplotlib finance rectangles

因此,我尝试使用matplotlib手动创建一个烛台图表,使用errorbar表示每日高价和低价,并Rectangle()表示调整后的收盘价和开盘价。 This question似乎具备完成此任务的所有先决条件。

我试图非常忠实地使用上述内容,但是在datetime64[ns]的x轴上绘制某些内容的问题让我没有错误的结束,所以我还试图合并the advice here来绘制日期时间。

到目前为止,这是我的代码,对于混乱道歉:

import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle

def makeCandles(xdata,high,low,adj_close,adj_open,fc='r',ec='None',alpha=0.5):

    ## Converting datetimes to numerical format matplotlib can understand.
    dates = mdates.date2num(xdata)

    ## Creating default objects
    fig,ax = plt.subplots(1)

    ## Creating errorbar peaks based on high and low prices
    avg = (high + low) / 2
    err = [high - avg,low - avg]

    ax.errorbar(dates,err,fmt='None',ecolor='k')

    ## Create list for all the error patches
    errorboxes = []

    ## Loop over data points; create "body" of candlestick 
    ## based on adjusted open and close prices

    errors=np.vstack((adj_close,adj_open))
    errors=errors.T

    for xc,yc,ye in zip(dates,avg,errors):
        rect = Rectangle((xc,yc-ye[0]),1,ye.sum())
        errorboxes.append(rect)

    ## Create patch collection with specified colour/alpha
    pc = PatchCollection(errorboxes,facecolor=fc,alpha=alpha,edgecolor=ec)

    ## Add collection to axes
    ax.add_collection(pc)

    plt.show()

我的数据看起来像

enter image description here

这是我尝试运行的,首先从quandl获取价格表,

import quandl as qd
api =  '1uRGReHyAEgwYbzkPyG3'
qd.ApiConfig.api_key = api 

data = qd.get_table('WIKI/PRICES', qopts = { 'columns': ['ticker', 'date', 'high','low','adj_open','adj_close'] }, \
                        ticker = ['AMZN', 'XOM'], date = { 'gte': '2014-01-01', 'lte': '2016-12-31' })
data.reset_index(inplace=True,drop=True)

makeCandles(data['date'],data['high'],data['low'],data['adj_open'],data['adj_close'])

代码运行时没有错误,但输出一个空图。所以我要求的是关于如何在日期时间日期绘制这些矩形的建议。对于矩形的宽度,我只需要制作一个制服" 1" BEC。我不知道一种简单的方法来指定矩形的日期时间宽度。我非常感谢经验丰富的帮助。

编辑:这是我目前正在获得的情节,将我的xdata转换为matplotlib mdates: enter image description here

在我通过mdates转换xdata之前,只有xdata作为我的x轴到处都是,这是我一直遇到的错误之一: enter image description here

1 个答案:

答案 0 :(得分:1)

要获得您想要的情节,需要考虑几个方面。首先,您要检索到股票AMZNXOM,显示两者会使您想要的图表看起来很有趣,因为数据相距很远。其次,您每天绘制几年的烛台图表将变得非常拥挤。最后,您需要在x轴上格式化您的序数日期。

如评论中所述,您可以使用candlestick2_ohlc可访问的预构建matplotlib mpl_finance函数(虽然已弃用),如this answer所示进行安装。我选择仅使用内置错误栏的matplotlib条形图。

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import quandl as qd
from matplotlib.dates import DateFormatter, WeekdayLocator, \
    DayLocator, MONDAY

# get data
api = '1uRGReHyAEgwYbzkPyG3'
qd.ApiConfig.api_key = api
data = qd.get_table('WIKI/PRICES', qopts={'columns': ['ticker', 'date', 'high', 'low', 'open', 'close']},
                    ticker=['AMZN', 'XOM'], date={'gte': '2014-01-01', 'lte': '2014-03-10'})
data.reset_index(inplace=True, drop=True)

fig, ax = plt.subplots(figsize = (10, 5))
data['date'] = mdates.date2num(data['date'].dt.to_pydatetime()) #convert dates to ordinal
tickers = list(set(data['ticker'])) # unique list of stock names
for stock_ind in tickers:
    df = data[data['ticker'] == 'AMZN'] # select one, can do more in a for loop, but it will look funny

    inc = df.close > df.open
    dec = df.open > df.close

    ax.bar(df['date'][inc],
           df['open'][inc]-df['close'][inc],
           color='palegreen',
           bottom=df['close'][inc],
           # this yerr is confusing when independent error bars are drawn => (https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.errorbar)
           yerr = [df['open'][inc]-df['high'][inc], -df['open'][inc]+df['low'][inc]],
           error_kw=dict(ecolor='gray', lw=1))

    ax.bar(df['date'][dec],
           df['close'][dec]-df['open'][dec],
           color='salmon', bottom=df['open'][dec],
           yerr = [df['close'][dec]-df['high'][dec], -df['close'][dec]+df['low'][dec]],
           error_kw=dict(ecolor='gray', lw=1))

    ax.set_title(stock_ind)

#some tweaking, setting the dates
mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
alldays = DayLocator()  # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
dayFormatter = DateFormatter('%d')  # e.g., 12
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
ax.set_ylabel('monies ($)')

plt.show()

Graph