lan*_*ery 2 python matplotlib candlestick-chart
当在中绘制烛台图时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)
Run Code Online (Sandbox Code Playgroud)
周末差距由绿色箭头显示。
不幸的是,据我所知,也matplotlib没有pandas一种仅绘制工作日数据的内置方法。但是,如此matplotlib示例所示,可以完成自定义刻度格式,以一种怪诞的方式人为地跳过周末。
主要思想是按顺序对数据重新索引(以便没有间隙),然后根据您知道它应该是的日期范围手动设置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()
Run Code Online (Sandbox Code Playgroud)
这是上述功能的几个用例。
# 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')
Run Code Online (Sandbox Code Playgroud)
运行时,将产生以下图表(无周末空白)。
*它包含一个元组列表-时间,开盘价,高价,低价和收盘价,这是非常独特的。
| 归档时间: |
|
| 查看次数: |
2973 次 |
| 最近记录: |