numpy 如何使用datestr2num而不是strpdate2num

n7taea2i  于 2023-10-19  发布在  其他
关注(0)|答案(3)|浏览(101)

strpdate 2num类在Matplotlib 3.1中被弃用,并将在3.3中被删除。请改用time.strptime或dateutil.parser.parse或datestr 2num。然而,我尝试了不同的方法,只是不断得到错误,最常见的错误消息是ValueError:(“未知字符串格式:”,“%Y-%m-% d”)
我已经尝试了time.strptime,dateutil.parser.parse和datestr 2num,但没有一个是正确的,我不知道我错了什么

import matplotlib.pyplot as plt
import numpy as np
import urllib.request
import matplotlib.dates as mdates

def bytespdate2num(fmt, encoding='utf-8'):
    strconverter = mdates.datestr2num(fmt)
    def bytesconverter(b):
        s = b.decode(encoding)
        return strconverter(s)
    return bytesconverter

def graph_data(stock):
    # Unfortunately, Yahoo's API is no longer available
    # feel free to adapt the code to another source, or use this drop-in replacement.
    stock_price_url = 'https://pythonprogramming.net/yahoo_finance_replacement'
    source_code = urllib.request.urlopen(stock_price_url).read().decode()
    stock_data = []
    split_source = source_code.split('\n')
    for line in split_source[1:]:
        split_line = line.split(',')
        if len(split_line) == 7:
            if 'values' not in line and 'labels' not in line:
                stock_data.append(line)

    date, closep, highp, lowp, openp, adj_closep, volume = np.loadtxt(  stock_data,
                                                                        delimiter=',',
                                                                        unpack=True,
                                                                        # %Y = full year. 2015
                                                                        # %y = partial year 15
                                                                        # %m = number month
                                                                        # %d = number day
                                                                        # %H = hours
                                                                        # %M = minutes
                                                                        # %S = seconds
                                                                        # 12-06-2014
                                                                        # %m-%d-%Y
                                                                        converters={0: bytespdate2num('%Y-%m-%d')})

    plt.plot_date(date, closep,'-', label='Price')

    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title('Interesting Graph\nCheck it out')
    plt.legend()
    plt.show()

graph_data('TSLA')

ValueError:(“未知字符串格式:”,“%Y-%m-% d”)

8mmmxcuj

8mmmxcuj1#

你的日期格式看起来很常见,所以strconverter = mdates.datestr2num应该可以工作(没有fmt参数)。当然,在这种情况下,整个转换器可以简化为

def bytespdate2num(b):
    return mdates.datestr2num(b.decode('utf-8'))

然后用它来

converters={0: bytespdate2num}
mfpqipee

mfpqipee2#

我一直坚持这一点,现在终于得到了解决方案,这里有一个例子:

import matplotlib.pyplot as plt
import numpy as np
import urllib.request as urq
import matplotlib.dates as mdates
import requests

def bytespdate2num(fmt, encoding='utf-8'):
    def bytesconverter(b):
        s = b.decode(encoding)
        return (mdates.datestr2num(s))
    return bytesconverter

def graph_data():

    stock_price_url='https://pythonprogramming.net/yahoo_finance_replacement'
    source_code = urq.urlopen(stock_price_url).read().decode()

    stock_data = []
    split_source = source_code.split('\n')

    for line in split_source:
        split_line = line.split(',')
        if len(split_line) is 7:
            if 'Volume' not in line:
                stock_data.append(line)

    datep, openp, highp, lowp, closep, ad_closep, vol = np.loadtxt(stock_data,
                                                                  delimiter=',',
                                                                  unpack=True,
                                                                  converters={0:bytespdate2num('%Y-%m-%d')}
                                                                  )

    plt.plot_date(datep, closep, '-', label='Price')

    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title('Interesting Graph\nCheck it out')
    plt.legend()
    plt.show()

graph_data()
lb3vh1jj

lb3vh1jj3#

import matplotlib.pyplot as plt
import numpy as np
import urllib.request
import matplotlib.dates as mdates
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

def bytespdate2num (fmt, encoding='utf-8'):
    def bytesconverter(b):
        s= b.decode(encoding)
        return (mdates.datestr2num(s))
    return bytesconverter

def graph_data(stock):
    stock_price_url = urllib.request.Request('https://query1.finance.yahoo.com/v7/finance/download/'+stock+'?period1=1633102184&period2=1664638184&interval=1d&events=history&includeAdjustedClose=true')
    status_code = urllib.request.urlopen(stock_price_url).getcode()
    with urllib.request.urlopen(stock_price_url) as sc:
        source_code = sc.read().decode()
    print(status_code)
         
        

    stock_data =[]
    split_source = source_code.split('\n')
    for line in split_source[1:]:
        split_line = line.split(',')
        if len(split_line) == 7:
            if 'values' not in line and 'labels' not in line:
                stock_data.append(line)

    date, openp, highp, lowp, closep, adjclose, volume = np.loadtxt(stock_data, 
    delimiter=',', unpack=True, converters= {0: bytespdate2num('%Y%m%d')})

    plt.plot_date(date,  closep, '-', label='PRICE')
    plt.xlabel('DATE')
    plt.ylabel('PRICE')
    plt.legend()
    plt.show()
graph_data(stock='TSLA')

相关问题