mpl_finance 烛台中的未知错误。该怎么办?

Unknown error in mpl_finance candlestick. What to do?

请原谅我的无知,我环顾四周,找不到我的问题的答案。任何和所有建议将不胜感激 我正在尝试从 API 打印 OHLC 烛台数据,但出现以下错误:

Traceback (most recent call last):
  File "test5.py", line 53, in <module>
    candlestick_ohlc(ax1,ohlc_df.values,width=1, colorup='g', colordown='k',alpha=0.75)
  File "/Users/MBP/Python_world/py_env1/lib/python3.6/site-packages/mpl_finance.py", line 731, in candlestick_ohlc
    alpha=alpha, ochl=False)
  File "/Users/MBP/Python_world/py_env1/lib/python3.6/site-packages/mpl_finance.py", line 784, in _candlestick
    height = close - open
TypeError: unsupported operand type(s) for -: 'str' and 'str'

这是我的代码:

import requests
import json
import pandas as pd
import matplotlib
import numpy as np
from mpl_finance import candlestick_ohlc
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import datetime as datetime


# Get OHLC data from kraken api [time,open,high,low,close,vwap,volume,count]

ticker='XXBTZEUR'   
period='5'      
starting='1505677500'

parameters={"pair":ticker,"interval":period,"since":starting}
response=requests.get("https://api.kraken.com/0/public/OHLC", params=parameters)
krakohlc=response.json()['result'][ticker]

ohlc=[]

for i in range(len(krakohlc)):
ohlcdata=krakohlc[i][0:5]
ohlc.append(ohlcdata)       #Make data array (time,O,H,L,C)


labels = ['Date', 'Open', 'High', 'Low', 'Close']
ohlc_df=pd.DataFrame.from_records(ohlc, columns=labels)


print(ohlc_df)

#Making plot area
fig = plt.figure()
ax1 = plt.subplot2grid((6,1), (0,0), rowspan=6, colspan=1)


#Making candlestick plot
candlestick_ohlc(ax1,ohlc_df.values,width=1, colorup='g', colordown='k',alpha=0.75)
ax1.xaxis_date()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax1.grid(True)

plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.show()

我想这里有几个问题。第一个也产生错误,是数据是字符串,而不是数字。

# cast data to float
ohlc_df = ohlc_df.astype(float) 

然后为了使用 matplotlib 绘图,还需要将时间戳转换为 matplotlib 可以识别为日期的格式。这可以作为

# convert timestamp column to matplotlib date numbers
f = lambda x: mdates.date2num(datetime.datetime.fromtimestamp(x))
ohlc_df[labels[0]] = ohlc_df[labels[0]].apply(f)

最后蜡烛的宽度不应该是一天,而是连续日期时间值之间的大致差异,在本例中为 5 分钟,

candlestick_ohlc(ax1,ohlc_df.values,width=1./(24*60)*5)

完整示例:

import requests
import pandas as pd
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import datetime as datetime

# Get OHLC data from kraken api [time,open,high,low,close,vwap,volume,count]
ticker='XXBTZEUR'   
period='5'      
starting='1505677500'

parameters={"pair":ticker,"interval":period,"since":starting}
response=requests.get("https://api.kraken.com/0/public/OHLC", params=parameters)
krakohlc=response.json()['result'][ticker]

ohlc=[]

for i in range(len(krakohlc)):
    ohlcdata=krakohlc[i][0:5]
    ohlc.append(ohlcdata)       #Make data array (time,O,H,L,C)

labels = ['Date', 'Open', 'High', 'Low', 'Close']
ohlc_df=pd.DataFrame.from_records(ohlc, columns=labels)
# cast data to float
ohlc_df = ohlc_df.astype(float)
# convert timestamp column to matplotlib date numbers
f = lambda x: mdates.date2num(datetime.datetime.fromtimestamp(x))
ohlc_df[labels[0]] = ohlc_df[labels[0]].apply(f)

#Making plot area
fig = plt.figure()
ax1 = plt.subplot2grid((6,1), (0,0), rowspan=6, colspan=1)

#Making candlestick plot
width = 1./(24*60)*5  # make candles 5 minutes wide
candlestick_ohlc(ax1,ohlc_df.values,width=width, colorup='g', colordown='k',alpha=0.75)
ax1.xaxis_date()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax1.xaxis.set_major_locator(mdates.HourLocator(byhour=[0,12]))
fig.autofmt_xdate()
ax1.grid(True)

plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.show()