请原谅我的无知,我已经环顾四周,无法找到问题的答案。任何和所有建议将不胜感激 我试图从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()
答案 0 :(得分:0)
我想这里有几个问题。第一个也产生错误的是数据是字符串,而不是数字。
# 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()