python - 使用 matplotlib.finance 中的 candlestick_ohlc 函数在 python 中绘制 OHLC 蜡烛
问题描述
我想用 matplotlib.finance 中的烛台_ohlc 函数在 python 中绘制 OHLC 蜡烛。
我有一个这样的数据框:
Open High Low Close Volume Market Cap
Date
2018-04-09 7044.32 7178.11 6661.99 6770.73 4894060000 119516000000
2018-04-08 6919.98 7111.56 6919.98 7023.52 3652500000 117392000000
2018-04-07 6630.51 7050.54 6630.51 6911.09 3976610000 112467000000
2018-04-06 6815.96 6857.49 6575.00 6636.32 3766810000 115601000000
2018-04-05 6848.65 6933.82 6644.80 6811.47 5639320000 116142000000
将 'Open,High,Low,Close' 转换为列表列表:
ohlc =
[['2018-04-09', 7044.32, 7178.11, 6661.99, 6770.73],
['2018-04-08', 6919.98, 7111.56, 6919.98, 7023.52],
['2018-04-07', 6630.51, 7050.54, 6630.51, 6911.09],
['2018-04-06', 6815.96, 6857.49, 6575.0, 6636.32],
['2018-04-05', 6848.65, 6933.82, 6644.8, 6811.47]]
尝试绘制:
from matplotlib.finance import candlestick_ohlc
fig, ax = plt.subplots(nrows=2, ncols=2,sharex=True,figsize=(30,20))
candlestick_ohlc(ax[1,0],ohlc,width=0.6)
TypeError: 不支持的操作数类型 -: 'str' 和 'float'
将日期字符串转换为元组:
ohlc=
[[(2018, 4, 9), 7044.32, 7178.11, 6661.99, 6770.73],
[(2018, 4, 8), 6919.98, 7111.56, 6919.98, 7023.52],
[(2018, 4, 7), 6630.51, 7050.54, 6630.51, 6911.09],
[(2018, 4, 6), 6815.96, 6857.49, 6575.0, 6636.32],
[(2018, 4, 5), 6848.65, 6933.82, 6644.8, 6811.47]]
TypeError: unsupported operand type(s) for -: 'tuple' and 'float'
有什么帮助吗?
提前谢谢
解决方案
该candlestick_ohlc
函数需要特殊的日期输入,实际上是数字。您可以通过将mdates.date2num
函数应用于日期来获取它,然后通过操纵绘图的轴来格式化这些数字。
import pandas as pd
from matplotlib.finance import candlestick_ohlc
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas_datareader.data as web
import datetime
# creating dates
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2013, 1, 27)
# download data from morningstar
f = web.DataReader('AAPL', 'morningstar', start, end)
# remove the multilevel index structure
f.reset_index(level=['Symbol', 'Date'], inplace=True)
# change the dates into numbers so that the candlestick function can accept it
f['Date'] = f.index.map(mdates.date2num)
ohlc = f[['Date', 'Open', 'High', 'Low', 'Close']]
f1, ax = plt.subplots(figsize = (10,5))
candlestick_ohlc(ax, ohlc.values.tolist(), width=.6, colorup='green', colordown='red')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.show()
推荐阅读
- tensorflow - 如何解决 Tensorflow 2 对象检测 API 中的 UnicodeError
- node.js - 如何使用 Nodejs 和 Mandrill 向许多内容不同的人发送电子邮件
- python - element_to_be_clickable 给出 TimeoutException
- groovy - Katalon Studio中基于自定义关键字的下拉选择
- python - 为什么此错误来自以下代码?
- git - 合并不相关的分支分支从 SVN 到 Git 转换
- android - 使用命令行使用 Google 的上传密钥证书签署捆绑包
- python - 屏幕锁定时使用 Selenium Python 将文件上传到 Sharepoint
- asp.net-core - Microsoft.AspNetCore.OData v8.0.2 不区分大小写的字段名称
- autodesk-forge - 我想在不丢失默认 3d 控件的情况下修复滚动