2017-08-30 5 views
0

私はPythonを使用してWikipediaのデータセットにアクセスしようとしていますが、コードの目的はS & p500企業のテーブルにアクセスし、 csvファイル(1つのCSVファイル内の各企業がデータ)データのいくつかは、よくアクセスされますが、私はunderstand.Iに少し難しい見つけていたソケット例外は私の完全なコードPythonを使ってWikipediaのデータにアクセスする際にソケットエラーを解決する方法

import bs4 as bs 
import datetime as dt 
import os 
import pandas as pd 
import pandas_datareader.data as web 
import pickle 
import requests 


def save_sp500_tickers(): 
resp = requests.get('http://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) 

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: 
    # just in case your connection breaks, we'd like to save our progress! 
    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() 

を与えている取得しています私は、例外が発生しました

 Traceback (most recent call last): 
     File "C:\Users\Jeet Chatterjee\Data Analysis With Python for finance\op6.py", line 49, in <module> 
get_data_from_yahoo() 
    File "C:\Users\Jeet Chatterjee\Data Analysis With Python for finance\op6.py", line 44, in get_data_from_yahoo 
df = web.DataReader(ticker, "yahoo", start, end) 
    File "C:\Program Files (x86)\Python36-32\lib\site-packages\pandas_datareader\data.py", line 121, in DataReader 
session=session).read() 
     File "C:\Program Files (x86)\Python36-32\lib\site-packages\pandas_datareader\yahoo\daily.py", line 115, in read 
df = super(YahooDailyReader, self).read() 
     File "C:\Program Files (x86)\Python36-32\lib\site-packages\pandas_datareader\base.py", line 181, in read 
params=self._get_params(self.symbols)) 
     File "C:\Program Files (x86)\Python36-32\lib\site-packages\pandas_datareader\base.py", line 79, in _read_one_data 
out = self._read_url_as_StringIO(url, params=params) 
     File "C:\Program Files (x86)\Python36-32\lib\site-packages\pandas_datareader\base.py", line 90, in _read_url_as_StringIO 
response = self._get_response(url, params=params) 
     File "C:\Program Files (x86)\Python36-32\lib\site-packages\pandas_datareader\base.py", line 139, in _get_response 
raise RemoteDataError('Unable to read URL: {0}'.format(url)) 
    pandas_datareader._utils.RemoteDataError: Unable to read URL: https://query1.finance.yahoo.com/v7/finance/download/AGN?period1=946665000&period2=1483208999&interval=1d&events=history&crumb=6JtBOAj%5Cu002F6EP 

この問題を解決するために、事前に感謝してください。

答えて

1

あなたがやっていることにあまり間違いはありません。一つの問題は、Yahooの時系列データは利用可能であることが保証されていないということです。表示され、消えます。私はちょうどYahooのサイトを見ました。ブラウンフォーマン(BF.B)とバークシャーハサウェイB(BRK.B)を利用しようとした時、あなたにとって失敗したアレルガン(AGN)には問題はないようです。

もう1つの問題は、S & P 500上のすべてのシンボルが、ハードコードされた範囲内のtimeseriesデータを持つと想定できないことです。いくつかは2017年だけ存在します。

以下は、2000年1月1日から現在の日にデータを要求し、Yahooが '利用可能なデータがあります。

これは現在、S & P 500にある505個のシンボルのうち503個を時系列で取り出すことができました。注記プロキシサーバーを使用しましたが、コードのこの部分を削除またはコメントアウトすることができます。

import bs4 as bs 
import datetime as dt 
import os 
import pandas as pd 
import pandas_datareader.data as web 
import pickle 
import requests 

# proxy servers for internet connection 
proxies = { 
    'http': 'http://my.proxy.server:8080', 
    'https': 'https://my.proxy.server:8080', 
} 

symbol_filename = "sp500tickers.pickle" 

def save_sp500_tickers():  
    resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies', proxies=proxies) 
    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(symbol_filename,"wb") as f: 
     pickle.dump(tickers,f) 
    return tickers 


def get_data_from_yahoo(reload_sp500=False): 
    if reload_sp500 or not os.path.exists(symbol_filename): 
     tickers = save_sp500_tickers() 
    else: 
     with open(symbol_filename,"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(dt.date.today().year, dt.date.today().month, dt.date.today().day) 

    for ticker in tickers: 
     if not os.path.exists('stock_dfs/{}.csv'.format(ticker)): 
      try: 
       print ticker 
       df = web.DataReader(ticker, "yahoo", start, end) 
       df.to_csv('stock_dfs/{}.csv'.format(ticker)) 
      except: 
       print ("No timeseries available for " + ticker) 
     else: 
      pass # print('Already have {}'.format(ticker)) 


os.environ["HTTP_PROXY"]=proxies['http'] 
os.environ["HTTPS_PROXY"]=proxies['https'] 
get_data_from_yahoo() 

希望があります。

+0

大変感謝しています。なぜプロキシを定義したのか説明できますか? – Mandrek

+0

@Mandrek私は会社のネットワーク上でこれを実行していたので、プロキシを定義しただけで、すべてのHTTP要求がHTTPプロキシサーバーを経由する必要があります。私がプロキシを定義しないと、私は呼び出しを行うことはできません、それだけです。 –

関連する問題