Code Monkey home page Code Monkey logo

ystockquote's Introduction

ystockquote

Python module - fetch stock quote data from Yahoo Finance

image


  • Created by: Corey Goldberg (2007,2008,2013, 2016)
  • License: GNU LGPLv2+
  • Dev Home
  • PyPI

Requirements

Python 2.7 or Python 3.3+

Install

ytockquote can be installed from PyPI with pip:

$ pip install ystockquote

You can also clone the development repo to install (requires git):

$ git clone git://github.com/cgoldberg/ystockquote.git
$ cd ystockquote
$ python setup.py install

To run unit tests:

$ tox

Example Usage

>>> import ystockquote
>>> print(ystockquote.get_price_book('GOOGL'))
'51.18'
>>> print(ystockquote.get_bid_realtime('GOOGL'))
'904.77'
>>>
>>> import ystockquote
>>> from pprint import pprint
>>> pprint(ystockquote.get_historical_prices('GOOGL', '2013-01-03', '2013-01-08'))
{'2013-01-03': {'Adj Close': '723.67',
                'Close': '723.67',
                'High': '731.93',
                'Low': '720.72',
                'Open': '724.93',
                'Volume': '2318200'},
 '2013-01-04': {'Adj Close': '737.97',
                'Close': '737.97',
                'High': '741.47',
                'Low': '727.68',
                'Open': '729.34',
                'Volume': '2763500'},
 '2013-01-07': {'Adj Close': '734.75',
                'Close': '734.75',
                'High': '739.38',
                'Low': '730.58',
                'Open': '735.45',
                'Volume': '1655700'},
 '2013-01-08': {'Adj Close': '733.30',
                'Close': '733.30',
                'High': '736.30',
                'Low': '724.43',
                'Open': '735.54',
                'Volume': '1676100'}}
>>>

ystockquote's People

Contributors

cgoldberg avatar eriktaubeneck avatar gaz3ll3 avatar madsailor avatar williamalu 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

ystockquote's Issues

Change values from string --> float

Hey cglodberg, big fan of ystockquote. I'm using it for recording historical stock data to look at trends, and will possibly be using it for backtesting trading strategies. Is it possible to have get_all (and other methods) return floats instead of strings? I'm willing to make that change and make a new pull request if you're okay with that as well.

Using List

Trying to use a list to gather mass data at once but it seems to cut off the first and last array....kinda new to programing so might be my own fault....googling as I type this for more help. Added Start and End to the list, since they are thrown out anyway. Any way around this?

python test.py 0.00 544.46 99.43 57.49 55.05 136.41 0.00 ['START', 'AAPL', 'XOM', 'TWTR', 'FB', 'MMM', 'END']

Add a method to get historical 52-week high

I have a small enhancement to the package that computes a historical 52-week high.
The definition of a historical 52-week high I used is as follows:
The highest 'High' of all prices of a given symbol in a 1-year range than ends at a specified date.
The function returns a dict of dicts (just like original get_historical_prices) which usually contains a single element with the date as a key and a full data dictionary of that dates data as a value.
In a rare case of more than one occasions of the same highest 'High' value within the period all those occasions are included in the result.
I will create a pull request with my enhancement shortly.

