2017-02-10 110 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

*這需要一個元組列表 - 時間,開放,高,低,並關閉值,這是相當獨特的。