烛台 - 使用带日期的刻度标签

时间:2021-01-21 12:39:18

Well, I am having a hard time understanding the conversion of dates when using the function candlestick_ohlc. I can print a chart with the dates, but in a weird format.

好吧,在使用函数candlestick_ohlc时,我很难理解日期的转换。我可以用日期打印图表,但格式很奇怪。

烛台 - 使用带日期的刻度标签

When I try to use the function

当我尝试使用该功能时

ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

I get the following error:

我收到以下错误:

ValueError: year 4172023 is out of range

Here it follows the code I am using:

这是我使用的代码:

%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&currencyPair='
    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()

.........................................................................

1 个解决方案

#1


0  

In order to convert timestamps to numeric matplotlib dates you may e.g. use

为了将时间戳转换为数字matplotlib日期,您可以例如使用

data.date = date2num([dt.datetime.fromtimestamp(d) for d in data.date])

Next you would need to bring your data in the correct format for ohlc to understand it,

接下来,您需要以正确的格式提供数据,以便了解它,

ohlc = list(zip(date, opens, highs, lows, closes, volume))

Next you need to use a valid datetime formatter, e.g.

接下来,您需要使用有效的日期时间格式器,例如

ax2.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m %H'))

Finally you need to adjust the width of your candles to something useful, e.g. width=1./24 to make them one hour wide.

最后,你需要将蜡烛的宽度调整为有用的东西,例如:宽度= 1. / 24使它们宽一小时。

#1


0  

In order to convert timestamps to numeric matplotlib dates you may e.g. use

为了将时间戳转换为数字matplotlib日期,您可以例如使用

data.date = date2num([dt.datetime.fromtimestamp(d) for d in data.date])

Next you would need to bring your data in the correct format for ohlc to understand it,

接下来,您需要以正确的格式提供数据,以便了解它,

ohlc = list(zip(date, opens, highs, lows, closes, volume))

Next you need to use a valid datetime formatter, e.g.

接下来,您需要使用有效的日期时间格式器,例如

ax2.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m %H'))

Finally you need to adjust the width of your candles to something useful, e.g. width=1./24 to make them one hour wide.

最后,你需要将蜡烛的宽度调整为有用的东西,例如:宽度= 1. / 24使它们宽一小时。