ValueError:年份超出范围(使用matplotlib.pyplot)

时间:2019-06-10 05:26:52

标签: python-3.x matplotlib

在我调用Candlestick_ohlc之后,我似乎无法将x轴日期转换为matplotlib可以理解的内容。

我是一名菜鸟Python程序员。我尝试过将数据框变成列表,尝试过将日期传递到Candlestick_ohlc,除了更改以外,似乎没有任何作用

 df['time'] = (df['time'].astype('float')) 

进入

df['time'] = (df['time'].astype('float')\1000) 

尽管这会显示错误的日期时间。

import requests
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdate
import matplotlib.style as style
import matplotlib.ticker as mticker
from matplotlib.dates import date2num
from mpl_finance import candlestick_ohlc
import datetime as dt
import numpy as np
import matplotlib.ticker as mticker


def get_data(date):
    """ Query the API for 2000 days historical price data starting from "date". """
    url = "https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD&limit=2000&toTs={}".format(date)
    r = requests.get(url)
    ipdata = r.json()
    return ipdata

def get_df(from_date, to_date):
    """ Get historical price data between two dates. """
    date = to_date
    holder = []
    # While the earliest date returned is later than the earliest date requested, keep on querying the API
    # and adding the results to a list. 
    while date > from_date:
        data = get_data(date)
        holder.append(pd.DataFrame(data['Data']))
        date = data['TimeFrom']
    # Join together all of the API queries in the list.    
    df = pd.concat(holder, axis = 0)                    
    # Remove data points from before from_date
    df = df[df['time']>from_date]                       
    # Convert to timestamp to readable date format
    # df['time'] = pd.to_datetime(df['time'], unit='s')   
    # Make the DataFrame index the time
    df.set_index('time', inplace=True)                  
    # And sort it so its in time order 
    df.sort_index(ascending=False, inplace=True)        
    return df

df = get_df(1528502400, 1560112385)

style.use('dark_background')    
fig = plt.figure()
ax1 = plt.subplot2grid((1,1), (0,0))
df = df.reset_index()

cols = ['time', 'open', 'high', 'low', 'close', 'volumefrom', 'volumeto']
df = df[cols]

#IF YOU /1000 AFER ('float') IT WILL RUN BUT NOT CORRECT DATE
df['time'] = (df['time'].astype('float'))

print(df.dtypes)
ohlc = df.values.tolist()
candlestick_ohlc(ax1, ohlc, width=.4, colorup='g', colordown='r')

# IF YOU COMMENT NEXT 4 LINES IT WILL RUN, but NO DATES for XAXIS
date_fmt = "%d-%m-%Y"
date_formatter = mdate.DateFormatter(date_fmt)
ax1.xaxis.set_major_formatter(date_formatter)
fig.autofmt_xdate()

ax1.set_ylabel('BTC Price (USD)')
ax1.set_xlabel('Date')
plt.show()

预期结果将是标为d-m-y的日期标签。 :)

Wish this had dates for xaxis labels not seconds since 1970

This is what I want it to look like, but with accurate dates

1 个答案:

答案 0 :(得分:0)

这是修复代码的方法:

df ['time'] = df ['time']。apply(mdates.epoch2num)

这绝对是您花费数小时的代码行之一……现在我知道了。