Yahoo! Finance market data downloader (+faster Pandas Datareader)

Overview

Yahoo! Finance market data downloader

Python version PyPi version PyPi status PyPi downloads Travis-CI build status CodeFactor Star this repo Follow me on twitter

Ever since Yahoo! finance decommissioned their historical data API, many programs that relied on it to stop working.

yfinance aimes to solve this problem by offering a reliable, threaded, and Pythonic way to download historical market data from Yahoo! finance.

NOTE

The library was originally named fix-yahoo-finance, but I've since renamed it to yfinance as I no longer consider it a mere "fix". For reasons of backward-compatibility, fix-yahoo-finance now import and uses yfinance, but you should install and use yfinance directly.

Changelog »


==> Check out this Blog post for a detailed tutorial with code examples.


Quick Start

The Ticker module

The Ticker module, which allows you to access ticker data in a more Pythonic way:

Note: yahoo finance datetimes are received as UTC.

import yfinance as yf

msft = yf.Ticker("MSFT")

# get stock info
msft.info

# get historical market data
hist = msft.history(period="max")

# show actions (dividends, splits)
msft.actions

# show dividends
msft.dividends

# show splits
msft.splits

# show financials
msft.financials
msft.quarterly_financials

# show major holders
msft.major_holders

# show institutional holders
msft.institutional_holders

# show balance sheet
msft.balance_sheet
msft.quarterly_balance_sheet

# show cashflow
msft.cashflow
msft.quarterly_cashflow

# show earnings
msft.earnings
msft.quarterly_earnings

# show sustainability
msft.sustainability

# show analysts recommendations
msft.recommendations

# show next event (earnings, etc)
msft.calendar

# show ISIN code - *experimental*
# ISIN = International Securities Identification Number
msft.isin

# show options expirations
msft.options

# get option chain for specific expiration
opt = msft.option_chain('YYYY-MM-DD')
# data available via: opt.calls, opt.puts

If you want to use a proxy server for downloading data, use:

import yfinance as yf

msft = yf.Ticker("MSFT")

msft.history(..., proxy="PROXY_SERVER")
msft.get_actions(proxy="PROXY_SERVER")
msft.get_dividends(proxy="PROXY_SERVER")
msft.get_splits(proxy="PROXY_SERVER")
msft.get_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msft.option_chain(..., proxy="PROXY_SERVER")
...

To use a custom requests session (for example to cache calls to the API or customize the User-agent header), pass a session= argument to the Ticker constructor.

import requests_cache
session = requests_cache.CachedSession('yfinance.cache')
session.headers['User-agent'] = 'my-program/1.0'
ticker = yf.Ticker('msft aapl goog', session=session)
# The scraped response will be stored in the cache
ticker.actions

To initialize multiple Ticker objects, use

import yfinance as yf

tickers = yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects

# access each ticker using (example)
tickers.tickers.MSFT.info
tickers.tickers.AAPL.history(period="1mo")
tickers.tickers.GOOG.actions

Fetching data for multiple tickers

import yfinance as yf
data = yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

I've also added some options to make life easier :)

data = yf.download(  # or pdr.get_data_yahoo(...
        # tickers list or string as well
        tickers = "SPY AAPL MSFT",

        # use "period" instead of start/end
        # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
        # (optional, default is '1mo')
        period = "ytd",

        # fetch data by interval (including intraday if period < 60 days)
        # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
        # (optional, default is '1d')
        interval = "1m",

        # group by ticker (to access via data['SPY'])
        # (optional, default is 'column')
        group_by = 'ticker',

        # adjust all OHLC automatically
        # (optional, default is False)
        auto_adjust = True,

        # download pre/post regular market hours data
        # (optional, default is False)
        prepost = True,

        # use threads for mass downloading? (True/False/Integer)
        # (optional, default is True)
        threads = True,

        # proxy URL scheme use use when downloading?
        # (optional, default is None)
        proxy = None
    )

Managing Multi-Level Columns

