Giter VIP home page Giter VIP logo

yahoo-finance's Introduction

yhoo-finance

Python module to get stock data from Yahoo! Finance

image

Yahoo!, Y!Finance, and Yahoo! finance are registered trademarks of Yahoo, Inc.

yhoo-finance is not affiliated, endorsed, or vetted by Yahoo, Inc. It's an open-source tool that uses Yahoo's publicly available APIs, and is intended for research and educational purposes.

You should refer to Yahoo!'s terms of use (https://policies.yahoo.com/us/en/yahoo/terms/product-atos/apiforydn/index.htm, https://legal.yahoo.com/us/en/yahoo/terms/otos/index.html, https://policies.yahoo.com/us/en/yahoo/terms/index.htm) for details on your rights to use the actual data downloaded. Remember - the Yahoo! finance API is intended for personal use only.

Know issues

Yahoo! Finance backend is http://datatables.org/. If this service is down or has network problems you will receive errors from group YQL*, eg. YQLQueryError.

You can monitor this service via https://www.datatables.org/healthchecker/

More details #44

Install

From PyPI with pip:

$ pip install yahoo-finance

From development repo (requires git)

$ git clone git://github.com/lukaszbanasiak/yhoo-finance.git
$ cd yahoo-finance
$ python setup.py install

Usage examples

Get shares data

Example: Yahoo! Inc. (YHOO)

>>> from yahoo_finance import Share
>>> yahoo = Share('YHOO')
>>> print yahoo.get_open()
'36.60'
>>> print yahoo.get_price()
'36.84'
>>> print yahoo.get_trade_datetime()
'2014-02-05 20:50:00 UTC+0000'

Refresh data from market

>>> yahoo.refresh()
>>> print yahoo.get_price()
'36.87'
>>> print yahoo.get_trade_datetime()
'2014-02-05 21:00:00 UTC+0000'

Historical data

>>> print yahoo.get_historical('2014-04-25', '2014-04-29')
[{u'Volume': u'28720000', u'Symbol': u'YHOO', u'Adj_Close': u'35.83', u'High': u'35.89', u'Low': u'34.12', u'Date': u'2014-04-29', u'Close': u'35.83', u'Open': u'34.37'}, {u'Volume': u'30422000', u'Symbol': u'YHOO', u'Adj_Close': u'33.99', u'High': u'35.00', u'Low': u'33.65', u'Date': u'2014-04-28', u'Close': u'33.99', u'Open': u'34.67'}, {u'Volume': u'19391100', u'Symbol': u'YHOO', u'Adj_Close': u'34.48', u'High': u'35.10', u'Low': u'34.29', u'Date': u'2014-04-25', u'Close': u'34.48', u'Open': u'35.03'}]

More readable output :)

>>> from pprint import pprint
>>> pprint(yahoo.get_historical('2014-04-25', '2014-04-29'))
[{u'Adj_Close': u'35.83',
  u'Close': u'35.83',
  u'Date': u'2014-04-29',
  u'High': u'35.89',
  u'Low': u'34.12',
  u'Open': u'34.37',
  u'Symbol': u'YHOO',
  u'Volume': u'28720000'},
 {u'Adj_Close': u'33.99',
  u'Close': u'33.99',
  u'Date': u'2014-04-28',
  u'High': u'35.00',
  u'Low': u'33.65',
  u'Open': u'34.67',
  u'Symbol': u'YHOO',
  u'Volume': u'30422000'},
 {u'Adj_Close': u'34.48',
  u'Close': u'34.48',
  u'Date': u'2014-04-25',
  u'High': u'35.10',
  u'Low': u'34.29',
  u'Open': u'35.03',
  u'Symbol': u'YHOO',
  u'Volume': u'19391100'}]

