如何更改烛台图表中阴影垂直线的颜色?

时间:2015-02-19 06:00:49

标签: python matplotlib

我试图制作一份综合财务图表,我可以用它来分析历史和图表。目前的价格。我已经完成了项目,但我遇到的问题是每个烛台中间出现的垂直线。它以某种方式默认为黑色(你不能看到黑色背景颜色),我想将这种颜色改为colorup和colordown。所以我试着修改matplotlib库中的finance.py,方法是将vLine代码移动到_candlestick函数中的if / else语句并进行相应的修改。它看起来像这样:

def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r',
                alpha=1.0):
    warnings.warn(_warn_str.format(fun='candlestick'),
                  mplDeprecation)

    return _candlestick(ax, quotes, width=width, colorup=colorup,
                        colordown=colordown,
                        alpha=alpha, ochl=True)

def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r',
                alpha=1.0, ochl=True):
 OFFSET = width / 2.0

    lines = []
    patches = []
    for q in quotes:
        if ochl:
            t, open, close, high, low = q[:5]
        else:
            t, open, high, low, close = q[:5]

        if close >= open:
            color = colorup
            lower = open
            height = close - open
            vline = Line2D(
                xdata=(t, t), ydata=(low, high),
                color=colorup,
                linewidth=0.5,
                antialiased=True,
                )       
        else:
            color = colordown
            lower = close
            height = open - close
            vline = Line2D(
                xdata=(t, t), ydata=(low, high),
                color=colordown,
                linewidth=0.5,
                antialiased=True,
                )            
'''
        vline = Line2D(
            xdata=(t, t), ydata=(low, high),
            color=color,
            linewidth=0.5,
            antialiased=True,
            )
'''
        rect = Rectangle(
            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)
        ax.add_patch(rect)
    ax.autoscale_view()

    return lines, patches

然后我在我的主代码中调用了这个函数:

candlestick(ax1, candleAr[-SP:], width=.75, colorup='#53C156', colordown='#ff1717')

我得到了相同的结果,好像我没有做任何改变。我该怎么办?请帮忙。

首先感谢发帖。我的观点不足以让我上传得到的数字,因此我只会向您展示显示图中所示分析之一的代码:

def graphData(stock,MA1,MA2):
    try:
        try:
            print 'Currently Pulling data for:', stock
            print str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S'))
            urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
            stockFile = []
            try:
                sourceCode = urllib2.urlopen(urlToVisit).read()
                splitSource = sourceCode.split('\n')
                for eachLine in splitSource:
                    splitLine = eachLine.split(',')
                    if len(splitLine)==6:
                        if 'values' not in eachLine:
                            stockFile.append(eachLine)

            except Exception, e:
                print str(e), 'failed to organize pulled data'


        except Exception, e:
            print str(e), 'failed to pull price data'

        #stockFile = stock+'.txt'

        date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=',', unpack=True, converters={0:mdates.strpdate2num('%Y%m%d')})

        x = 0
        y = len(date)
        candleAr = []
        while x < y:
            appendLine = date[x],openp[x],closep[x],highp[x],lowp[x],volume[x]
            candleAr.append(appendLine)
            x+=1

        Av1 = movingaverage(closep, MA1)
        Av2 = movingaverage(closep, MA2)

        SP = len(date[MA2-1:])

        fig = plt.figure(facecolor='#07000d')

        ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
        candlestick(ax1, candleAr[-SP:], width=.75, colorup='#53C156', colordown='#ff1717')

        label1 = str(MA1)+'  SMA'           
        label2 = str(MA2)+'  SMA'
        ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=label1, linewidth = 1.5)
        ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=label2, linewidth = 1.5)  

        ax1.grid(True, color='w')
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='lower'))
        ax1.yaxis.label.set_color('w')
        ax1.spines['bottom'].set_color('#5998ff')
        ax1.spines['top'].set_color('#5998ff')      
        ax1.spines['right'].set_color('#5998ff')        
        ax1.spines['left'].set_color('#5998ff') 
        ax1.tick_params(axis='y', colors='w')   
        ax1.tick_params(axis='x', colors='w')   
        plt.ylabel('Stock Price and Volume')

等等。你明白了。

1 个答案:

答案 0 :(得分:1)

确保您正在编辑正确的finance.py文件。我知道在我的电脑上有两份文件。从'if'和'else'语句中取出'vline = ...'并取消注释vline代码块。我编辑的文件有:

def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r',
            alpha=1.0, color='k'):

    return _candlestick(ax, quotes, width=width, colorup=colorup,
                        colordown=colordown,
                        alpha=alpha, ochl=True)

def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r',
                 alpha=1.0, ochl=True):
     OFFSET = width / 2.0

    lines = []
    patches = []
    for q in quotes:
        if ochl:
            t, open, close, high, low = q[:5]
        else:
            t, open, high, low, close = q[:5]

        if close >= open:
            color = colorup
            lower = open
            height = close - open
        else:
            color = colordown
            lower = close
            height = open - close

        vline = Line2D(
            xdata=(t, t), ydata=(low, high),
            color=color,
            linewidth=0.5,
            antialiased=True,
        )

        rect = Rectangle(
            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)
        ax.add_patch(rect)
    ax.autoscale_view()

    return lines, patches

https://www.youtube.com/watch?v=HSyMaJPOfX8引导您完成整个过程。如果您仍然遇到问题请告诉我。