如何使用Matplotlib(Python 2.7)和您自己的d创建烛台图表

2024-04-20 12:20:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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))] 

为了得到一个烛台图(也就是说,列表中的每个元素都在创建一个烛台图),我应该为这两个数据点编写什么代码?当然,我可以操作数据(例如要在浮动日中转换的日期字符串等),但我无法获得创建图表的简单命令。有人能帮忙吗?


Tags: 数据代码类型列表closematplotlib图表open
1条回答
网友
1楼 · 发布于 2024-04-20 12:20:57

在matplotlibexample之后,我得到了以下解决方案:

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()

相关问题 更多 >