Available methods

  • get_price()
  • get_change()
  • get_percent_change()
  • get_volume()
  • get_prev_close()
  • get_open()
  • get_avg_daily_volume()
  • get_stock_exchange()
  • get_market_cap()
  • get_book_value()
  • get_ebitda()
  • get_dividend_share()
  • get_dividend_yield()
  • get_earnings_share()
  • get_days_high()
  • get_days_low()
  • get_year_high()
  • get_year_low()
  • get_50day_moving_avg()
  • get_200day_moving_avg()
  • get_price_earnings_ratio()
  • get_price_earnings_growth_ratio()
  • get_price_sales()
  • get_price_book()
  • get_short_ratio()
  • get_trade_datetime()
  • get_historical(start_date, end_date)
  • get_name()
  • refresh()
  • get_percent_change_from_year_high()
  • get_percent_change_from_year_low()
  • get_change_from_year_low()
  • get_change_from_year_high()
  • get_percent_change_from_200_day_moving_average()
  • get_change_from_200_day_moving_average()
  • get_percent_change_from_50_day_moving_average()
  • get_change_from_50_day_moving_average()
  • get_EPS_estimate_next_quarter()
  • get_EPS_estimate_next_year()
  • get_ex_dividend_date()
  • get_EPS_estimate_current_year()
  • get_price_EPS_estimate_next_year()
  • get_price_EPS_estimate_current_year()
  • get_one_yr_target_price()
  • get_change_percent_change()
  • get_dividend_pay_date()
  • get_currency()
  • get_last_trade_with_time()
  • get_days_range()
  • get_year_range()

Get currency data

Example: EUR/PLN (EURPLN=X)

>>> from yahoo_finance import Currency
>>> eur_pln = Currency('EURPLN')
>>> print eur_pln.get_bid()
'4.2007'
>>> print eur_pln.get_ask()
'4.2091'
>>> print eur_pln.get_rate()
'4.2049'
>>> print eur_pln.get_trade_datetime()
'2014-03-05 11:23:00 UTC+0000'

Refresh data from market

>>> eur_pln.refresh()
>>> print eur_pln.get_rate()
'4.2052'
>>> print eur_pln.get_trade_datetime()
'2014-03-05 11:27:00 UTC+0000'

Avalible methods

  • get_bid()
  • get_ask()
  • get_rate()
  • get_trade_datetime()
  • refresh()

Requirements

See requirements.txt

yahoo-finance's People

Contributors

benbrostoff avatar danielorf avatar grantrules avatar hayd avatar jmeridth avatar jwallden avatar katms avatar llybin avatar lukaszbanasiak avatar mcardillo55 avatar organicirradiation avatar svardfredrik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yahoo-finance's Issues

Problem with get_price(), even after the USD / COP market has opened

Hello, we’re experiencing an issue that you might help us clarify. When using the method get_price(), sometimes in the morning, even after the USD / COP market has opened, we still get the prior market day’s price, instead of the spot value. Is this something related to Yahoo’s service or is it something we might find a solution for?

Thanks

.get_historical sometimes results in a KeyError: "query"

Not sure what's causing it, but if I run the following code a few times then eventually it results in an error "yahoo_finance.YQLQueryError: Query failed with error: "'No definition found for Table yahoo.finance.historicaldata'"."
from yahoo_finance import Share
index = "^IXIC"
index = Share(index)
print(index.get_historical("2016-07-20", "2016-07-21"))

I'd be interested in hearing if others can reproduce it. I wasn't getting this error before and I've been using this API for weeks, so I'm sad to be getting this issue. FYI, ^IXIC represents the Nasdaq Composite index and is just an example, the same error occurs for other indices and regular stocks such as MSFT.

get_info()

Hi,

get_info() returns incomplete data. Is it issue from Yahoo ?

Share() doesn't work (builtins.AttributeError: 'NoneType' object has no attribute 'popitem')

I've just installed yahoo finance to try to parse the key facts of some stock with a program I'm beginning to develop: I just don't manage to make it work and I suspect there has been some changes in Yahoo Finance website since the last package update that has affected the ability of the package to work.
When I try to get stock information with the basic Share class, I get an error:

