问题描述
我只是在 YouTube 中编写来自 this video 的代码,却被这个错误难住了:
Traceback (most recent call last):
File "C:/Users/john/pycharm_coding/stock_investing_using_AI/stock investing/do
Now/scripts/finance.py",line 49,in <module>
get_data_from_yahoo()
File "C:/Users/john/pycharm_coding/stock_investing_using_AI/stock investing/do Now/scripts/finance.py",line 31,in get_data_from_yahoo
tickers = pickle.load(f)
EOFError: Ran out of input
我检查了代码,一切都一样(除非你计算变量名),所以我真的很困惑。
这是我的代码:
import bs4 as bs
import datetime as dt
import os
import pandas as pd
import pandas_datareader.data as web
import pickle
import requests
from datetime import date
link = 'https://www.youtube.com/watch?v=baCAFPHb1o4'
def save_sp500_tickers():
resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup = bs.BeautifulSoup(resp.text,"lxml")
table = soup.find('table',{'class':'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[0].text
tickers.append(ticker)
with open("sp500tickers.pickle","wb") as f:
pickle.dump(tickers,f)
print(tickers)
return tickers
# save_sp500_tickers()
def get_data_from_yahoo(reload_sp500=False):
if reload_sp500:
tickers = save_sp500_tickers()
else:
with open("sp500tickers.pickle","rb") as f:
tickers = pickle.load(f)
if not os.path.exists('stock_data'):
os.makedirs('stock_data')
start = dt.datetime(2000,1,1)
end = date.today()
for ticker in tickers:
print(ticker)
if not os.path.exists('stock_data/{}.csv'.format(ticker)):
print('Scraping data from' + ticker + '...')
data = web.get_data_yahoo(ticker,'yahoo',start,end)
data.to_csv('stock_data/{}.csv'.format(ticker))
print('Done.')
else:
print('Already have {}'.format(ticker))
get_data_from_yahoo()
我搜索了网络,但我只找到了一个与我的情况相符的结果,但它并不是很有帮助,以防万一您想知道它是什么,这里是 link。
起初,我尝试复制代码并粘贴该代码中的代码,然后使用下面的答案解决它,但随后它只是“处理完成,退出代码为 0”,并且在应该执行时没有输出很多。然后我发现我没有调用它,然后取消了最后一行的缩进,但是 EOFError 又来了。
解决方法
我已在我的环境中尝试过您的代码。 原因是数据读取器的规范,不需要“雅虎”。但是,我无法解决所有问题。在某些情况下,某些股票的数据不存在,因此您需要有相应的代码。
#data = web.get_data_yahoo(ticker,'yahoo',start,end)
data = web.get_data_yahoo(ticker,end)