问题
I am trying to plot a candlestick chart using matplotplib. I have queried my database, returned the relevant data and appended in to an anrray named candleAr, in the required format (date,open,close,high,low)
My code is as follows:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
from matplotlib.finance import candlestick
candleAr=[]
cursor = conx.cursor()
query= 'SELECT ticker,date,time,open,low,high,close FROM eurusd WHERE date > "2013-02-28"'
cursor.execute(query)
for line in cursor:
#appendLine in correct format for candlesticks - date,open,close,high,low
appendLine = line[1],line[3],line[6],line[5],line[4]
candleAr.append(appendLine)
fig = plt.figure()
ax1 = plt.subplot(1,1,1)
candlestick(ax1, candleAr, width=1, colorup='g', colordown='r')
ax1.grid(True)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
However I am getting the following error message:
Traceback (most recent call last):
File "C:\Users\Stuart\Desktop\Python Programming\Apache\Liclipse\Andres-Apache\FX\fx2.py", line 53, in <module>
candlestick(ax1, candleAr, width=1, colorup='g', colordown='r')
File "C:\Users\Stuart\AppData\Local\Enthought\Canopy32\User\lib\site-packages\matplotlib\finance.py", line 359, in candlestick
xy = (t-OFFSET, lower),
TypeError: unsupported operand type(s) for -: 'datetime.date' and 'float'
When I print out my candleAr, I get the following (I have just included the first couple of results for an example):
[(datetime.date(2013, 3, 1), 1.306, 1.305, 1.306, 1.305), (datetime.date(2013, 3, 1), 1.305, 1.306, 1.306, 1.305)
So there are the datetime and floats relating to the error message no doubt, but surely the candlestick import from matplotlib can handle datetimes and floats - I mean what else can be passed to it to build a chart related to prices and dates, if not dates/datetimes and floats!??
Would anyone be able to point out what i am doing wrong?
回答1:
Matplotlib uses floating point numbers representing ordinals (counting days from 0001-01-01), with decimals representing fractions of a day.
This is documented in the candlestick docstring:
time must be in
float
days format - seedate2num
The matplotlib.dates module gives you tools to convert datetime
objects to such numbers:
>>> from datetime import date
>>> from matplotlib.dates import date2num
>>> date2num(date(2013, 3, 1))
734928.0
For your code that looks like:
from matplotlib.dates import date2num
appendLine = date2num(line[1]), line[3], line[6], line[5], line[4]
For datetime.date()
this basically comes down to datetime.date.toordinal()
as a float instead of an integer.
来源:https://stackoverflow.com/questions/25224244/matplotlib-candlestick-chart-error-xy-t-offset-lower-typeerror-unsupporte