>>> import yahoo_finance
>>> yahoo=yahoo_finance.Share('YHOO')
Traceback (most recent call last):
  Python Shell, prompt 5, line 1
  File "C:\Users\PORTABLE\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\yahoo_finance\__init__.py", line 178, in __init__
    self.refresh()
  File "C:\Users\PORTABLE\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\yahoo_finance\__init__.py", line 142, in refresh
    self.data_set = self._fetch()
  File "C:\Users\PORTABLE\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\yahoo_finance\__init__.py", line 181, in _fetch
    data = super(Share, self)._fetch()
  File "C:\Users\PORTABLE\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\yahoo_finance\__init__.py", line 134, in _fetch
    data = self._request(query)
  File "C:\Users\PORTABLE\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\yahoo_finance\__init__.py", line 125, in _request
    _, results = response['query']['results'].popitem()
builtins.AttributeError: 'NoneType' object has no attribute 'popitem'

Before this error the command executes itself during a few seconds, as if it were trying to retrieve a webpage for a long time (but I've checked Yahoo Finance and it's perfectly working on my browser).
Do you know what it is caused by and how to fix it?

Use exchange and stock symbol

Hi,

thanks for the package.
Some symbols aren't unique like MTX (MTX NYSE Minerals Technologies Inc) and (MTX Frankfurt MTU Aero Engines)
Is it possible to specify the exchange in some way?
Something like
MTX_NYSE = Share('NYSE:MTX')

Thanks!

Currency.get_rate() fails while parsing date while using PyQt4

I am using yahoo-finance 1.2.1 on ubuntu 15.10 with python 3.5

When using yahoo-finance from a PyQt4 app, the date parsing fails with an ValueError when doing this:

usd_in_eur = Currency('USDEUR').get_rate()

Without PyQt4, it works perfectly.

I have inserted a print statement in the edt_to_utc code, and the date variable was: 12/15/2015 9:23pm in both cases

This is the stacktrace:

  File "/home/daniel/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 155, in __init__
    self.refresh()
  File "/home/daniel/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 146, in refresh
    self.data_set = self._fetch()
  File "/home/daniel/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 160, in _fetch
    data[u'DateTimeUTC'] = edt_to_utc('{0} {1}'.format(data['Date'], data['Time']))
  File "/home/daniel/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 27, in edt_to_utc
    date_ = datetime.strptime(date.replace(" 0:", " 12:"), mask)
  File "/usr/lib/python3.5/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.5/_strptime.py", line 340, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: pm

Suggest Symbol

Is this something that exists in Yahoo's API? Or any ideas how something like this could be implemented? It would be really slick if you could do something like .symbolSuggest("Yahoo") and get back "YHOO".

issue on get_price()

Hello,

Thanx for yahoo_finance module.
I have an issue after :

from yahoo_finance imprt Share
mc = Share('MCD')
mc.get_price() # or after mc.refresh() then mc.get_price()

I get the last price, so everything is OK, but sometimes i get previous close price.
Is it a known issue, then how to fix it, or i miss something ?

Possible get_week_high/low?

Would get_week_high and get_week_low be best implemented by calling get_historical(last trading week range)? If others find this useful I can submit a pull request with this feature.

Chinese shares are not recognized.

Even though they are on the yahoo finance website, finance.yahoo.com/q?s=601106.SS&ql=1, chinese stocks such as 601106.SS return 'None' after .get_price() is invoked.

get_historical does not return complete historical data in certain date for certain stock

get_historical does not return a complete set of historical data for certain stock. Take a random example for a stock in KLSE (Malaysian Stock Market Exchange) with yahoo ticker code of 5247.KL, with date from "2015-05-09" to "2015-06-26", it only returns a few days of data instead of all. Not sure if this is yahoo server issue or has something to do with the script.

Try the following code:
stock = Share("5247.KL")
print (stock.get_historical("2015-06-09","2015-06026"))

Error initializing with YHOO data

I'm getting an error when using the API inside a Django application.
It looks like an issue with datetime parsing, but I haven't figure it out yet.

