2017-02-10 113 views
1

matplotlib上绘制烛台图时,该图会在周末留下难看的空白。发生这种情况的原因是由于周末市场关闭导致数据中断。周末的差距如何消除?如何删除Matplotlib烛台图表中的周末?

下面是一个简单的例子,演示图中存在空隙。

import matplotlib.pyplot as plt 
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc 

date1, date2 = [(2006, 6, 1), (2006, 8, 1)] 
quotes_mpl = quotes_historical_yahoo_ohlc('INTC', date1, date2) 

fig, ax = plt.subplots() 
candlestick_ohlc(ax, quotes_mpl) 
ax.xaxis_date() 
plt.xticks(rotation=45) 

周末间隙用绿色箭头表示。

enter image description here

回答

2

不幸的是,matplotlib也不pandas据我所知,有一个只有绘制平日数据的内置方式。但是,如this matplotlib example所示,自定义刻度格式可以通过某种冒险的方式人为跳过周末。

主要想法是按顺序重新索引您的数据(以便没有空白),然后根据您知道它应该是的日期范围手动设置xticks。 matplotlib烛台图有点特殊*,因此不能简单地将其引入与上面相关的示例。相反,我写了下面的帮助函数来跳过丢失的数据更易于管理。

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc 


def weekday_candlestick(ohlc_data, ax, fmt='%b %d', freq=7, **kwargs): 
    """ Wrapper function for matplotlib.finance.candlestick_ohlc 
     that artificially spaces data to avoid gaps from weekends """ 

    # Convert data to numpy array 
    ohlc_data_arr = np.array(ohlc_data) 
    ohlc_data_arr2 = np.hstack(
     [np.arange(ohlc_data_arr[:,0].size)[:,np.newaxis], ohlc_data_arr[:,1:]]) 
    ndays = ohlc_data_arr2[:,0] # array([0, 1, 2, ... n-2, n-1, n]) 

    # Convert matplotlib date numbers to strings based on `fmt` 
    dates = mdates.num2date(ohlc_data_arr[:,0]) 
    date_strings = [] 
    for date in dates: 
     date_strings.append(date.strftime(fmt)) 

    # Plot candlestick chart 
    candlestick_ohlc(ax, ohlc_data_arr2, **kwargs) 

    # Format x axis 
    ax.set_xticks(ndays[::freq]) 
    ax.set_xticklabels(date_strings[::freq], rotation=45, ha='right') 
    ax.set_xlim(ndays.min(), ndays.max()) 

    plt.show() 

下面是上述函数的几个用例。

# Get data using quotes_historical_yahoo_ohlc 
date1, date2 = [(2006, 6, 1), (2006, 8, 1)] 
date3, date4 = [(2006, 5, 15), (2008, 4, 1)] 
data_1 = quotes_historical_yahoo_ohlc('INTC', date1, date2) 
data_2 = quotes_historical_yahoo_ohlc('INTC', date3, date4) 

# Create figure with 2 axes 
fig, axes = plt.subplots(ncols=2, figsize=(14, 6)) 

weekday_candlestick(data_1, ax=axes[0], fmt='%b %d', freq=3, width=0.5) 
weekday_candlestick(data_2, ax=axes[1], fmt='%b %d %Y', freq=30) 

# Set the plot titles 
axes[0].set_title('Shorter Range Stock Prices') 
axes[1].set_title('Longer Range Stock Prices') 

运行时,它会产生下图(没有周末间隙)。

enter image description here

*这需要一个元组列表 - 时间,开放,高,低,并关闭值,这是相当独特的。