如何修复新的无法读取 yahoo 金融 python 中的 URL 错误 [英] How to fix new unable to read URL error in python for yahoo finance

查看:50
本文介绍了如何修复新的无法读取 yahoo 金融 python 中的 URL 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我去年一直在使用这个代码,但现在它产生了一个错误.有谁知道为什么会发生这种情况以及如何解决它?

<预><代码># 导入必要的包从 pandas_datareader 导入数据为 web将日期时间导入为 dt导入 matplotlib.pyplot 作为 plt将熊猫导入为 pd导入操作系统将 numpy 导入为 np# 雅虎财经的股票选择stock = input("输入股票代码或票号(Exp.General Electric is 'GE'): ")# 随着时间的推移可视化股票并设置数据框start_date = (dt.datetime.now() - dt.timedelta(days=40000)).strftime(%m-%d-%Y")df = web.DataReader(stock, data_source='yahoo', start=start_date)#错误就在这条线上^plt.plot(df['关闭'])plt.title('股票价格随时间变化',fontsize=14)plt.xlabel('Date',fontsize=14)plt.ylabel('中间价',fontsize=14)plt.show()

RemoteDataError:无法读取 URL:https://finance.yahoo.com/quote/MCD/history?period1=-1830801600&period2=1625284799&interval=1d&frequency=1d&filter=history响应文本:b'\n \n \n \n Yahoo\n \n \n \n html {\n height: 100%;\n }\n body {\n background: #fafafc url(https://s.yimg.com/nn/img/sad-panda-201402200631.png) 50% 50%;\n 背景尺寸:封面;\n 高度:100%;\n 文本对齐:居中;\n 字体:300 18px helvetica neue"、helvetica、verdana、tahoma、arial, sans-serif;\n }\n table {\n height: 100%;\n width: 100%;\n table-layout: fixed;\n border-collapse: collapse;\n border-spacing: 0;\n 边框:无;\n }\n h1 {\n 字体大小:42px;\n 字体粗细:400;\n 颜色:#400090;\n }\np {\n 颜色:#1A1A1A;\n }\n #message-1 {\n font-weight: bold;\n margin: 0;\n }\n #message-2 {\n display: inline-block;\n *display: inline;\n缩放: 1;\n 最大宽度: 17em;\n _width: 17em;\n }\n \n \n document.write('&test=\'+encodeURIComponent(\'%\')+\'" width="0px" height="0px"/>');var beacon = new Image();beacon.src="//bcn.fp.yahoo.com/p?s=1197757129&t="+ne...

解决方案

我遇到了同样的问题.最近,pdr 停止了与雅虎的合作(再次).AlphaVantage 并没有像雅虎那样持有所有股票;据我所知,googlefinance 包仅获取当前报价,而不是时间序列;yahoo-finance 软件包不起作用(或者我无法让它起作用);Econdb 发回某种形式怪异的数据帧(也许这是可以修复的);Quandl 对非美国股票设有付费墙.

因此,因为我很便宜,所以我研究了 Yahoo CSV 下载功能并想出了这个,它返回的 df 与 pdr 非常相似:

将pandas导入为pd从日期时间导入日期时间为 dt导入日历导入 io进口请求# 雅虎历史 csv 基本网址yBase = 'https://query1.finance.yahoo.com/v7/finance/download/'yHeaders = {'接受':'text/csv;charset=utf-8'}def getYahooDf(ticker, startDate, endDate=None): # ISO 格式的日期start = dt.fromisoformat(startDate) # 到 datetime.datetime 对象fromDate = calendar.timegm(start.utctimetuple()) # 到雅虎使用的Unix时间戳格式如果结束日期为无:结束=dt.now()别的:end = dt.fromisoformat(endDate)toDate = calendar.timegm(end.utctimetuple())参数 = {'period1': str(fromDate),'period2': str(toDate),'间隔':'1d','事件':'历史','includeAdjustedClose': '真'}response = requests.request(GET", yBase + ticker, headers=yHeaders, params=params)如果 response.status_code <200 或 response.status_code >299:返回无别的:csv = io.StringIO(response.text)df = pd.read_csv(csv, index_col='Date')返回 df

