在烛台图表

时间:2017-07-19 19:34:07

标签: python python-3.x pandas numpy matplotlib

我使用pandas.DataFrame.rolling计算了移动平均线。所以我的Dataframe看起来像这样,

   CurrencyPair           TimeStamp    Open    High     Low   Close      MA50
40       EURUSD 2017-07-10 16:00:00  1.1397  1.1401  1.1396  1.1397       NaN
41       EURUSD 2017-07-10 15:00:00  1.1389  1.1396  1.1386  1.1396       NaN
42       EURUSD 2017-07-10 14:00:00  1.1393  1.1396  1.1389  1.1390       NaN
43       EURUSD 2017-07-10 13:00:00  1.1393  1.1394  1.1387  1.1391       NaN
44       EURUSD 2017-07-10 12:00:00  1.1390  1.1395  1.1386  1.1392       NaN
45       EURUSD 2017-07-10 11:00:00  1.1392  1.1393  1.1384  1.1390       NaN
46       EURUSD 2017-07-10 10:00:00  1.1387  1.1395  1.1385  1.1395       NaN
47       EURUSD 2017-07-10 09:00:00  1.1397  1.1398  1.1387  1.1389       NaN
48       EURUSD 2017-07-10 08:00:00  1.1417  1.1418  1.1399  1.1403       NaN
49       EURUSD 2017-07-10 07:00:00  1.1400  1.1416  1.1400  1.1416  1.142272
50       EURUSD 2017-07-10 06:00:00  1.1410  1.1411  1.1399  1.1399  1.142154
51       EURUSD 2017-07-10 05:00:00  1.1405  1.1409  1.1404  1.1409  1.142068
52       EURUSD 2017-07-10 04:00:00  1.1406  1.1407  1.1402  1.1404  1.141952
53       EURUSD 2017-07-10 03:00:00  1.1406  1.1407  1.1403  1.1406  1.141804

我设法使用来自TimeStampOHLC的数据来绘制烛台图表,但我不确定如何在烛台图表上使用相同的轴绘制我的移动平均线。我尝试使用eurusd['MA50'].plot(ax = ax),但收到错误ValueError: ordinal must be >= 1

这是我的代码,

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
from mpl_finance import candlestick_ohlc

eurusd = pd.read_csv('fxhistoricaldata_EURUSD_hour.csv')
eurusd['TimeStamp'] = pd.to_datetime(eurusd['TimeStamp'], format = '%d/%m/%Y %H:%M')

# Set date & time range
# start_date (Y-m-d H-M) & end_date (Y-m-d H-M)
mask = (eurusd['TimeStamp'] >= '2017-07-10 3:00') & (eurusd['TimeStamp'] <= '2017-07-12 8:00')
eurusd = eurusd.loc[mask]

# Calculate Moving Averages MA50 
eurusd = eurusd.reindex(columns = np.append(eurusd.columns, ['MA50']))
eurusd['MA50'] = eurusd[['Close']].rolling(50).mean()

print(eurusd)

eurusd['TimeStamp'] = eurusd['TimeStamp'].map(lambda d: mdates.datestr2num(dt.datetime.strftime(d, '%Y-%m-%d %H:%M')))

fig, ax = plt.subplots()
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d %H:%M'))
ax.grid(True, color = 'k', alpha = 0.5)
plt.xticks(rotation = 45)
plt.xlabel("Date")
plt.ylabel("Price")
plt.title("EUR/USD")

candlestick_ohlc(ax, eurusd[['TimeStamp','Open','High','Low','Close']].values, width = 0.01, colorup = 'g')
eurusd['MA50'].plot(ax = ax)

plt.show()

这是完整的错误日志,

    ticks = self.get_major_ticks()
  File "C:\Users\Meng Da\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\matplotlib\axis.py", line 1320, in get_major_ticks
    numticks = len(self.get_major_locator()())
  File "C:\Users\Meng Da\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\matplotlib\dates.py", line 986, in __call__
    self.refresh()
  File "C:\Users\Meng Da\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\matplotlib\dates.py", line 1006, in refresh
    dmin, dmax = self.viewlim_to_dt()
  File "C:\Users\Meng Da\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\matplotlib\dates.py", line 763, in viewlim_to_dt
    return num2date(vmin, self.tz), num2date(vmax, self.tz)
  File "C:\Users\Meng Da\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\matplotlib\dates.py", line 401, in num2date
     return _from_ordinalf(x, tz)
  File "C:\Users\Meng Da\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\matplotlib\dates.py", line 254, in _from_ordinalf
    dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
ValueError: ordinal must be >= 1

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

好像你有斧头的问题。你究竟想通过subplot2grid实现什么目标?如果你删除它然后它开箱即用。请注意,我使用了candlestick2_ohlc。您还需要添加日期,我相信您已经知道了这些日期。enter image description here

from pandas_datareader import data
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc

aapl = data.DataReader('AAPL', 'google', '2017-06-01')
aapl['MA50'] = aapl["High"].rolling(10).mean()
aapl.reset_index(inplace=True)

fig, ax = plt.subplots()
plt.xticks(rotation = 45)
plt.xlabel("Date")
plt.ylabel("Price")
plt.title("EUR/USD")

candlestick2_ohlc(ax, aapl.Open, aapl.High, aapl.Low, aapl.Close, width=1, colorup='g')
aapl.MA50.plot(ax=ax)

plt.show()

答案 1 :(得分:1)

我设法使用ax.plot(eurusd['TimeStamp'], eurusd['MA50'])来解决问题。以防任何人遇到类似的问题。