Pip install not compatible with master (examples don't work when installed with pip)

Hi there,

I installed ystockquote with pip and tried running:

>>> import ystockquote
>>> print(ystockquote.get_price_book('GOOG'))

but it doesn't work, instead printing:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'get_price_book'

However, after I cloned and installed the master branch, the examples started working. This suggests that pip's version of ystockquote is not the same as master.

Link expired from where the data is fetched

URLError: <urlopen error [Errno -2] Name or service not known>

This error is thrown when I try to run the module using python3 IDLE. After analyzing the module I came to know that the link that is being used for fetching data from the Yahoo Finance server has expired i.e. it does not exist anymore. We need to fix the data retrieval part to make the module functional again.

get_50_sma() and get_200_sma() returns incorrect values

Hi

I really enjoy ystockquote and how easy it is to use. While creating a MA-crossover script i noticed that the returned values are incorrect. I tried multiple stocks from various lists and none of the MA values where the same as when I looked them up at my broker or at investing.com. This will in turn give incorrect crossover signals. Are the sma:s fetched from yahoo or where can the problem be located?

Thank you

Market Index, DJI, does not pull data. Can work with NASDAQ, S & P 500 with proper URL encoding

Has anyone been able to get ystockquote to report Market Indices? For example, I tried plugging in DJI (Dow Jones,) IXIC (NASDAQ,) and GSPC (S&P 500) and I'm getting back N/A for any of the data.

What I have discovered is that if I used %5E (URL Encoding for the ^ symbol) I can pull NASDAQ and S&P 500.

tickerSymbol = ['%5EIXIC', '%5EGSPC']

Those two will work and correctly return me the NASDAQ and S&P, but I can't find the code for Dow Jones Industrial Average. I tried %5EDJI , %5EDJIA but it is not working.

Anyone run into this issue?

Clarify the License

I'm a bit confused as to the license under which this code is distributed. The README and the comments in ystockquote.py both list the GPL and the LGPL. However, setup.py lists the license as 'Apache v2.0', which also gets listed in the pypi metadata.

Thanks in advance for the clarification!

`get_all` returns messy data

Below are the result of pprint(ystockquote.get_all('GOOGL')):

{
  'after_hours_change_realtime': u'N/A',
  'annualized_gain': u'N/A',
  'ask_realtime': u'N/A',
  'ask_size': u'691748000',
  'average_daily_volume': u'138624',
  'bid_realtime': u'N/A',
  'bid_size': u'1516685',
  'book_value': u'8.42',
  'change': u'+2.90',
  'change_200_sma': u'145.51',
  'change_50_sma': u'+17.10%',
  'change_from_52_week_high': u'323.51',
  'change_from_52_week_low': u'672.66',
  'change_percent': u'"+0.29%"',
  'change_percent_change': u'"+2.90 - +0.29%"',
  'change_percent_realtime': u'N/A',
  'change_realtime': u'N/A',
  'company_name': u'599351000',
  'dividend_pay_date': u'N/A',
  'dividend_per_share': u'N/A',
  'dividend_yield': u'N/A',
  'ebitda': u'94.77B',
  'eps': u'N/A',
  'eps_estimate_current_year': u'29.59',
  'eps_estimate_next_quarter': u'40.53',
  'eps_estimate_next_year': u'33.95',
  'ex_dividend_date': u'N/A',
  'fifty_sma': u'+7.70%',
  'fiftytwo_week_high': u'N/A',
  'fiftytwo_week_low': u'997.62',
  'fiftytwo_week_range': u'-0.15%',
  'float_shares': u'N/A',
  'high_limit': u'N/A',
  'holdings_gain': u'N/A',
  'holdings_gain_percent': u'1061.67',
  'holdings_gain_percent_realtime': u'N/A',
  'holdings_gain_realtime': u'N/A',
  'holdings_value': u'N/A',
  'holdings_value_realtime': u'N/A',
  'last_trade_date': u'"5/30/2017"',
  'last_trade_price': u'"4:00pm - <b>996.17</b>"',
  'last_trade_realtime_time': u'997.62',
  'last_trade_size': u'600',
  'last_trade_time': u'"4:00pm"',
  'last_trade_time_plus': u'N/A',
  'low_limit': u'N/A',
  'market_cap': u'1516685',
  'market_cap_realtime': u'689.10B',
  'more_info': u'N/A',
  'notes': u'"Alphabet Inc."',
  'one_year_target': u'850.66',
  'order_book_realtime': u'1535780',
  'pe': u'7.25',
  'pe_realtime': u'4.74',
  'peg': u'33.66',
  'percent_change_50_sma': u'71.22',
  'percent_change_from_52_week_high': u'+48.09%',
  'percent_change_from_52_week_low': u'-1.45',
  'previous_close': u'993.27',
  'price_book': u'31.21B',
  'price_eps_estimate_current_year': u'N/A',
  'price_eps_estimate_next_year': u'1.56',
  'price_paid': u'N/A',
  'price_sales': u'209.43',
  'revenue': u'N/A',
  'shares_outstanding': u'N/A',
  'shares_owned': u'N/A',
  'short_ratio': u'29.34',
  'stock_exchange': u'"672.66 - 997.62"',
  'ticker_trend': u'100',
  'today_open': u'993.27',
  'todays_high': u'991.36',
  'todays_low': u'N/A',
  'todays_range': u'N/A',
  'todays_range_realtime': u'"991.36 - 997.62"',
  'todays_value_change': u'996.17',
  'todays_value_change_realtime': u'N/A',
  'trade_date': u'N/A',
  'trade_links': u'N/A',
  'twohundred_sma': u'924.95',
  'volume': u'"NMS"'
}

Many fields are not properly populated. For example, 'volume': u'"NMS"'.

HTTP 404 error

Getting HTTP 404 error from this module
Running on Pi Zero 2W OS = Bullseye


Traceback (most recent call last):
  File "/home/pi/stockq2.py", line 3, in <module>
    print(ystockquote.get_price_book('GOOGL'))
  File "/usr/local/lib/python3.9/dist-packages/ystockquote.py", line 438, in get_price_book
    return _request(symbol, 'p6')
  File "/usr/local/lib/python3.9/dist-packages/ystockquote.py", line 32, in _request
    resp = urlopen(req)
  File "/usr/lib/python3.9/urllib/request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.9/urllib/request.py", line 523, in open
    response = meth(req, response)
  File "/usr/lib/python3.9/urllib/request.py", line 632, in http_response
    response = self.parent.error(
  File "/usr/lib/python3.9/urllib/request.py", line 555, in error
    result = self._call_chain(*args)
  File "/usr/lib/python3.9/urllib/request.py", line 494, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.9/urllib/request.py", line 747, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "/usr/lib/python3.9/urllib/request.py", line 523, in open
    response = meth(req, response)
  File "/usr/lib/python3.9/urllib/request.py", line 632, in http_response
    response = self.parent.error(
  File "/usr/lib/python3.9/urllib/request.py", line 561, in error
    return self._call_chain(*args)
  File "/usr/lib/python3.9/urllib/request.py", line 494, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.9/urllib/request.py", line 641, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

I wonder if perhaps, the URLs are outdated?

 url = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s'
 url = 'http://real-chart.finance.yahoo.com/table.csv?%s'

Thank you.

API Gets Stuck

A line of code needs to be added that says "If API can't grab data after 5-10 seconds, skip and place data as None"

Get_historcial HTTPError 404 On days market was closed

An attempt to get historical data from a weekday when the market was closed, for example national holidays, results in a 404 error from urllib. It would probably be better to catch the error and return an empty dict.

Retrieve beta for stocks

Hi,

Great work! In addition to your existing calls, I would be great to retieve also the beta of the stocks. I is listed on the 'Basic Technical Analysis' Page at Yahoo Finance. What do you think ?

Best regards

Andy

Aligning date formats

get_historical_prices() should accept dates formated at [YYYY]-[MM]-[DD] to align with date formats being returned (and align with ISO 8601).

Also, could possibly accept a datetime object as well (or instead?) and return a datetime object, to remove any ambiguity.

If there is agreement on this, I'm happy to work on the implementation.

get_historical_prices not working--bad url?

when calling get_historical_prices I get a 404 not found error. The URL this function calls to get historical stock prices seems to no longer be valid. Is there a new URL to use?
Thanks

Why my python (Spyder) got stuck (i.e. did not return result) when I was trying to run the code of retrieving stock data from yahoo finance

I have a list of US stocks ( around 3000 stocks) in excel and I want to get the stock price and other related daily stock info on each stock in certain time period. So I wrote a for loop to get all related stock info on each stock ( and I have tried both yahoo_fin.stock_info and yfinance packages). But then it just got stuck at certain stock and never return the result. I am using spyder for my python coding. below is the code:

import pandas as pd
import numpy as np
import yahoo_fin.stock_info as si

ticker_list = pd.read_excel(r'C:\Users\user\Desktop\ticker_list.xlsx',engine="openpyxl")

n=[]
et=[] 
df_empty=[]
for i in range(len(ticker_list)): 
    try:
        df = df_empty[0:0]
        df=si.get_data(ticker_list.iloc[i]['ticker'], start_date='2021-09-30', end_date='2022-04-25') 
# I used yf.download for using yfinance package
        mkt_cap=si.get_quote_table(ticker_list.iloc[i]['ticker'])["Market Cap"]
        df.insert (7,"mkt_cap",mkt_cap) 
        print(ticker_list.iloc[i]['ticker'])
        df.replace(np.inf, np.nan)        
        df = df.dropna()
        df.reset_index(inplace=True)   
        n.append(df)   
    except:
        et.append(ticker_list.iloc[i]['ticker'])
        print('error: ' + ticker_list.iloc[i]['ticker'])
        pass
print(n)

when I run the code below what it shows in my console:

Python 3.8.13 (default, Mar 28 2022, 06:59:08) [MSC v.1916 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 7.31.1 -- An enhanced Interactive Python.

runfile('C:/Users/USER/get_all_stock_data.py', wdir='C:/Users/USER')
BYDDY
CHTR
JD
KYCCF
RY-PT
GE
BP
MO
VLKPF
SMAWF
AMAT

I tired many times already , everytime it just stuck on different ticker everytime. Also I have also tried to leave the code running for a day but it just stop it right there and never give me return. when I tried to debug, it also stop running at either the si.get.data line or si.get_quote_table line. I actually use this code since last year and it work fine, it just start not working when I run this code again last week. I also tried several other packages ( e.g. pandas_datareader.data) still not able to get the stock info. Appreciate if anyone can let me know what is the problem.

Thanks

This is pretty complete, only thing I can think of adding is combining with scikit-learn for some prediction capabilities. Great lib.

exchange rates

I am new to this library. how do I get historical data about the exchange rates? say eur/usd
I tried

ystockquote.get_historical_prices('GBPEUR=X', '2013-01-03', '2013-11-08')

but does not work

Misalignment of parsed outputs in .get_all() function

Maybe Yahoo Finance has changed the reporting structure (frustrating), but the results from the .get_all() function no longer aligns up with the attribute name.

code:
print ystockquote.get_all("GOOG")

Output (Lengthy, but as you can see certain fields are misaligned e.g. 'stock_exchange'):
{'previous_close': '1069.86', 'shares_owned': '"Google Inc."', 'change_from_52_week_low': '695.52', 'revenue': '36.746', 'average_daily_volume': '000', 'todays_range_realtime': '"1059.04 - 1084.95"', 'today_open': '1071.85', 'last_trade_realtime_time': '1084.95', 'fiftytwo_week_high': '"N/A - N/A"', 'ebitda': '44.15', 'fifty_sma': '+3.82%', 'pe_realtime': '12.26', 'ask_realtime': '1097.00', 'percent_change_50_sma': '+39.90', 'percent_change_from_52_week_low': '-7.5601', 'price_paid': '"N/A - N/A"', 'pe': 'N/A', 'holdings_value': '"Choose Brokerage"', 'price_eps_estimate_next_year': '17.599B', 'dividend_per_share': '0.00', 'twohundred_sma': '1044.85', 'trade_links': '2212546', 'market_cap': '2212546', 'todays_value_change_realtime': '"- - +1.39%"', 'change_realtime': '"+14.89"', 'low_limit': '" +===== "', 'volume': '"695.52 - 1092.3101"', 'todays_high': '1059.04', 'ask_size': '-', 'holdings_gain': '"-"', 'shares_outstanding': '"-"', 'holdings_gain_realtime': '"N/A - N/A"', 'last_trade_price': '"Dec 18 - 1084.75"', 'notes': '000', 'change_percent': '"+1.39%"', 'change_percent_realtime': '"N/A - +1.39%"', 'ticker_trend': '087', 'todays_low': '-', 'bid_realtime': '1054.00', 'change_50_sma': '+16.43%', 'more_info': 'N/A', 'price_book': '52.09', 'price_eps_estimate_current_year': '248.353', 'order_book_realtime': '100', 'todays_range': '-', 'change_from_52_week_high': '+389.23', 'book_value': '-', 'market_cap_realtime': '362.4B', 'dividend_yield': 'N/A', 'percent_change_from_52_week_high': '029', 'holdings_gain_percent': '1118.59', 'stock_exchange': '-0.69%', 'annualized_gain': '"- - -"', 'high_limit': '100', 'todays_value_change': '1084.75', 'short_ratio': '6.23', 'company_name': ' 276', 'trade_date': '-', 'dividend_pay_date': '"N/A"', 'change_200_sma': '+153.094', 'peg': '57.386B', 'bid_size': '"NasdaqNM"', 'last_trade_time_plus': '"N/A - 1084.75"', 'eps_estimate_next_quarter': '-', 'eps_estimate_current_year': '1836150', 'fiftytwo_week_range': '+55.96%', 'fiftytwo_week_low': '1092.3101', 'last_trade_date': '"12/18/2013"', 'holdings_value_realtime': '"GOOG"', 'ex_dividend_date': '"N/A"', 'after_hours_change_realtime': '"N/A - N/A"', 'price_sales': '-', 'change': '+14.89', 'eps_estimate_next_year': '"GOOG"', 'holdings_gain_percent_realtime': '-', 'eps': '300', 'one_year_target': '931.656', 'last_trade_time': '"4:00pm"', 'float_shares': 'N/A', 'change_percent_change': '"+14.89 - +1.39%"', 'last_trade_size': ' 334'}

Obtaining latest ystockquote

Sorry if this is more of a Git question than ystockquote, but how exactly can I get the latest version of ystockquote? Thanks in advance.

get_historical_prices not working

As of this week, get_historical_prices seems to either timeout or give URL not found responses.
I have tried from several platforms with the same results. Can others reproduce the error? Does anyone know the cause or a solution?

pprint(ystockquote.get_historical_prices('GOOGL', '2013-01-03', '2013-01-08'))
Traceback (most recent call last):
File "", line 1, in
File "//anaconda/lib/python2.7/site-packages/ystockquote.py", line 486, in get_historical_prices
resp = urlopen(req)
File "//anaconda/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "//anaconda/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "//anaconda/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "//anaconda/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "//anaconda/lib/python2.7/urllib2.py", line 1227, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "//anaconda/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 60] Operation timed out>

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.