使用 matplotlib.finance.candlestick2_ochl 无法显示正日烛台

Failure to display positive day Candlesticks using matplotlib.finance.candlestick2_ochl

我有一个 python 数据框 df 包含日期、开盘价、最高价、最低价、收盘价和交易量值。

我正在尝试绘制一只股票的烛台图。出于某种原因,我似乎无法 matplotlib.finance.candlestick2_ochl() 正确显示收盘价 self.df['closep'] 高于开盘价 self.df['openp'] 的日期。在这些积极的(绿色)日子里,matplotlib 要么显示十字星,要么什么都不显示。

不太清楚为什么我会出现这种行为。我怀疑这与我的程序从我的 Pandas DataFrame self.df.

访问股票数据的方式有关

这是我的代码:

# Visualize my stock data

import pandas as pd
import datetime
import time
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ochl
import matplotlib.ticker as mticker
import matplotlib.dates as mdates


class MyStock:
    def __init__(self, stock):
        self.stock = stock
        self.pullData()


    def pullData(self):
        try:
            print('Currently pulling', self.stock)
            print(str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')))
            urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + self.stock + '/chartdata;type=quote;range=5d/csv'

            self.df = pd.read_csv(urlToVisit, header=None, names=['date', 'closep', 'highp', 'lowp', 'openp', 'volume'],
                             skiprows=22, dtype=float)

            print('Pulled', self.stock, '\n')

        except Exception as e:
            print('main loop', str(e))

        print('Constucting DataFrame\n')
        self.df['date'] = pd.to_datetime(self.df['date'], unit='s')

        self.df = self.df.set_index('date').tz_localize('UTC').tz_convert('US/Eastern').reset_index()
        self.df['date'] = self.df['date'].dt.strftime('%Y-%m-%d %H:%M:%S')

        print(self.df.tail())


    def CandleStick(self):


        self.fig = plt.figure()

        ax1 = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, axisbg='w')

        candlestick2_ochl(ax1, opens=self.df['openp'], closes=self.df['closep'], highs=self.df['highp'], lows=self.df['lowp'], width=.75, colorup='k', colordown='r', alpha=0.75)

        plt.ylabel('Stock Price')
        ax1.grid(True)
        for label in ax1.xaxis.get_ticklabels():
            label.set_rotation(90)

        plt.subplots_adjust(left=.10, bottom=.19, right=.93, top=.95, wspace=.20, hspace=0)

        plt.suptitle(self.stock + ' Stock Price')
        plt.show()


amd = MyStock('AMD')
amd.CandleStick()

以及 DataFrame 相关部分旁边的输出屏幕截图:

您可以在此屏幕截图中清楚地看到正天数(绿色)未正确显示。我确定我在这里遗漏了一些非常明显的东西。

感谢任何帮助。

这里有一个错误

我使用的是 Matplotlib 1.5.1,matplotlib 目录中有一个 finance.py 文件,第 1059-1067 行。原代码为:

    candlestick2_ohlc(ax, opens, highs, closes, lows, width=width,
                 colorup=colorup, colordown=colordown,
                 alpha=alpha)


def candlestick2_ohlc(ax, opens, highs, lows, closes, width=4,
             colorup='k', colordown='r',
             alpha=0.75,
             ): 

应该是:

(交换参数中'closes'和'lows'的位置)

    candlestick2_ohlc(ax, opens, highs, lows, closes, width=width,
                 colorup=colorup, colordown=colordown,
                 alpha=alpha)


def candlestick2_ohlc(ax, opens, highs, lows, closes, width=4,
             colorup='k', colordown='r',
             alpha=0.75,
             ):

编辑此文件并保存。它应该可以解决您的问题。

Candlestick Chart. sorry for no picture displayed here. you have to click the url above to see the effect.

在 2 小时内解决了这个问题(现在是 2 a.m。) 就像我在 2 小时前猜测的一样(但不完全是同一个地方),很遗憾人们投票否决了我。


我 2 小时前写的东西。

我在官方Matplotlib API文档中找到了这句话,章节:"matplotlib.finance":

Preserves the original argument order.

这与您的问题有什么关系吗?

其实,我也遇到了和你一样的问题。

fig = plt.figure()
ax1 = plt.subplot(1,1,1)

candlestick(ax1,
        opens=test_data.open,
        closes=test_data.close,
        highs=test_data.high,
        lows=test_data.low,
        width=1,
        colorup='k',
        colordown='r',
        alpha=0.75)

fig.savefig('index.png',dpi=300,bbox_inches='tight')

我得到了这个: some wrong chart ploted by me

请查看生成颜色正确的烛台的代码:

import pandas as pd
import datetime
import time
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ochl
import matplotlib.ticker as mticker
import matplotlib.dates as mdates


class MyStock:
    def __init__(self, stock):
        self.stock = stock
        self.pullData()


    def pullData(self):
        try:
            print('Currently pulling', self.stock)
            print(str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')))
            urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + self.stock + '/chartdata;type=quote;range=2d/csv'

            self.df = pd.read_csv(urlToVisit, header=None, names=['date', 'closep', 'highp', 'lowp', 'openp', 'volume'],
                             skiprows=22, dtype=float)

            print('Pulled', self.stock, '\n')

        except Exception as e:
            print('main loop', str(e))

        print('Constucting DataFrame\n')
        self.df['date'] = pd.to_datetime(self.df['date'], unit='s')

        self.df = self.df.set_index('date').tz_localize('UTC').tz_convert('US/Eastern').reset_index()
        self.df['date'] = self.df['date'].dt.strftime('%Y-%m-%d %H:%M:%S')

        print(self.df.tail())


    def CandleStick(self):


        self.fig = plt.figure()
        ax1 = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, axisbg='w')
        candlestick2_ochl(ax1,
                          self.df['openp'], self.df['highp'], self.df['lowp'], self.df['closep'],
                          width=.75, colorup='g', colordown='r', alpha=0.75)

        plt.ylabel('Stock Price')
        ax1.grid(True)
        for label in ax1.xaxis.get_ticklabels():
            label.set_rotation(90)

        plt.subplots_adjust(left=.10, bottom=.19, right=.93, top=.95, wspace=.20, hspace=0)

        plt.suptitle(self.stock + ' Stock Price')
        plt.show()

amd = MyStock('AMD')
amd.CandleStick()