【问题标题】:Python - yahoo finance automatically downloadPython - 雅虎财经自动下载
【发布时间】:2020-02-24 14:01:01
【问题描述】:

我正在尝试从这里运行代码:

Download history stock prices automatically from yahoo finance in python

import urllib

base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
    return base_url + ticker_symbol

output_path = "C:/Users/test/Desktop/research/stock_data/test"
def make_filename(ticker_symbol, directory="S&P"):
    return output_path + "/" + directory + "/" + ticker_symbol + ".csv"

def pull_historical_data(ticker_symbol, directory="S&P"):
    try:
        urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
    except urllib.ContentTooShortError as e:
        outfile = open(make_filename(ticker_symbol, directory), "w")
        outfile.write(e.content)
        outfile.close()




pull_historical_data('AAPL', directory="S&P")

但我收到以下错误:

AttributeError: module 'urllib' has no attribute 'ContentTooShortError'

我怎样才能让它工作?或者你能给我指出一些有效的代码吗?

【问题讨论】:

    标签: python yahoo-finance


    【解决方案1】:

    您需要导入 'urllib.request' 而不是 urllib,并按照以下说明更新您的代码。

    urllib.request.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
    
    except urllib.request.ContentTooShortError as e:
    
    import urllib.request
    
    base_url = "http://ichart.finance.yahoo.com/table.csv?s="
    def make_url(ticker_symbol):
        return base_url + ticker_symbol
    
    output_path = "C:/Users/test/Desktop/research/stock_data/test"
    def make_filename(ticker_symbol, directory="S&P"):
        return output_path + "/" + directory + "/" + ticker_symbol + ".csv"
    
    def pull_historical_data(ticker_symbol, directory="S&P"):
        try:
            urllib.request.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
        except urllib.request.ContentTooShortError as e:
            outfile = open(make_filename(ticker_symbol, directory), "w")
            outfile.write(e.content)
            outfile.close()
    
    pull_historical_data('AAPL', directory="S&P")
    

    【讨论】:

    • 我收到HTTPError: Proxy Authentication Required
    • 似乎您在代理后面,您需要添加以下代码以通过代理进行身份验证。 proxy = urllib.request.ProxyHandler({'http': r'username:password@url:port'}) auth = urllib.request.HTTPBasicAuthHandler() opener = urllib.request.build_opener(proxy, auth, urllib.request.HTTPHandler) urllib。 request.install_opener(opener) conn = urllib.request.urlopen(make_url(ticker_symbol)) return_str = conn.read()
    • 你能在上面的帖子中编辑你的回复吗,因为我不明白我需要改变什么
    • 不知道您是否知道,icart 服务自 2017 年起已停止 (stackoverflow.com/questions/44361361/…)。我在运行代码时收到了一条奇怪的错误消息,因此尝试访问上述页面并收到“无法访问此站点”消息。
    猜你喜欢
    • 2019-09-12
    • 1970-01-01
    • 2017-09-16
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多