使用matplotlib在python中绘制OHLC图表

时间:2018-04-23 00:17:50

标签: python matplotlib

我有一个烛台对象列表,每个烛台对象有6个值(打开,高,低,关闭,音量,时间戳)。我想使用matplotlib.finance.candlestick2_ohlc(ax,opens,highs,lows,closing,width = 4,colorup =' k&#39 ;, colordown =' r',alpha = 0.75)用于绘制此数据的功能。问题是,我如何将我的列表细分为打开,高,低和关闭以便将其加载到此功能?

这是我的烛台课程:

class Candle:
#Candlestick chart object
def __init__(self, open, high, low, close, volume, timeStamp):
    self.open = open
    self.high = high
    self.low = low
    self.close = close
    self.volume = volume
    self.timestamp = timeStamp

def __str__(self):
    return """
    Open: %s
    High: %s
    Low: %s
    Close: %s
    Volume : %s
    Timestamp: %s""" %(self.open, self.high, self.low, self.close, self.volume, self.timestamp)

这是我的列表构建方法:

def getTradeHistory(self, timeFrame, symbol, count):
    #Get the trade history from the API

    return self.client.Trade.Trade_getBucketed(binSize=timeFrame, partial=True, symbol=symbol, reverse=False, count=count).result()

def constructCandles(self, th):
    #Iterate through list of trade history items and store them as candles in a list

    for candle in th :
        self.candles.append(Candle(candle['open'], candle['high'], candle['low'], candle['close'], candle['volume'], candle['timestamp']))

1 个答案:

答案 0 :(得分:2)

说你的烛台对象列表叫做my_candles然后:

opens = [candle.open for candle in my_candles]
highs = [candle.high for candle in my_candles]
lows = [candle.low for candle in my_candles]
closes = [candle.close for candle in my_candles]

现在您有打开,关闭,高点和低点的列表,您可以调用matplotlib.finance.candlestick2_ohlc

import matplotlib.pyplot as plt
import matplotlib.finance as mpf

fig, ax = plt.subplots(figsize=(8,5))
mpf.candlestick2_ochl(ax, opens, closes, highs, lows, width=4, colorup='k', colordown='r', alpha=0.75)

另请注意,matplotlib.finance在2.0中已弃用。