如何使用 mplfinance candlestick_ohlc 在 matplotlib 中用日期时间绘制 ohlc 烛台?
How to plot ohlc candlestick with datetime in matplotlib using mplfinance candlestick_ohlc?
我正在尝试绘制 5 分钟的历史烛台,但我遇到了这些问题:
使用每日烛台数据执行此操作会显示正确的结果:1-day chart
但是 5m 看起来像这样:5 minutes chart
df['date'] = pd.to_datetime(df['date'])
df['date'] = df['date'].apply(mpl_dates.date2num)
df = df.astype(float)
plt.style.use('dark_background')
levels = self.getLevels()
ax = plt.subplot2grid((1, 1), (0, 0), rowspan=6, colspan=4)
candlestick_ohlc(ax,df.values,width=0.4, \
colorup='green', colordown='red', alpha=1.0)
#ax.grid(True)
# Setting labels
ax.set_xlabel('Date')
ax.set_ylabel('Price')
# Formatting Date
date_format = mpl_dates.DateFormatter("%d/%m/%y %H:%M")
ax.xaxis_date()
ax.xaxis.set_major_formatter(date_format)
#fig.autofmt_xdate()
#fig.tight_layout()
plt.xticks(rotation=90)
for level in levels:
plt.hlines(level[1],xmin=df['date'][level[0]],\
xmax=max(df['date']),colors='blue')
plt.show()
我 运行 你的代码,但它没有按预期工作。目前 mpl_finance 已弃用,建议使用 mplfinance。 mplfinance 具有绘制趋势线等功能,并且可以绘制部分水平线。画断线,把起点和终点放在一个列表里处理。在我的示例中,我列出了起始价和最高价并将它们设置为直线。详情请参考此页explanation。
import mplfinance as mpf
import matplotlib.pyplot as plt
import yfinance as yf
import pandas as pd
df = yf.download("AAPL", start="2021-10-25", end="2021-10-29", interval='5m', progress=False)
df.index = pd.to_datetime(df.index)
df.index = df.index.tz_localize(None)
df = df[:200] # Limit data to emphasize the lines in the graph.
o_lines = []
m_lines = []
for c in df.columns[:4]:
if c == 'Open':
idx, price1, end, price2 = df[c].head(1).index[0], df[c].head(1)[0], df[c].tail(1).index[0], df[c].head(1)[0]
o_lines.append((idx, price1))
o_lines.append((end, price2))
if c == 'High':
idx, price1, end, price2 = df.loc[df[c].idxmax()].name, df.loc[df[c].idxmax()][c], df[c].tail(1).index[0], df.loc[df[c].idxmax()][c]
m_lines.append((idx, price1))
m_lines.append((end, price2))
# print(m_lines)
mpf.plot(df, type='candle', alines=dict(alines=[o_lines, m_lines], colors=['b','r'], linewidths=2, alpha=0.4), style='yahoo')
lines = []
for level in levels:
idx, price1, end, price2 = ohlc['date'][level[0]], level[1], max(ohlc['date']),level[1]
lines.append((idx, price1,end, price2))
print(lines)
mpf.plot(ohlc, type='candle',alines=dict(alines=lines,colors = 'y',linewidths=2, alpha=0.3), volume=True,panel_ratios=(4,1),addplot=indicators)
(
Timestamp("2021-10-01 20:15:00+0000", tz="UTC"),
31.58,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
31.58,
),
(
Timestamp("2021-10-01 22:15:00+0000", tz="UTC"),
32.29,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
32.29,
),
(
Timestamp("2021-10-02 01:15:00+0000", tz="UTC"),
32.72,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
32.72,
),
(
Timestamp("2021-10-02 02:00:00+0000", tz="UTC"),
32.0,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
32.0,
),
(
Timestamp("2021-10-02 22:15:00+0000", tz="UTC"),
33.02,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
33.02,
),
]
我正在尝试绘制 5 分钟的历史烛台,但我遇到了这些问题: 使用每日烛台数据执行此操作会显示正确的结果:1-day chart 但是 5m 看起来像这样:5 minutes chart
df['date'] = pd.to_datetime(df['date'])
df['date'] = df['date'].apply(mpl_dates.date2num)
df = df.astype(float)
plt.style.use('dark_background')
levels = self.getLevels()
ax = plt.subplot2grid((1, 1), (0, 0), rowspan=6, colspan=4)
candlestick_ohlc(ax,df.values,width=0.4, \
colorup='green', colordown='red', alpha=1.0)
#ax.grid(True)
# Setting labels
ax.set_xlabel('Date')
ax.set_ylabel('Price')
# Formatting Date
date_format = mpl_dates.DateFormatter("%d/%m/%y %H:%M")
ax.xaxis_date()
ax.xaxis.set_major_formatter(date_format)
#fig.autofmt_xdate()
#fig.tight_layout()
plt.xticks(rotation=90)
for level in levels:
plt.hlines(level[1],xmin=df['date'][level[0]],\
xmax=max(df['date']),colors='blue')
plt.show()
我 运行 你的代码,但它没有按预期工作。目前 mpl_finance 已弃用,建议使用 mplfinance。 mplfinance 具有绘制趋势线等功能,并且可以绘制部分水平线。画断线,把起点和终点放在一个列表里处理。在我的示例中,我列出了起始价和最高价并将它们设置为直线。详情请参考此页explanation。
import mplfinance as mpf
import matplotlib.pyplot as plt
import yfinance as yf
import pandas as pd
df = yf.download("AAPL", start="2021-10-25", end="2021-10-29", interval='5m', progress=False)
df.index = pd.to_datetime(df.index)
df.index = df.index.tz_localize(None)
df = df[:200] # Limit data to emphasize the lines in the graph.
o_lines = []
m_lines = []
for c in df.columns[:4]:
if c == 'Open':
idx, price1, end, price2 = df[c].head(1).index[0], df[c].head(1)[0], df[c].tail(1).index[0], df[c].head(1)[0]
o_lines.append((idx, price1))
o_lines.append((end, price2))
if c == 'High':
idx, price1, end, price2 = df.loc[df[c].idxmax()].name, df.loc[df[c].idxmax()][c], df[c].tail(1).index[0], df.loc[df[c].idxmax()][c]
m_lines.append((idx, price1))
m_lines.append((end, price2))
# print(m_lines)
mpf.plot(df, type='candle', alines=dict(alines=[o_lines, m_lines], colors=['b','r'], linewidths=2, alpha=0.4), style='yahoo')
lines = []
for level in levels:
idx, price1, end, price2 = ohlc['date'][level[0]], level[1], max(ohlc['date']),level[1]
lines.append((idx, price1,end, price2))
print(lines)
mpf.plot(ohlc, type='candle',alines=dict(alines=lines,colors = 'y',linewidths=2, alpha=0.3), volume=True,panel_ratios=(4,1),addplot=indicators)
(
Timestamp("2021-10-01 20:15:00+0000", tz="UTC"),
31.58,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
31.58,
),
(
Timestamp("2021-10-01 22:15:00+0000", tz="UTC"),
32.29,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
32.29,
),
(
Timestamp("2021-10-02 01:15:00+0000", tz="UTC"),
32.72,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
32.72,
),
(
Timestamp("2021-10-02 02:00:00+0000", tz="UTC"),
32.0,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
32.0,
),
(
Timestamp("2021-10-02 22:15:00+0000", tz="UTC"),
33.02,
Timestamp("2021-10-03 21:00:00+0000", tz="UTC"),
33.02,
),
]