【发布时间】:2018-05-01 14:21:24
【问题描述】:
嗯,我很难理解使用函数烛台_ohlc 时的日期转换。我可以打印带有日期的图表,但格式很奇怪。
当我尝试使用该功能时
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
我收到以下错误:
ValueError: year 4172023 is out of range
这里是我使用的代码:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
from matplotlib.dates import date2num
from matplotlib.finance import candlestick_ohlc
import numpy as np
import requests
import time
import pandas as pd
import datetime as dt
def getNow(pair):
return requests.get('https://poloniex.com/public?command=returnTicker').json()[pair]
def getPast(pair, period, daysBack, daysData):
now = int(time.time())
end = now-(24*60*60*daysBack)
start = end-(24*60*60*daysData)
base = 'https://poloniex.com/public?command=returnChartData¤cyPair='
response = requests.get('{0}{1}&start={2}&end={3}&period={4}'.format(base, pair, start, end, period))
return response.json()
pair = "USDT_BTC" # Use ETH pricing data on the BTC market
period = 7200 # Use 7200 second candles
daysBack = 0 # Grab data starting 0 days ago
daysData = 15 # From there collect 15 days of data
# Request data from Poloniex
data = getPast(pair, period, daysBack, daysData)
# Convert to Pandas dataframe with datetime format
data = pd.DataFrame(data)
#Convert dates do float for matplotlib
data.date = data.date.astype(float)
#Define ohlc
date, closes, highs, lows, opens, volume = data['date'], data['close'], data['high'],data['low'], data['open'], data['volume']
ohlc = [date, opens, highs, lows, closes, volume]
ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1)
#ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1, sharex=ax1)
plt.xlabel('Date')
ax2v = ax2.twinx()
#Customize the grid
ax2.grid(True, color='k', linestyle='--', linewidth=0.5)
#Rotate the axis ticklabels
for label in ax2.xaxis.get_ticklabels():
label.set_rotation(45)
#Format the dates in the label
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%d%h'))
labels = ax2.get_xticklabels()
#Plot candlestick chart in the figure and set title, xlabel and ylabel
candlestick_ohlc(ax2, ohlc, colorup='#77d879', colordown='#db3f3f', width = 1)
ax2.set_title(pair+'\n')
ax2.set_xlabel('Date')
ax2.set_ylabel('Price')
plt.show()
.................................................. …………
【问题讨论】:
-
1523894400是什么日期或时间格式? -
>> type(date[1]) >> float
-
来自文档:'时间必须采用浮点天数格式 - 参见 date2num'
-
matplotlib 理解的数字日期是 自 0001-01-01 UTC 以来的天数加上 1。这意味着例如今天,2018 年 5 月 1 日是号码
736815。但是1523894400是什么?您希望它对应于哪个日期? -
这是 unix 时间戳:时间戳 1523894400 表示:在您的本地时区:2018 年 4 月 16 日星期一 01:00:00 PM UTC:2018 年 4 月 16 日星期一 04:00:00 PM
标签: python python-3.x date matplotlib