I have been using this code for the last year but now it produces an error. Does anyone know why this is happening and how to fix it?


# Importing necessary packages
from pandas_datareader import data as web
import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
import os
import numpy as np

# Stock selection from Yahoo Finance
stock = input("Enter stock symbol or ticket symbol (Exp. General Electric is 'GE'): ")

# Visualizing the stock over time and setting up the dataframe
start_date = (dt.datetime.now() - dt.timedelta(days=40000)).strftime("%m-%d-%Y")
df = web.DataReader(stock, data_source='yahoo', start=start_date)
#THE ERROR IS ON THIS LINE^

plt.plot(df['Close'])
plt.title('Stock Prices Over Time',fontsize=14)
plt.xlabel('Date',fontsize=14)
plt.ylabel('Mid Price',fontsize=14)
plt.show()

RemoteDataError: Unable to read URL: https://finance.yahoo.com/quote/MCD/history?period1=-1830801600&period2=1625284799&interval=1d&frequency=1d&filter=history Response Text: b'\n \n \n \n Yahoo\n \n \n \n html {\n height: 100%;\n }\n body {\n background: #fafafc url(https://s.yimg.com/nn/img/sad-panda-201402200631.png) 50% 50%;\n background-size: cover;\n height: 100%;\n text-align: center;\n font: 300 18px "helvetica neue", helvetica, verdana, tahoma, arial, sans-serif;\n }\n table {\n height: 100%;\n width: 100%;\n table-layout: fixed;\n border-collapse: collapse;\n border-spacing: 0;\n border: none;\n }\n h1 {\n font-size: 42px;\n font-weight: 400;\n color: #400090;\n }\n p {\n color: #1A1A1A;\n }\n #message-1 {\n font-weight: bold;\n margin: 0;\n }\n #message-2 {\n display: inline-block;\n *display: inline;\n zoom: 1;\n max-width: 17em;\n _width: 17em;\n }\n \n \n document.write('&test=\'+encodeURIComponent(\'%\')+\'" width="0px" height="0px"/>');var beacon = new Image();beacon.src="//bcn.fp.yahoo.com/p?s=1197757129&t="+ne...

解决方案

I had the same problem. At some recent point pdr stopped working with Yahoo (again). AlphaVantage doesn't carry all the stocks that Yahoo does; googlefinance package only gets current quotes as far as I can tell, not time series; the yahoo-finance package doesn't work (or I failed to get it to work); Econdb sends back some kind of weirdly-formed dataframe (maybe this is fixable); and Quandl has a paywall on non-US stocks.

So because I'm cheap, I looked into the Yahoo CSV download functionality and came up with this, which returns a df pretty much like pdr does:

import pandas as pd
from datetime import datetime as dt
import calendar
import io
import requests

# Yahoo history csv base url
yBase = 'https://query1.finance.yahoo.com/v7/finance/download/'
yHeaders = {
    'Accept': 'text/csv;charset=utf-8'
    }

def getYahooDf(ticker, startDate, endDate=None): # dates in ISO format
    start = dt.fromisoformat(startDate) # To datetime.datetime object
    fromDate = calendar.timegm(start.utctimetuple()) # To Unix timestamp format used by Yahoo
    if endDate is None:
        end=dt.now()
    else:
        end = dt.fromisoformat(endDate)
    toDate = calendar.timegm(end.utctimetuple())
    params = { 
        'period1': str(fromDate),
        'period2': str(toDate),
        'interval': '1d',
        'events': 'history',
        'includeAdjustedClose': 'true'
    }
    response = requests.request("GET", yBase + ticker, headers=yHeaders, params=params)
    if response.status_code < 200 or response.status_code > 299:
        return None
    else:
        csv = io.StringIO(response.text)
        df = pd.read_csv(csv, index_col='Date')
        return df

这篇关于如何修复新的无法读取 yahoo 金融 python 中的 URL 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