The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance?

  • yfinance returns a pandas.DataFrame with multi-level column names, with a level for the ticker and a level for the stock price data
    • The answer discusses:
      • How to correctly read the the multi-level columns after saving the dataframe to a csv with pandas.DataFrame.to_csv
      • How to download single or multiple tickers into a single dataframe with single level column names and a ticker column

pandas_datareader override

If your code uses pandas_datareader and you want to download data faster, you can "hijack" pandas_datareader.data.get_data_yahoo() method to use yfinance while making sure the returned data is in the same format as pandas_datareader's get_data_yahoo().

from pandas_datareader import data as pdr

import yfinance as yf
yf.pdr_override() # <== that's all it takes :-)

# download dataframe
data = pdr.get_data_yahoo("SPY", start="2017-01-01", end="2017-04-30")

Installation

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

Install yfinance using conda:

$ conda install -c ranaroussi yfinance

Requirements

Optional (if you want to use pandas_datareader)

Legal Stuff

yfinance is distributed under the Apache Software License. See the LICENSE.txt file in the release for details.

P.S.

Please drop me an note with any feedback you have.

Ran Aroussi

Comments
  • simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

    simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

    I've been using yfinance for some time and was working great. All of a sudden, I am getting this error (sporadically) on the "download" when I specifically use the following:

    import yfinance as yf start = 'some valid date' end = 'another valid date' data = yf.download(tickers[x], start=starting_point, end=ending_point, progress=False)

    opened by Greengolfer 108
  • Peg Ratio value way off

    Peg Ratio value way off

    The Peg Ratio value for "FE", First Energy seems to be wrong, according to Google Finance the value is 2.99 but yfinance returns 43.37 on my script. This is how i got this value:

    import yfinance as yf
    
    symbol = yf.Ticker("FE")
    
    infos = (symbol.info)
    
    print(infos['pegRatio'])
    

    Output: 43.37

    It works just fine with other stock which is why i don't really get what the problem seems to be.

    opened by rickturner2001 93
  • Getting this Error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

    Getting this Error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

    Hallo I am keep getting an Error for different scripts her an exampl script: `tickers = gettickers('mdax') days = 30 returns, symbols = [], [] klines = {} for ticker in tickers[]: klines[ticker] = yf.download(ticker.upper(), interval='1d', period=f'{days}d', threads=False) if len(klines[ticker]) > 0:
    cumret = (pd.DataFrame(klines[ticker])['Close'].astype(float).pct_change() + 1).prod() - 1 returns.append(cumret) symbols.append(ticker)

    retdf = pd.DataFrame(returns, index=symbols, columns=['Return'])` print(retdf.Return.nlargest(3))

    I am getting an Error thrown for different stocks each time. Did yahoo change its site? Is there a fix for the problem? This is the Error: Traceback (most recent call last): File "C:\Users\User\Desktop\Python\pythonProject\stock\test_center.py", line 53, in klines[ticker] = yf.download(ticker.upper(), interval='1d', period=f'{days}d', threads=False) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\yfinance\multi.py", line 102, in download data = _download_one(ticker, period=period, interval=interval, File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\yfinance\multi.py", line 181, in download_one return Ticker(ticker).history(period=period, interval=interval, File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\yfinance\base.py", line 179, in history data = data.json() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 910, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\json_init.py", line 346, in loads return _default_decoder.decode(s) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

    Process finished with exit code 1

    opened by MaximilianPannenbaecker 38
  • AttributeError: 'float' object has no attribute 'upper'

    AttributeError: 'float' object has no attribute 'upper'

    Any ideas on the error below?

    My code works fine on windows locally on my laptop, it basically pulls data for a group of 5000 stocks 1 by 1. When i try to run it onlinus most of the symbols work fine, but i seem to get this error a handfull of times during the loop.

    Any ideas what might be causing it, i already have it wrapped in a try/except ststement but the error weirdly still shows (and the code continues if i use ctrl+c)

    Any help appreciated.

    Exception in thread Thread-1337: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.8/dist-packages/multitasking/init.py", line 104, in _run_via_pool return callee(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/yfinance/multi.py", line 191, in _download_one_threaded data = _download_one(ticker, start, end, auto_adjust, back_adjust, File "/usr/local/lib/python3.8/dist-packages/yfinance/multi.py", line 205, in _download_one return Ticker(ticker).history(period=period, interval=interval, File "/usr/local/lib/python3.8/dist-packages/yfinance/base.py", line 168, in history end = utils._parse_user_dt(end, tz) File "/usr/local/lib/python3.8/dist-packages/yfinance/utils.py", line 154, in _parse_user_dt dt = _tz.timezone(exchange_tz).localize(dt) File "/usr/local/lib/python3.8/dist-packages/pytz/init.py", line 170, in timezone if zone.upper() == 'UTC': AttributeError: 'float' object has no attribute 'upper'

    opened by gib-uk 36
  • Getting json.decoder.JSONDecodeError: Expecting value

    Getting json.decoder.JSONDecodeError: Expecting value

    Getting this error randomly and the thread is stuck. Tried upgrading the library but doesn't work.

    Here's the trace:

    Traceback (most recent call last):
      File "/usr/local/Cellar/[email protected]/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner
        self.run()
      File "/usr/local/Cellar/[email protected]/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run
        self._target(*self._args, **self._kwargs)
      File "/usr/local/lib/python3.9/site-packages/multitasking/__init__.py", line 102, in _run_via_pool
        return callee(*args, **kwargs)
      File "/usr/local/lib/python3.9/site-packages/yfinance/multi.py", line 169, in _download_one_threaded
        data = _download_one(ticker, start, end, auto_adjust, back_adjust,
      File "/usr/local/lib/python3.9/site-packages/yfinance/multi.py", line 181, in _download_one
        return Ticker(ticker).history(period=period, interval=interval,
      File "/usr/local/lib/python3.9/site-packages/yfinance/base.py", line 162, in history
        data = data.json()
      File "/usr/local/lib/python3.9/site-packages/requests/models.py", line 900, in json
        return complexjson.loads(self.text, **kwargs)
      File "/usr/local/Cellar/[email protected]/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 346, in loads
        return _default_decoder.decode(s)
      File "/usr/local/Cellar/[email protected]/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 337, in decode
        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      File "/usr/local/Cellar/[email protected]/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 355, in raw_decode
        raise JSONDecodeError("Expecting value", s, err.value) from None
    json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
    opened by danlinenberg 32
  • Get earnings date historics

    Get earnings date historics

    Hi, I couldn't find a way to access earnings date history for a given ticker. It would be great if could be added to the library. Data seem to be easyly accessible:

    ` web_request = requests.get(url='https://finance.yahoo.com/calendar/earnings?symbol=TD.TO',headers=headers)

    web_tables = pd.read_html( web_request.text)

    print(web_tables[0]) ` Thanks!

    opened by nono-london 30
  • json.decoder.JSONDecodeError

    json.decoder.JSONDecodeError

    Hi, I am using yfinance daily. Thank you very much for support! But today I received on all scripts I am using this error: Something changed with new version that is causing this?

    Traceback (most recent call last): File "C:/Users/user/Desktop/NOTES/Codes/project/yf.py", line 7, in prices.append(yf.Ticker(ticker).history(period="1d")["Close"].values[0]) File "C:\Users\user\Desktop\NOTES\Codes\projectI\venv\lib\site-packages\yfinance\base.py", line 157, in history data = data.json() File "C:\Users\user\Desktop\NOTES\Codes\project\venv\lib\site-packages\requests\models.py", line 900, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\json_init_.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

    opened by draew6 30
  • Futures index does not return Saturday and Sunday data

    Futures index does not return Saturday and Sunday data

    There are futures indexes that trade on Saturday and Sunday that are tracked by Yahoo Finance. These indexes are denoted with tickers such as:

    ES=F is ^GSPC futures RTY=F is Russell 2000 futures MNQ=F is NASDAQ futures

    The yfinance package does not return the Saturday and Sunday values for these kinds of tickers. I've been looking for where in the yfinance code the Saturday and Sunday values are dropped but I can't find it. Perhaps the data is not returned in the first place.

    opened by amichae2 22
  • KeyError: 'exchangeTimezoneName' when accessing ticker history

    KeyError: 'exchangeTimezoneName' when accessing ticker history

    Current yfinance 0.1.75 raises an exception when running the following:

    import yfinance as yf
    
    
    def _main():
        stock_data = yf.download(
            "AFN",
            start="2018-01-01",
            end="2018-12-31",
            group_by="ticker",
            threads=False
        )
        print(stock_data)
    
    
    if __name__ == "__main__":
        _main()
    
      stock_data = yf.download(
      File "/Users/manoel/opt/anaconda3/envs/Qiskitenv/lib/python3.8/site-packages/yfinance/multi.py", line 120, in download
        data = _download_one(ticker, period=period, interval=interval,
      File "/Users/manoel/opt/anaconda3/envs/Qiskitenv/lib/python3.8/site-packages/yfinance/multi.py", line 205, in _download_one
        return Ticker(ticker).history(period=period, interval=interval,
      File "/Users/manoel/opt/anaconda3/envs/Qiskitenv/lib/python3.8/site-packages/yfinance/base.py", line 148, in history
        end = utils._parse_user_dt(end, self._get_ticker_tz())
      File "/Users/manoel/opt/anaconda3/envs/Qiskitenv/lib/python3.8/site-packages/yfinance/base.py", line 328, in _get_ticker_tz
        tkr_tz = self.info["exchangeTimezoneName"]
    KeyError: 'exchangeTimezoneName'
    

    Running the same sample against the previous release returns:

    [*********************100%***********************]  1 of 1 completed
                     Open       High        Low      Close  Adj Close  Volume
    Date                                                                     
    2018-01-02  29.799999  29.799999  29.799999  29.799999  29.799999       0
    2018-01-03  30.000000  30.000000  30.000000  30.000000  30.000000       0
    2018-01-04  30.000000  30.000000  30.000000  30.000000  30.000000       0
    2018-01-05  30.200001  30.200001  30.200001  30.200001  30.200001       0
    2018-01-08  30.000000  30.000000  30.000000  30.000000  30.000000       0
    2018-01-09  30.200001  30.200001  30.200001  30.200001  30.200001       0
    2018-01-10  32.799999  32.799999  32.799999  32.799999  32.799999       0
    2018-01-11  31.799999  31.799999  31.799999  31.799999  31.799999       0
    2018-01-12  30.799999  30.799999  30.799999  30.799999  30.799999       0
    2018-01-16  30.200001  30.200001  30.200001  30.200001  30.200001       0
    2018-01-17  30.799999  30.799999  30.799999  30.799999  30.799999       0
    2018-01-18  30.799999  30.799999  30.799999  30.799999  30.799999       0
    2018-01-19  30.799999  30.799999  30.799999  30.799999  30.799999       0
    2018-01-22  31.400000  31.400000  31.400000  31.400000  31.400000       0
    2018-01-23  32.000000  32.000000  32.000000  32.000000  32.000000       0
    2018-01-24  31.600000  31.600000  31.600000  31.600000  31.600000       0
    2018-01-25  31.200001  31.200001  31.200001  31.200001  31.200001       0
    2018-01-26  32.200001  32.200001  32.200001  32.200001  32.200001       0
    2018-01-29  31.799999  31.799999  31.799999  31.799999  31.799999       0
    2018-01-30  31.520000  31.520000  31.520000  31.520000  31.520000       0
    

    If I run with threads=True it will raise the exception and hang.

    Yahoo spam 
    opened by manoelmarques 21
  • Yfinance Intermittently working

    Yfinance Intermittently working

    I have used yfinance for a while using a very old mac and haven't had any problems. I recently upgraded my computer to Windows 11 and am trying to run basic yfinance functions like yf.download in jupyter notebook on a chrome browser and I keep gettting the error message "No data found for this date range, symbol may be delisted" as well as error 10060. I have tried downgrading to older library versions and using the "pip install yfinance --upgrade --no-cache-dir" recommended fix but I am still getting this problem. The workaround I came up with is to keep retrying the yf.download and sleeping for a couple seconds if it fails. It seems to eventually download after around 10 tries or so but this doesn't seem to be the most elegant solution. I have tried changing my firewall settings and it doesn't seem like my computer is blocking anything. I am pretty stumped, if you have any suggestions I would really appreciate it!

    Windows 
    opened by locfinessemonster 20
  • Financial values (Income Statement) are differnt between website and yfinance

    Financial values (Income Statement) are differnt between website and yfinance

    Values for example EBIT or Gross Profit are always diferent. I cheked differend companies (IBM, Google, Deutsche Wohnen and so on). The values are always different between webside and yfinance

    a part of the code: IBM = yf.Ticker("IBM") print(IBM.financials)

    then compare the values between the site (see link) and output values from python instruction.

    yf-financials 
    opened by prischon 20
  • Yahoo changed access?

    Yahoo changed access?

    I tried the code in the example of yfinance and it returns an error. Code: import yfinance as yf msft = yf.Ticker("MSFT")

    get stock info

    msft.info

    get historical market data

    hist = msft.history(period="max") Error: Traceback (most recent call last):

    File "C:\Users\Win-7\anaconda3\lib\site-packages\requests\models.py", line 971, in json return complexjson.loads(self.text, **kwargs)

    File "C:\Users\Win-7\anaconda3\lib\site-packages\simplejson_init_.py", line 525, in loads return _default_decoder.decode(s)

    File "C:\Users\Win-7\anaconda3\lib\site-packages\simplejson\decoder.py", line 370, in decode obj, end = self.raw_decode(s)

    File "C:\Users\Win-7\anaconda3\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode return self.scan_once(s, idx=_w(s, idx).end())

    File "C:\Users\Win-7\anaconda3\lib\site-packages\simplejson\scanner.py", line 79, in scan_once return _scan_once(string, idx)

    File "C:\Users\Win-7\anaconda3\lib\site-packages\simplejson\scanner.py", line 70, in _scan_once raise JSONDecodeError(errmsg, string, idx)

    JSONDecodeError: Expecting value

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):

    File "F:\AI\Wavelets\Production\untitled1.py", line 16, in hist = msft.history(period="max")

    File "C:\Users\Win-7\anaconda3\lib\site-packages\yfinance\base.py", line 157, in history data = data.json()

    File "C:\Users\Win-7\anaconda3\lib\site-packages\requests\models.py", line 975, in json raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)

    JSONDecodeError: Expecting value

    opened by GuyFBordelon 4
  • Can't find EBITDA data that matches yahoo finance site

    Can't find EBITDA data that matches yahoo finance site

    Whenever I try to get ebitda data for a specific ticker it returns a number that doesn't match the website. An example as of 1/4/23 would be:

    msft = yf.Ticker("MSFT")

    msft.info['ebitda']

    98841001984

    The yahoo finance website shows the number as:

    image

    yfinance version = 0.2.3

    opened by AbdulHassan0 0
  • Ticket data from different timezone are not aligned (bug introduced with #1085)

    Ticket data from different timezone are not aligned (bug introduced with #1085)

    I am trying to find correlations between tickets in differnet timezone (one in the New York Stock exchange and the other in the London Stock Exchange). Due to changes to the timezone logic, the data in each row of yfinance.download are no longer the data of the Tickets at the same time. Using ignore_tz=False fixes this problem. This problem didn't exist with version 0.1.77 and previous. So I think by default ignore_tz should be set to True as that behaviour is consistent with the previous minor versions.

    opened by DE0CH 1
  • sqlite database is locked when using multithread download

    sqlite database is locked when using multithread download

    • Info about your system:
      • yfinance version
        • 0.2.3
      • operating system
        • Windows WSL Ubuntu 20.04, running in Docker image from python:3.7-slim
    • Simple code that reproduces your problem
    import yfinance as yf
    start_date = '2017-01-01'
    end_date= '2022-04-29'
    tickers = 'SPY TSLA NVDA MSFT'
    
    data = yf.download(  # or pdr.get_data_yahoo(...
        # tickers list or string as well, cannot be an numpy.ndarray
        tickers=tickers,
    
        # start date
        start=start_date,
    
        # end date
        end=end_date,
    
        # fetch data by interval (including intraday if period < 60 days)
        # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
        # (optional, default is '1d')
        interval="1d",
    
        # group by ticker (to access via data['SPY'])
        # (optional, default is 'column')
        group_by='ticker',
    
        # adjust all OHLC automatically
        # (optional, default is False)
        auto_adjust=False,
    
        # download pre/post regular market hours data
        # (optional, default is False)
        prepost=True,
    
        # use threads for mass downloading? (True/False/Integer)
        # (optional, default is True)
        threads=True,
    
        # proxy URL scheme use use when downloading?
        # (optional, default is None)
        proxy=None
    )
    
    • The error message
      • - NVDA: OperationalError('database is locked')

    When running the multithread download from my flask server in Docker image, I sometime saw this error message, the failed symbol can be different one. The failing symbol will still produce empty dataset.

    Any suggestion on how to know there is an error when calling yf.download(threads=True) or is there a way to fix the sqlite database lock issue? (Maybe by increasing the timeout?)

    opened by gogog22510 5
  • Yahoo's dividend-adjustment of weekly & monthly prices is wrong

    Yahoo's dividend-adjustment of weekly & monthly prices is wrong

    Yahoo applies dividend-adjustment back in time - a dividend affects all older prices, but not future prices. Fine if Yahoo is consistent and implements correctly. But for weekly & monthly intervals containing a dividend before last working day, Yahoo is adjusting the close price. Example:

    tkr = "I3E.L"
    dat = yf.Ticker(tkr)
    
    • Daily prices:
    df = dat.history(start="2022-11-07", end="2022-11-14", interval="1d", auto_adjust=False)
    df[["Close","Adj Close","Dividends"]]
    

    | Date | Close | Adj Close | Dividends | | - | - | - | - | | 2022-11-07 00:00:00+00:00 | 24.600000 | 24.451147 | 0.0000 | | 2022-11-08 00:00:00+00:00 | 24.500000 | 24.351751 | 0.0000 | | 2022-11-09 00:00:00+00:00 | 23.549999 | 23.407499 | 0.0000 | | 2022-11-10 00:00:00+00:00 | 23.500000 | 23.500000 | 0.1425 | | 2022-11-11 00:00:00+00:00 | 23.500000 | 23.500000 | 0.0000 |

    Dividend is mid-week so Friday close not affected.

    • Weekly prices:
    df = dat.history(start="2022-11-07", end="2022-11-14", interval="1wk", auto_adjust=False)
    df[["Close","Adj Close","Dividends"]]
    

    | Date | Close | Adj Close | Dividends | | - | - | - | - | | 2022-11-07 00:00:00+00:00 | 23.5 | 23.357803 | 0.1425

    Yahoo has applied mid-week dividend adjustment forward to Friday close, wrong! Problem also exists in monthly data.

    This also means how yfinance adjusts the high & low via auto_adjust is wrong. Currently is doing adjust(week high) when it should be max(adjusted daily highs).

    Solution

    Only way to correct is for yfinance to fetch 1d data and group to create weekly/monthly data. Any opposition to correcting this? Because means contradicting Yahoo's Adj Close on history page.

    opened by ValueRaider 0
Releases(0.2.3)
Owner
Ran Aroussi
Founder @Tradologics. Creator of tools for traders. Programming is how I meditate.
Ran Aroussi
Python Backtesting library for trading strategies

backtrader Yahoo API Note: [2018-11-16] After some testing it would seem that data downloads can be again relied upon over the web interface (or API v

DRo 9.8k Dec 30, 2022
Fourth and final milestone project

Milestone Project 4: Pound Dog Click link to visit "Pound Dog" Aim of the project The aim of this project is to provide access to a website informing

Jamie Wilson 1 Oct 31, 2021
Performance analysis of predictive (alpha) stock factors

Alphalens Alphalens is a Python Library for performance analysis of predictive (alpha) stock factors. Alphalens works great with the Zipline open sour

Quantopian, Inc. 2.5k Dec 28, 2022
An open source reinforcement learning framework for training, evaluating, and deploying robust trading agents.

TensorTrade: Trade Efficiently with Reinforcement Learning TensorTrade is still in Beta, meaning it should be used very cautiously if used in producti

4k Dec 30, 2022
crypto utilities as a way of learning

cryptos Just me developing a pure Python from-scratch zero-dependency implementation of Bitcoin for educational purposes. This includes a lot of the c

Andrej 958 Jan 02, 2023
Technical Analysis Library using Pandas and Numpy

Technical Analysis Library in Python It is a Technical Analysis library useful to do feature engineering from financial time series datasets (Open, Cl

Darío López Padial 3.4k Jan 02, 2023
A proper portfolio tracker. Featuring historical allocation, cash flows and real returns.

Python Portfolio Analytics A portfolio tracker featuring account transactions, historical allocation, dividends and splits management and endless perf

Simone Precicchiani 13 Aug 13, 2022
Python sync/async framework for Interactive Brokers API

Introduction The goal of the IB-insync library is to make working with the Trader Workstation API from Interactive Brokers as easy as possible. The ma

Ewald de Wit 2k Dec 30, 2022
An Algorithmic Trading Library for Crypto-Assets in Python

Service Master Develop CI Badge Catalyst is an algorithmic trading library for crypto-assets written in Python. It allows trading strategies to be eas

Enigma 2.4k Jan 05, 2023
Python Algorithmic Trading Library

PyAlgoTrade PyAlgoTrade is an event driven algorithmic trading Python library. Although the initial focus was on backtesting, paper trading is now pos

Gabriel Becedillas 3.9k Jan 01, 2023
Portfolio and risk analytics in Python

pyfolio pyfolio is a Python library for performance and risk analysis of financial portfolios developed by Quantopian Inc. It works well with the Zipl

Quantopian, Inc. 4.8k Jan 08, 2023
Indicator divergence library for python

Indicator divergence library This module aims to help to find bullish/bearish divergences (regular or hidden) between two indicators using argrelextre

8 Dec 13, 2022
Software for quick purchase of mystery boxes on Binance.

english | русский язык Software for quick purchase of mystery boxes on Binance. Purpose Installation & setup Motivation Specification Disclaimer Purpo

Ellis 5 Mar 08, 2022
rotki is an open source portfolio tracking, analytics, accounting and tax reporting tool that respects your privacy.

rotki is an open source portfolio tracking, analytics, accounting and tax reporting tool that respects your privacy. The mission of rotki is to bring transparency into the crypto and financial sector

Rotki 2k Dec 30, 2022
This repository provides all Python codes and Jupyter Notebooks of the book Python for Finance

Python for Finance (O'Reilly) This repository provides all Python codes and Jupyter Notebooks of the book Python for Finance -- Analyze Big Financial

Yves Hilpisch 1.6k Jan 03, 2023
Supply a wrapper ``StockDataFrame`` based on the ``pandas.DataFrame`` with inline stock statistics/indicators support.

Stock Statistics/Indicators Calculation Helper VERSION: 0.3.2 Introduction Supply a wrapper StockDataFrame based on the pandas.DataFrame with inline s

Cedric Zhuang 1.1k Dec 28, 2022
:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.

Backtesting.py Backtest trading strategies with Python. Project website Documentation the project if you use it. Installation $ pip install backtestin

3.1k Dec 31, 2022
'Personal Finance' is a project where people can manage and track their expenses

Personal Finance by Abhiram Rishi Pratitpati 'Personal Finance' is a project where people can manage and track their expenses. It is hard to keep trac

Abhiram Rishi Prattipati 1 Dec 21, 2021
ARCH models in Python

arch Autoregressive Conditional Heteroskedasticity (ARCH) and other tools for financial econometrics, written in Python (with Cython and/or Numba used

Kevin Sheppard 1k Jan 04, 2023
High-performance TensorFlow library for quantitative finance.

TF Quant Finance: TensorFlow based Quant Finance Library Table of contents Introduction Installation TensorFlow training Development roadmap Examples

Google 3.5k Jan 01, 2023