我想用matplotlib.finance中的candlestick_ohlc函数在python中绘制OHLC-candles。
我有一个像这样的数据帧:
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
将“打开,高,低,关闭”转换为列表列表:
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'
任何帮助?
提前谢谢
答案 0 :(得分:0)
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()