(most recent call last):

File "/projects/projetos/xxxx/module/submodule.py", line 455, in getYahoo
yahoo = Share('YHOO')
File "/projects/projetos/xxxx/venv/lib/python2.7/site-packages/yahoo_finance/init.py", line 175, in init
super(Share, self).init(symbol)
File "/projects/projetos/xxxx/venv/lib/python2.7/site-packages/yahoo_finance/init.py", line 75, in init
self.data_set = self._fetch()
File "/projects/projetos/xxxx/venv/lib/python2.7/site-packages/yahoo_finance/init.py", line 180, in fetch
data[u'LastTradeDateTimeUTC'] = edt_to_utc('{0} {1}'.format(data['LastTradeDate'], data['LastTradeTime']))
File "/projects/projetos/xxxx/venv/lib/python2.7/site-packages/yahoo_finance/init.py", line 21, in edt_to_utc
date
= datetime.strptime(date, mask)
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: pm

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Random JSON error

Hey

I've some code which loops through some Yahoo tickers and fetches today's OHLCV

It seems to randomly stop and give me this:

Traceback (most recent call last):
File "fetch.py", line 79, in
data = fetch_since(s_clean, date_start)
File "fetch.py", line 53, in fetch_since
equity = yahoo_finance.Share(symbol)
File "build/bdist.linux-x86_64/egg/yahoo_finance/init.py", line 178, in init
File "build/bdist.linux-x86_64/egg/yahoo_finance/init.py", line 142, in refresh
File "build/bdist.linux-x86_64/egg/yahoo_finance/init.py", line 181, in _fetch
File "build/bdist.linux-x86_64/egg/yahoo_finance/init.py", line 134, in _fetch
File "build/bdist.linux-x86_64/egg/yahoo_finance/init.py", line 118, in _request
File "build/bdist.linux-x86_64/egg/yahoo_finance/yql.py", line 62, in execute
File "/home/henry/.local/lib/python2.7/site-packages/simplejson/init.py", line 516, in loads
return _default_decoder.decode(s)
File "/home/henry/.local/lib/python2.7/site-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/home/henry/.local/lib/python2.7/site-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Symbol not found

Hi
You could raise an error, or create a status field if the symbol is not found.
The current solution is throwing an error on:

File "build/bdist.linux-x86_64/egg/yahoo_finance/init.py", line 127, in _fetch
data[u'LastTradeDateTimeUTC'] = edt_to_utc('%s %s' % (data['LastTradeDate'], data['LastTradeTime']))

Thanks

test_yhoo intermittently fails on build

I noticed when running the unit tests prior to market open I'd often get TypeError: float() argument must be a string or a number when running test_yhoo , as None would be returned instead of the opening price. I'm assuming this is a result of how the Yahoo API works during non-market hours. One solution here might be to do a general check during setUp to ensure the API response is as we expect.

Visual Studio Intellisense - python setup.py install doesn't add lib/site-packages/yahoo-finance/ directory

Hello,

Perhaps I'm being a python noob, but running Anaconda Python 2.7 from the Anaconda Prompt and executing "python setup.py install" on the downloaded extracted folder installs everything correctly except I do not get a "lib/site-packages/yahoo-finance/" directory inside my Anaconda directory. Without this, I can still "import yahoo_finance," but Visual Studio's Intellisense cannot create a database for the module without putting the "yahoo-finance-1.2.1/yahoo-finance" containing init and yql into the "site-packages" directory. This step is usually completed automatically in python installers. This way, Intellisense knows all the methods etc. of this module.

Hope this helps someone.
Jose

YQLQueries don't check the response code properly

See https://github.com/lukaszbanasiak/yahoo-finance/blob/master/yahoo_finance/yql.py#L60

If the response returns a failure code the body typically contains an error message rather than the expected data.

This results in an stacktrace when JSON decoding fails, which is annoying because that is not actually the root cause.

Checking the response code and failing with a clear error message would be much better.

