如何在Python中使用Matplotlib创建一个烛台图

945 阅读2分钟

蜡烛图是一种金融图表,显示证券在一段时间内的价格变动。

下面的例子展示了如何使用Python中的Matplotlib可视化库来创建一个蜡烛图。

例子:在Python中创建一个烛台图

假设我们有下面这个pandas数据框架,它显示了某只股票在8天内的开盘、收盘、最高价和最低价。

import pandas as pd

#create DataFrame
prices = pd.DataFrame({'open': [25, 22, 21, 19, 23, 21, 25, 29],
                       'close': [24, 20, 17, 23, 22, 25, 29, 31],
                       'high': [28, 27, 29, 25, 24, 26, 31, 37],
                       'low': [22, 16, 14, 17, 19, 18, 22, 26]},
                       index=pd.date_range("2021-01-01", periods=8, freq="d"))

#display DataFrame
print(prices)

            open  close  high  low
2021-01-01    25     24    28   22
2021-01-02    22     20    27   16
2021-01-03    21     17    29   14
2021-01-04    19     23    25   17
2021-01-05    23     22    24   19
2021-01-06    21     25    26   18
2021-01-07    25     29    31   22
2021-01-08    29     31    37   26

我们可以使用下面的代码来创建一个蜡烛图,以显示这只股票在这8天内的价格变动。

import matplotlib.pyplot as plt

#create figure
plt.figure()

#define width of candlestick elements
width = .4
width2 = .05

#define up and down prices
up = prices[prices.close>=prices.open]
down = prices[prices.close<prices.open]

#define colors to use
col1 = 'green'
col2 = 'red'

#plot up prices
plt.bar(up.index,up.close-up.open,width,bottom=up.open,color=col1)
plt.bar(up.index,up.high-up.close,width2,bottom=up.close,color=col1)
plt.bar(up.index,up.low-up.open,width2,bottom=up.open,color=col1)

#plot down prices
plt.bar(down.index,down.close-down.open,width,bottom=down.open,color=col2)
plt.bar(down.index,down.high-down.open,width2,bottom=down.open,color=col2)
plt.bar(down.index,down.low-down.close,width2,bottom=down.close,color=col2)

#rotate x-axis tick labels
plt.xticks(rotation=45, ha='right')

#display candlestick chart
plt.show()

Candlestick chart using matplotlib in Python

每个蜡烛图代表了该证券在某一天的价格变动。蜡烛图的颜色告诉我们,价格收盘时是比前一天高(绿色)还是低(红色)。

你可以随意改变蜡烛图的宽度和颜色,使图表以你喜欢的方式出现。

例如,我们可以使蜡烛更细,用不同的颜色来代表 "上涨 "和 "下跌 "的日子。

import matplotlib.pyplot as plt

#create figure
plt.figure()

#define width of candlestick elements
width = .2
width2 = .02

#define up and down prices
up = prices[prices.close>=prices.open]
down = prices[prices.close<prices.open]

#define colors to use
col1 = 'black'
col2 = 'steelblue'

#plot up prices
plt.bar(up.index,up.close-up.open,width,bottom=up.open,color=col1)
plt.bar(up.index,up.high-up.close,width2,bottom=up.close,color=col1)
plt.bar(up.index,up.low-up.open,width2,bottom=up.open,color=col1)

#plot down prices
plt.bar(down.index,down.close-down.open,width,bottom=down.open,color=col2)
plt.bar(down.index,down.high-down.open,width2,bottom=down.open,color=col2)
plt.bar(down.index,down.low-down.close,width2,bottom=down.close,color=col2)

#rotate x-axis tick labels
plt.xticks(rotation=45, ha='right')

#display candlestick chart
plt.show()

其他资源

下面的教程解释了如何在Python中创建其他常见的图表:

如何在一个图中创建多个Matplotlib图
如何在Python中从数据列表中绘制直方图
如何在Python中按组创建Boxplots图