我想在Matplotlib上创建一个烛台图表。我在网上找到了很多例子,但到目前为止,他们都使用与雅虎财务或其他类型的数据的连接,而没有解释如何获得相同的结果,当你有一个包含日期,开放,元组的元组列表关闭,价格高低。实际上,通常情况下,您已经拥有历史值或估计值,或者更多,您通常不希望使用来自Yahoo Finance等提供商的数字。我想知道的是使用您自己的值列表创建烛台图表这样的基本代码。假设我有一个元组列表,包含我需要两天的所有数据:
Prices = [('01/01/2010', 1.123 (open), 1.212 (close), 1.463 (high), 1.056(low)),
('02/01/2010', 1.121 (open), 1.216 (close), 1.498 (high), 1.002(low))]
我应该准确地编码以获得烛台图(这意味着列表“价格”的每个元素都在创建一个烛台)这两个数据点?我当然可以操纵数据(例如在浮动日等转换的日期字符串等),但我无法获得创建图表的简单命令。有人可以帮忙吗?
答案 0 :(得分:5)
在matplotlib example之后,我得到了以下解决方案:
from pylab import *
import matplotlib.pyplot as plt
from datetime import datetime
import time
from matplotlib.dates import DateFormatter, WeekdayLocator, HourLocator, \
DayLocator, MONDAY
from matplotlib.finance import candlestick,\
plot_day_summary, candlestick2
mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
alldays = DayLocator() # minor ticks on the days
weekFormatter = DateFormatter('%b %d') # e.g., Jan 12
dayFormatter = DateFormatter('%d') # e.g., 12
#starting from dates expressed as strings...
Date1 = '01/01/2010'
Date2 = '02/01/2010'
#...you convert them in float numbers....
Date1 = date2num(datetime.strptime(Date1, "%d/%m/%Y"))
Date2 = date2num(datetime.strptime(Date2, "%d/%m/%Y"))
#so redefining the Prices list of tuples...
Prices = [(Date1, 1.123, 1.212, 1.463, 1.056), (Date2,1.121, 1.216, 1.498, 1.002)]
#and then following the official example.
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
candlestick(ax, Prices, width=0.6)
ax.xaxis_date()
ax.autoscale_view()
plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
plt.show()