Я пытаюсь захватить ключевые финансовые данные для конкретных компаний (акции в поле ниже кода) с помощью этого кода:Не получая Txt в Python
netIncomeAr = []
endLink = 'order=asc' # order=asc&
try:
netIncome = urllib.request.urlopen('https://www.quandl.com/api/v3/datasets/RAYMOND/'+stock.upper()+'_NET_INCOME_A.csv?'+endLink).read()
splitNI = netIncome.split('\n')
print('Net Income:')
for eachNI in splitNI[1:-1]:
print(eachNI)
netIncomeAr.append(eachNI)
incomeDate, income = np.loadtxt(netIncomeAr, delimiter=',',unpack=True,
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
except Exception as e:
print('failed in the Quandl grab')
print(str(e))
time.sleep(555)
Но я получаю сообщение об ошибке, что я разработал «Failed в Quandl грейфером ». Я знаю, что ошибка должна быть в первых строках, выполняющих urllib.request из Quandl.
Кто-нибудь видит, почему этот код не работает?
OK - Спасибо Roland,
Я изменил код для этого ограниченного фрагмента кода доказательство правильности концепции:
import urllib.request, urllib.error, urllib.parse
import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
evenBetter = ['GOOG','AAPL']
def graphData(stock, MA1, MA2):
#######################################
#######################################
'''
Use this to dynamically pull a stock from Quandl:
'''
print('Currently Pulling',stock)
netIncomeAr = []
# revAr = []
# ROCAr = []
endLink = 'order=asc'
netIncome = str(urllib.request.urlopen('https://www.quandl.com/api/v3/datasets/RAYMOND/'+stock.upper()+'_NET_INCOME_A.csv?'+endLink).read())[2:-1]
# convert to string, remove leading "b'" and trailing "'" characters.
# netIncome = 'head\\ndata\\ndata\\n...'
splitNI = netIncome.split('\\')[1:-1]
# data segments still have leading 'n' character.
# the [1:-1] is more pythonic and releases memory.
for i in range (len(splitNI)):
splitNI[i] = splitNI[i][1:]
# data segments are now converted.
print('Net Income:')
for eachNI in splitNI:
print(eachNI)
netIncomeAr.append(eachNI)
incomeDate, income = np.loadtxt(netIncomeAr, delimiter=',',unpack=True,
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
for stock in evenBetter:
graphData(stock,25,50)
И я теперь получаю мимо urllib.request проблемы к другой .. . Ниже ошибка:
Currently Pulling GOOG
Net Income:
2009-12-31,6520448000.0
2010-12-31,8505000000.0
2011-12-31,9737000000.0
2012-12-31,10737000000.0
2013-12-31,12920000000.0
Traceback (most recent call last):
File "<ipython-input-3-5ce0b8405254>", line 1, in <module>
runfile('C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py', wdir='C:/Users/Morten/Google Drev/SpyderProject/test')
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py", line 57, in <module>
graphData(stock,25,50)
File "C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py", line 54, in graphData
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\npyio.py", line 860, in loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\npyio.py", line 860, in <listcomp>
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\matplotlib\dates.py", line 261, in __call__
return date2num(datetime.datetime(*time.strptime(s, self.fmt)[:6]))
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\_strptime.py", line 494, in _strptime_time
tt = _strptime(data_string, format)[0]
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\_strptime.py", line 306, in _strptime
raise TypeError(msg.format(index, type(arg)))
TypeError: strptime() argument 0 must be str, not <class 'bytes'>
с предложением Davse BAMSE, я вижу следующее отслеживающий (это жесткое):
Currently Pulling GOOG
Net Income:
Traceback (most recent call last):
File "<ipython-input-3-c3f1db0f3995>", line 1, in <module>
runfile('C:/Users/Morten/Google Drev/SpyderProject/test/sentdex_Test_comp_screener_own_webscraper2.py', wdir='C:/Users/Morten/Google Drev/SpyderProject/test')
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Morten/Google Drev/SpyderProject/test/sentdex_Test_comp_screener_own_webscraper2.py", line 59, in <module>
graphData(stock)
File "C:/Users/Morten/Google Drev/SpyderProject/test/sentdex_Test_comp_screener_own_webscraper2.py", line 56, in graphData
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\npyio.py", line 845, in loadtxt
converters[i] = conv
IndexError: list assignment index out of range
С новым предложением Davse BAMSE с списком, как это в конвертере:
[incomeDate, income] = np.loadtxt(netIncomeAr, delimiter=',',unpack=True,
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
Я вижу эту ошибку:
Currently Pulling GOOG
Net Income:
C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\npyio.py:823: UserWarning: loadtxt: Empty input file: "[]"
warnings.warn('loadtxt: Empty input file: "%s"' % fname)
Traceback (most recent call last):
File "<ipython-input-1-c3f1db0f3995>", line 1, in <module>
runfile('C:/Users/Morten/Google Drev/SpyderProject/test/sentdex_Test_comp_screener_own_webscraper2.py', wdir='C:/Users/Morten/Google Drev/SpyderProject/test')
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Morten/Google Drev/SpyderProject/test/sentdex_Test_comp_screener_own_webscraper2.py", line 60, in <module>
graphData(stock)
File "C:/Users/Morten/Google Drev/SpyderProject/test/sentdex_Test_comp_screener_own_webscraper2.py", line 56, in graphData
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\npyio.py", line 845, in loadtxt
converters[i] = conv
IndexError: list assignment index out of range
Спасибо за ваш вклад от 12 окт. 2015 Davse Bamse,
Однако я не уверен, где вставить .join как сказать ...
Не могли бы вы скопировать этот фрагмент и опубликовать (отредактированного) предложение об этом. Мне нужно увидеть свет! Это то, что у меня есть теперь после всех изменений до 12 окт.
import urllib.request, urllib.error, urllib.parse
import numpy as np
import matplotlib.dates as mdates
stocklist = ['GOOG']
def graphData(stock, MA1, MA2):
#######################################
#######################################
'''
Use this to dynamically pull a stock from Quandl:
'''
print('Currently Pulling',stock)
netIncomeAr = []
endLink = 'order=asc' # order=asc&
netIncome = str(urllib.request.urlopen('https://www.quandl.com/api/v3/datasets/RAYMOND/'+stock.upper()+'_NET_INCOME_A.csv?'+endLink).read())[2:-1]
# convert to string, remove leading "b'" and trailing "'" characters.
# netIncome = 'head\\ndata\\ndata\\n...'
splitNI = netIncome.split('\\')[1:-1]
# data segments still have leading 'n' character.
# the [1:-1] is more pythonic and releases memory.
for i in range (len(splitNI)):
splitNI[i] = splitNI[i][1:]
# data segments are now converted.
print('Net Income:')
for eachNI in splitNI:
print(eachNI)
netIncomeAr.append(eachNI)
incomeDate, income = np.loadtxt(netIncomeAr, delimiter=',',unpack=True,
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
for stock in stocklist:
graphData(stock,25,50)
С сегодняшними (13-10-2015) вход с Davse BAMSE, я получаю следующее сообщение об ошибке:
Currently Pulling GOOG
Net Income:
2009-12-31,6520448000.0
2010-12-31,8505000000.0
2011-12-31,9737000000.0
2012-12-31,10737000000.0
2013-12-31,12920000000.0
Traceback (most recent call last):
File "<ipython-input-13-5ce0b8405254>", line 1, in <module>
runfile('C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py', wdir='C:/Users/Morten/Google Drev/SpyderProject/test')
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py", line 54, in <module>
graphData(stock,25,50)
File "C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py", line 51, in graphData
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\npyio.py", line 740, in loadtxt
fh = iter(open(fname))
OSError: [Errno 22] Invalid argument: '2009-12-31,6520448000.0\n2010-12-31,8505000000.0\n2011-12-31,9737000000.0\n2012-12-31,10737000000.0\n2013-12-31,12920000000.0'
Davse Bamse предположил, что я использую io.StringIO так:
incomeDate, income = StringIO(np.loadtxt('\n'.join(netIncomeAr), delimiter=',',unpack=True,
converters={ 0: mdates.strpdate2num('%Y-%m-%d')}))
Но это дает мне ту же ошибку, что и раньше ... Любые мысли ???
Изменение преобразователя линии к этому:
incomeDate, income = np.loadtxt(StringIO('\n'.join(netIncomeAr)), delimiter=',',unpack=True,
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
предоставляет следующие StackTrace:
Currently Pulling GOOG
Net Income:
2009-12-31,6520448000.0
2010-12-31,8505000000.0
2011-12-31,9737000000.0
2012-12-31,10737000000.0
2013-12-31,12920000000.0
Traceback (most recent call last):
File "<ipython-input-26-5ce0b8405254>", line 1, in <module>
runfile('C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py', wdir='C:/Users/Morten/Google Drev/SpyderProject/test')
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py", line 60, in <module>
graphData(stock,25,50)
File "C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py", line 57, in graphData
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\npyio.py", line 860, in loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\npyio.py", line 860, in <listcomp>
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\matplotlib\dates.py", line 261, in __call__
return date2num(datetime.datetime(*time.strptime(s, self.fmt)[:6]))
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\_strptime.py", line 494, in _strptime_time
tt = _strptime(data_string, format)[0]
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\_strptime.py", line 306, in _strptime
raise TypeError(msg.format(index, type(arg)))
TypeError: strptime() argument 0 must be str, not <class 'bytes'>
Вместо Numpy-х (я в нп 1.9.2) loadtxt я нашел другой метод np.genfromtxt, что это может быть описано в этом решении numpy.loadtxt does not read file with complex numbers.
Таким образом, используя этот конвертер строки вместо
incomeDate, income = np.genfromtxt('\n'.join(netIncomeAr), delimiter=',',unpack=True,
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
Выход
Currently Pulling GOOG
Net Income:
2009-12-31,6520448000.0
2010-12-31,8505000000.0
2011-12-31,9737000000.0
2012-12-31,10737000000.0
2013-12-31,12920000000.0
Traceback (most recent call last):
File "<ipython-input-10-5ce0b8405254>", line 1, in <module>
runfile('C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py', wdir='C:/Users/Morten/Google Drev/SpyderProject/test')
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py", line 50, in <module>
graphData(stock,25,50)
File "C:/Users/Morten/Google Drev/SpyderProject/test/Test_sentdex_comp_screener_own_webscraper2.py", line 47, in graphData
converters={ 0: mdates.strpdate2num('%Y-%m-%d')})
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\npyio.py", line 1366, in genfromtxt
fhd = iter(np.lib._datasource.open(fname, 'rb'))
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\_datasource.py", line 151, in open
return ds.open(path, mode)
File "C:\Program Files\WinPython-64bit-3.3.5.7\python-3.3.5.amd64\lib\site-packages\numpy\lib\_datasource.py", line 501, in open
raise IOError("%s not found." % path)
OSError: 2009-12-31,6520448000.0
2010-12-31,8505000000.0
2011-12-31,9737000000.0
2012-12-31,10737000000.0
2013-12-31,12920000000.0 not found.
Я не знаю, если эта вещь лучше или хуже ...
Что означает 'print (str (e))' prints? –
Удалите попытку/захват вокруг вашего кодового блока, запустите его снова и распечатайте стек. Линия «except Exception as e:» маскирует ошибку. – rask004
Спасибо Roland, Stacktrace теперь включен в вопрос выше. – Morten