1
在使用pandas_datareader庫獲取所有SP500公司的數據時,似乎無法超越伯克希爾哈撒韋公司。在獲取所有SP500公司的數據時無法超越伯克希爾哈撒韋公司
這是代碼:
import bs4 as bs
import pickle
import datetime as dt
import os
import pandas as pd
import pandas_datareader.data as web
import requests
def save_sp500_tickers():
resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup = bs.BeautifulSoup(resp.text, "1xml")
table = soup.find('table', {'class': 'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[0].text
mapping = str.maketrans('.', '-')
ticker = ticker.translate(mapping)
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_dfs'):
os.makedirs('stock_dfs')
start = dt.datetime(2000, 1, 1)
end = dt.datetime(2016, 12, 31)
for ticker in tickers:
if not os.path.exists('stock_dfs/{}.csv'.format(ticker)):
df = web.DataReader(ticker, 'yahoo', start, end)
df.to_csv('stock_dfs/{}.csv'.format(ticker))
else:
print('Already have {}'.format(ticker))
get_data_from_yahoo()
是的,我從pythonprogramming.net 服用過程中的任何幫助將不勝感激! 謝謝!
沒有工作。仍然得到相同的錯誤。還有其他建議嗎? –
我的回答實際上是錯誤的,替換已經在save_sp500_tickers中的str.maketrans中完成。你得到的錯誤是什麼? – misantroop
這是我得到的錯誤:無法讀取URL:http://ichart.finance.yahoo.com/table.csv?s=BRK.B&a=0&b=1&c=2000&d=11&e=31&f=2016&g= d&忽略=的.csv –