Specific example: a response can timeout, leading to a 504 response status and the following response body (bytestring, of course):

<HEAD>
<TITLE>Inactivity Timeout</TITLE>
</HEAD>

<BODY BGCOLOR="white" FGCOLOR="black">
<H1>Inactivity Timeout</H1>
<HR>

<FONT FACE="Helvetica,Arial"><B>
Description: Too much time has passed without sending any data for document. 
</B></FONT>
<HR>
</BODY>

Error retrieving quotes for symbols with special characters

If I try to obtain quotes for companies which have a '&' in their symbol, for eg., "J&KBANK.BO", I get the following stack trace -

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print Share("J&KBANK.BO")
  File "/usr/local/lib/python2.7/dist-packages/yahoo_finance/__init__.py", line 178, in __init__
    self.refresh()
  File "/usr/local/lib/python2.7/dist-packages/yahoo_finance/__init__.py", line 142, in refresh
    self.data_set = self._fetch()
  File "/usr/local/lib/python2.7/dist-packages/yahoo_finance/__init__.py", line 181, in _fetch
    data = super(Share, self)._fetch()
  File "/usr/local/lib/python2.7/dist-packages/yahoo_finance/__init__.py", line 134, in _fetch
    data = self._request(query)
  File "/usr/local/lib/python2.7/dist-packages/yahoo_finance/__init__.py", line 120, in _request
    _, results = response['query']['results'].popitem()
AttributeError: 'NoneType' object has no attribute 'popitem'

Is there a workaround?
yahoo-finance 1.2.1 on Python 2.7.6.

Try avg methods

I have tried average method get_50day_moving_avg() and get_200day_moving_avg today but they have not worked.
Traceback (most recent call last):
File "", line 1, in
NameError: name 'get_200day_moving_avg' is not defined

Python 3.2.3: SyntaxError: invalid syntax

Could it be, that with python3.2 there is some error. Please see attached output.

python3.2
Python 3.2.3 (default, Feb 20 2013, 17:02:41)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from yahoo_finance import Share
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.2/dist-packages/yahoo_finance/__init__.py", line 156
    data[u'DateTimeUTC'] = edt_to_utc('{0} {1}'.format(data['Date'], data['Time']))
                      ^
SyntaxError: invalid syntax
python
Python 2.7.3 (default, Jun 20 2016, 16:18:47)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from yahoo_finance import Share
>>> yahoo = Share('^TRJCRB')
>>> print (yahoo.get_price())
188.7796
>>>
python
Python 3.5.1+ (default, Mar 30 2016, 22:46:26)
[GCC 5.3.1 20160330] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from yahoo_finance import Share
>>> yahoo = Share('^TRJCRB')
>>> print (yahoo.get_price())
188.7796
>>>

AttributeError: 'NoneType' object has no attribute 'popitem'

Got the following when creating a new Share instance:

File "/Users/mikecardillo/.virtualenvs/wallstreetbets-praw/lib/python2.7/site-packages/yahoo_finance/init.py", line 120, in _request
_, results = response['query']['results'].popitem()
AttributeError: 'NoneType' object has no attribute 'pop item'

Not sure what caused it, but my program calls Share() several times very quickly, often times with symbols that don't exist.

Can probably be resolved by adding AttributeError to https://github.com/lukaszbanasiak/yahoo-finance/blob/master/yahoo_finance/__init__.py#L121 but I'm not sure how to test since I don't know what triggered it.

AttributeError: 'NoneType' object has no attribute 'popitem' with some yahoo symbols: ^SSMI, PE&OLES.MX, SDR.L

Some yahoo symbols can't be fetched:

>>> yahoo = Share('^SSMI')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 178, in __init__
    self.refresh()
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 142, in refresh
    self.data_set = self._fetch()
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 181, in _fetch
    data = super(Share, self)._fetch()
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 134, in _fetch
    data = self._request(query)
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 120, in _request
    _, results = response['query']['results'].popitem()
