Python-雅虎财务自动下载

问题描述 投票:0回答:1

我正在尝试从此处运行代码:

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个回答
0
投票

您需要导入'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")
© www.soinside.com 2019 - 2024. All rights reserved.