AttributeError: 'NoneType' object has no attribute 'popitem'
Python 3.5.1+ (default, Mar 30 2016, 22:46:26) 
[GCC 5.3.1 20160330] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from yahoo_finance import Share
>>> yahoo = Share('PE&OLES.MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 178, in __init__
    self.refresh()
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 142, in refresh
    self.data_set = self._fetch()
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 181, in _fetch
    data = super(Share, self)._fetch()
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 134, in _fetch
    data = self._request(query)
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 120, in _request
    _, results = response['query']['results'].popitem()
AttributeError: 'NoneType' object has no attribute 'popitem'
yahoo = Share('SDR.L')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 178, in __init__
    self.refresh()
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 142, in refresh
    self.data_set = self._fetch()
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 181, in _fetch
    data = super(Share, self)._fetch()
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 134, in _fetch
    data = self._request(query)
  File "/home/chris/.local/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 120, in _request
    _, results = response['query']['results'].popitem()
AttributeError: 'NoneType' object has no attribute 'popitem'

Error querying APPL

AAPL seems to have no 'LastTrade', it;s breaking the code when starting Share('APPL').

Unable to use yahoo-finance behind proxy

Hi,

I can't use this module behind a corporate proxy. It might be related to httplib / http.client which does not support environment variables like HTTP_PROXY.

Did you ever manage to use it behind a proxy ?

Thanks

Output of get_info() does not match readme file.

Running:
import yahoo_finance as yf
from pprint import pprint
GE = yf.Share('GE')
pprint(GE.get_info())

yields:
{'CompanyName': None,
'end': '2015-05-21',
'start': '1962-01-02',
'symbol': 'GE'}

I was expecting to get Industry and Sector information in the returned dict.

Getting the currency at midnight raises ValueError.

It looks like (yahoo?) is returning a bad dateformat e.g. '4/21/2015 0:13am' Note: the 0 rather than 12 to indicate midnight. This means it isn't parseable with %I (which is used here).

In [1]: from yahoo_finance import Currency

In [2]: eur_pln = Currency("EURPLN")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-df89e7129008> in <module>()
----> 1 eur_pln = Currency("EURPLN")

/Users/andy/proj/yahoo-finance/yahoo_finance/__init__.py in __init__(self, symbol)
    147         self._table = 'xchange'
    148         self._key = 'pair'
--> 149         self.refresh()
    150
    151     def _fetch(self):

/Users/andy/proj/yahoo-finance/yahoo_finance/__init__.py in refresh(self)
    138
    139         """
--> 140         self.data_set = self._fetch()
    141
    142

/Users/andy/proj/yahoo-finance/yahoo_finance/__init__.py in _fetch(self)
    152         data = super(Currency, self)._fetch()
    153         if data['Date'] and data['Time']:
--> 154             data[u'DateTimeUTC'] = edt_to_utc('{0} {1}'.format(data['Date'], data['Time']))
    155         return data
    156

/Users/andy/proj/yahoo-finance/yahoo_finance/__init__.py in edt_to_utc(date, mask)
     19     utc = pytz.utc
     20     eastern = pytz.timezone('US/Eastern')
---> 21     date_ = datetime.strptime(date, mask)
     22     date_eastern = eastern.localize(date_, is_dst=None)
     23     date_utc = date_eastern.astimezone(utc)

/Users/andy/anaconda/envs/py34/lib/python3.4/_strptime.py in _strptime_datetime(cls, data_string, format)
    498     """Return a class cls instance based on the input string and the
    499     format string."""
--> 500     tt, fraction = _strptime(data_string, format)
    501     tzname, gmtoff = tt[-2:]
    502     args = tt[:6] + (fraction,)

/Users/andy/anaconda/envs/py34/lib/python3.4/_strptime.py in _strptime(data_string, format)
    335     if not found:
    336         raise ValueError("time data %r does not match format %r" %
--> 337                          (data_string, format))
    338     if len(data_string) != found.end():
    339         raise ValueError("unconverted data remains: %s" %

ValueError: time data '4/21/2015 0:13am' does not match format '%m/%d/%Y %I:%M%p'

get_historical method produces null set

I'm trying to run the below statement and I keep getting a null set being printed.
print yahoo.get_historical('2014-04-25', '2014-04-29')

All the other methods work great!!

API key addition

Hi,

the docs seem to not include a provision to add an API key to your lib. Is there any way to do this yet? Otherwise, Feature request!

Share.refresh() method in 1.1.3 raises exception

When I tried to refresh the data associated with the 'GOOG' share, I observed the following:

>>> import yahoo_finance
>>> s=yahoo_finance.Share('GOOG')
>>> s.get_price()
'532.42'
>>> s.refresh()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/lev/miniconda/envs/DEFAULT/lib/python2.7/site-packages/yahoo_finance/__init__.py", line 141, in refresh
    self.data_set = self._fetch()
  File "/home/lev/miniconda/envs/DEFAULT/lib/python2.7/site-packages/yahoo_finance/__init__.py", line 178, in _fetch
    data = super(Share, self)._fetch()
  File "/home/lev/miniconda/envs/DEFAULT/lib/python2.7/site-packages/yahoo_finance/__init__.py", line 133, in _fetch
    data = self._request(query)
  File "/home/lev/miniconda/envs/DEFAULT/lib/python2.7/site-packages/yahoo_finance/__init__.py", line 122, in _request
    raise YQLQueryError(response['error']['description'])
yahoo_finance.YQLQueryError: Query failed with error: ""Query syntax error(s) [line 1:29 expecting table got 'where',line 1:36 expecting equalityExpression got '=']"".

I'm using Python 2.7.9 on Ubuntu 14.04.1.

get_historical() incomplete data returned if dividend paid during date range

For example try retrieving stock BCE with date range 2015-12-07 to 2015-12-11. The data ends on 2015-12-09 even though there is data for all 5 days on Yahoo!?

See: http://finance.yahoo.com/q/hp?s=BCE&a=11&b=7&c=2015&d=11&e=11&f=2015&g=d

NOTE: The Dividend paid 2015-12-11. Every stock with a dividend "record" on Yahoo! in the historical data exhibits this behavior (truncated results).

DATA: [{ 'Adj_Close': '41.049999', 'Volume': '844300', 'Symbol': 'BCE', 'High': '41.810001', 'Low': '40.849998', 'Date': '2015-12-09', 'Open': '41.169998', 'Close': '41.049999' }, { 'Adj_Close': '41.040001', 'Volume': '983400', 'Symbol': 'BCE', 'High': '41.52', 'Low': '40.919998', 'Date': '2015-12-08', 'Open': '41.419998', 'Close': '41.040001' }, { 'Adj_Close': '41.91', 'Volume': '898900', 'Symbol': 'BCE', 'High': '42.580002', 'Low': '41.860001', 'Date': '2015-12-07', 'Open': '42.400002', 'Close': '41.91' }]

Issue appeared today was working yesterday thanks in advance for creating though

import yahoo_finance
SPY = yahoo_finance.Share('SPY')
Traceback (most recent call last):
File "/Users/andrewallin/anaconda/lib/python3.5/site-packages/yahoo_finance/init.py", line 120, in _request
_, results = response['query']['results'].popitem()
KeyError: 'query'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "", line 1, in
File "/Users/andrewallin/anaconda/lib/python3.5/site-packages/yahoo_finance/init.py", line 178, in init
self.refresh()
File "/Users/andrewallin/anaconda/lib/python3.5/site-packages/yahoo_finance/init.py", line 142, in refresh
self.data_set = self._fetch()
File "/Users/andrewallin/anaconda/lib/python3.5/site-packages/yahoo_finance/init.py", line 181, in _fetch
data = super(Share, self)._fetch()
File "/Users/andrewallin/anaconda/lib/python3.5/site-packages/yahoo_finance/init.py", line 134, in _fetch
data = self._request(query)
File "/Users/andrewallin/anaconda/lib/python3.5/site-packages/yahoo_finance/init.py", line 123, in _request
raise YQLQueryError(response['error']['description'])
yahoo_finance.YQLQueryError: Query failed with error: "'No definition found for Table yahoo.finance.quotes'".

get_trade_datetime() for Share and refresh --- wrong UTC times

`maxIter = 200
for k in range(maxIter):

# Refresh data from market
print '\nUpdate (refresh) data from currency exchange'
exch.refresh()
newRate = exch.get_rate()
print ' Rate: %s' %newRate    
newTime = exch.get_trade_datetime()    
print '*Currency exchange date-time: %s' %newTime
#if newRate != Rate: break

`

Installing for python3

pip3 install yahoo-finance did ain’t work for me, could we add another paragraph for the read.me like

For python3 on some system do:
git clone http://blablalba
cd yahoo-finance
python3 setup.py install #This part!

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

I was able to run simple commands yesterday but am not able to run them today. I ran the follow line in Python Shell:
stock = Share('YHOO')

and got the following error:

Traceback (most recent call last):
File "<pyshell#10>", line 1, in
stock = Share('YHOO')
File "C:\Python27\lib\site-packages\yahoo_finance__init__.py", line 176, in init
self.refresh()
File "C:\Python27\lib\site-packages\yahoo_finance__init__.py", line 140, in refresh
self.data_set = self.fetch()
File "C:\Python27\lib\site-packages\yahoo_finance__init
_.py", line 179, in fetch
data = super(Share, self).fetch()
File "C:\Python27\lib\site-packages\yahoo_finance__init
.py", line 132, in fetch
data = self.request(query)
File "C:\Python27\lib\site-packages\yahoo_finance__init
.py", line 116, in _request
response = yql.YQLQuery().execute(query)
File "C:\Python27\lib\site-packages\yahoo_finance\yql.py", line 51, in execute
return simplejson.loads(self.connection.getresponse().read())
File "C:\Python27\lib\httplib.py", line 1074, in getresponse
response.begin()
File "C:\Python27\lib\httplib.py", line 415, in begin
version, status, reason = self._read_status()
File "C:\Python27\lib\httplib.py", line 371, in _read_status
line = self.fp.readline(_MAXLINE + 1)
File "C:\Python27\lib\socket.py", line 476, in readline
data = self._sock.recv(self._rbufsize)
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Its happening for any ticker symbol I provide

get_info() is only returning the symbol

hi,

get_info() previously worked for me but it is now only returning the symbol and none of the other information eg Sector, Industry etc.

Thanks!

In [31]:
from yahoo_finance import Share
yahoo_info = Share('YHOO')
yahoo_info.get_info()

Out[31]:
{u'symbol': u'YHOO'}

Get index data?

Is it possible to get data (historical and/or present) for any of the market indexes? S&P500, DOW, NASDAQ? Trying to make comparisons between stock and index performance.

ResourceWarning for unclosed socket

In Python 3.5, I get a ResourceWarning while unit testing something using this module:

Warning (from warnings module):
    File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/yahoo_finance/__init__.py", line 118
    response = yql.YQLQuery().execute(query)
ResourceWarning: unclosed <socket.socket fd=10, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('...', ...), raddr=('...', ...)>

get_historical data doesn't return correct results if there is only one row returned

If between start date and end date there is only one result row then data is not returned correctly. Below patch to the function fixes is it all

    def get_historical(self, start_date, end_date):
        """
        Get Yahoo Finance Stock historical prices

        :param start_date: string date in format '2009-09-11'
        :param end_date: string date in format '2009-09-11'
        :return: list
        """
        hist = []
        for s, e in get_date_range(start_date, end_date):
            try:
                query = self._prepare_query(table='historicaldata', startDate=s, endDate=e)
                result = self._request(query)
                if isinstance(result, dict):
                    result = [result]
                hist.extend(result)
            except AttributeError:
                pass
        return hist

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.