какая версия python для работы с yahoo finance

Как скачать исторические котировки c yahoo finance и финама с помощью python

какая версия python для работы с yahoo finance. Смотреть фото какая версия python для работы с yahoo finance. Смотреть картинку какая версия python для работы с yahoo finance. Картинка про какая версия python для работы с yahoo finance. Фото какая версия python для работы с yahoo finance

В одной из прошлых заметок мне нужно было скачать исторические котировки по 650 активам. Часть из них на российском рынке, часть крипта и большая часть на рынке США. Всё, что касается крипты, валют и американского рынка качал с yahoo finance. Российский рынок качал с финама. Естественно качал с помощью питона. Дальше расскажу как это можно повторить.

Yahoo finance и python

Пакет yfinance. Гитахб github.com/ranaroussi/yfinance Установка командой: pip install yfinance

Можно качать не только дневные данные. Интервалы из документации: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo На практике данные меньше дневных сильно ограничены. Например, часовые доступны за 60 последних дней.

Перейдём к делу, как качать котировки:

import yfinance as yf

data = yf.download(«TSLA», start=«2017-01-01», end=«2017-04-30»)

Как добавить интервал:

data = yf.download(«TSLA», start=«2017-01-01», end=«2017-04-30», interval=’1h’)

Данные скачиваются в датафрейм. Датафрейм можно сохранить в csv:

Finam и python

Нашёл замечательный пакет finam-export. Гитхаб github.com/ffeast/finam-export Установить можно командой: pip install finam-export

В отличии от яху финанс можно качать даже тиковые данные за любой срок! Правда где-то читал, что за слишком большой срок данные могут качаться несколько дней. Я пока не придумал как использовать тиковые данные.

Сам пакет не так хорошо продуман, как предыдущий. Иногда приходится поломать голову.

Как тут качать? Минимальный набор:

from finam import Exporter, Market, Timeframe

exporter = Exporter()
ticker = ‘SBER’
asset = exporter.lookup(name=ticker, market=Market.SHARES)
asset_id = asset[asset[‘name’] == ticker].index[0]
data = exporter.download(asset_id, market=Market.SHARES)

Ищем айдишник тикера в финаме и по нему скачиваем котировки.

Вот так можно задавать другие параметры:

data = exporter.download(asset_id, market=Market.SHARES, start_date=datetime.date(2017, 1, 1), end_date=datetime.date(2018, 1, 1), timeframe=Timeframe.DAILY)

Особенности finam-export

Тикер нужно искать в том рынке, где он есть. Фьючерсы во фьючерсах, акции в акциях. Если искать без рынка, то у одного тикера может найтись несколько айдишников. Константы по рынкам и таймфреймам можно посмотреть в файле: github.com/ffeast/finam-export/blob/master/finam/const.py

Иногда в строчке asset = exporter.lookup(name=ticker, market=Market.SHARES) нужно name заменить на code, будет вот так asset = exporter.lookup(code=ticker, market=Market.SHARES) Хрен его знает что от этого меняется, но иногда работает так иногда так.

В константах может не быть рынка, который вам нужен. Например для биткоина айдишник рынка 520. Его нет в константах. Я пробовал его добавлять руками, но котировки всё равно не качались. Если знаете как скачать, напишите.

Если качать много тикеров, то нужно задавать задержку между заросами в одном тикере и между тикерами, инче будет 403 ошибка. Я прописывал через рандом в запросе: data = exporter.download(asset_id, market=Market.SHARES, start_date=datetime.date(2017, 1, 1), end_date=datetime.date(2018, 1, 1), timeframe=Timeframe.DAILY, delay=random.randint(3,5)) И в цикле: time.sleep(random.randint(3,5))

Как скорость?

Да в целом норм. Дневные данные по 650 тикерам с января 2007 года вчера скачались примерно за час.

Источник

Получение котировок акций при помощи Python

Привет, Хабр! Представляю вашему вниманию перевод статьи «Historical Stock Price Data in Python» автора Ishan Shah.

Статья о том, как получить ежедневные исторические данные по акциям, используя yfinance, и минутные данные, используя alpha vantage.

какая версия python для работы с yahoo finance. Смотреть фото какая версия python для работы с yahoo finance. Смотреть картинку какая версия python для работы с yahoo finance. Картинка про какая версия python для работы с yahoo finance. Фото какая версия python для работы с yahoo finance

Как вы знаете, акции относятся к очень волатильному инструменту и очень важно тщательно анализировать поведение цены, прежде чем принимать какие-либо торговые решения. Ну а сначала надо получить данные и python может помочь в этом.

Биржевые данные могут быть загружены при помощи различных пакетов. В этой статье будут рассмотрены yahoo finance и alpha vantage.

Yahoo Finance

Сначала испытаем yfianance пакет. Его можно установить при помощи команды pip install yfinance. Приведенный ниже код показывает, как получить данные для AAPL с 2016 по 2019 год и построить скорректированную цену закрытия (скорректированная цена закрытия на дивиденды и сплиты) на графике.

какая версия python для работы с yahoo finance. Смотреть фото какая версия python для работы с yahoo finance. Смотреть картинку какая версия python для работы с yahoo finance. Картинка про какая версия python для работы с yahoo finance. Фото какая версия python для работы с yahoo finance

Ну а если необходимо получить по нескольким акциям, то необходимо внести небольшое дополнение в код. Для хранения значений используется DataFrame. При помощи пакета matplotlib и полученных данных можно построить график дневной доходности.

какая версия python для работы с yahoo finance. Смотреть фото какая версия python для работы с yahoo finance. Смотреть картинку какая версия python для работы с yahoo finance. Картинка про какая версия python для работы с yahoo finance. Фото какая версия python для работы с yahoo finance

какая версия python для работы с yahoo finance. Смотреть фото какая версия python для работы с yahoo finance. Смотреть картинку какая версия python для работы с yahoo finance. Картинка про какая версия python для работы с yahoo finance. Фото какая версия python для работы с yahoo finance

Для значений по российским акциям есть небольшая тонкость. К названию акцию добавляется точка и заглавными буквами ME. Спасибо знатоки на смартлабе подсказали.

какая версия python для работы с yahoo finance. Смотреть фото какая версия python для работы с yahoo finance. Смотреть картинку какая версия python для работы с yahoo finance. Картинка про какая версия python для работы с yahoo finance. Фото какая версия python для работы с yahoo finance

Получение минутных данных при помощи Alpha vantage

К сожалению, бесплатная версия Yahoo Finance не позволяет получить данные с периодичностью меньше, чем дневная. Для этого можно использовать пакет Alpha vantage, которые позволяет получить такие интервалы, как 1 мин, 5 мин, 15 мин, 30 мин, 60 мин.

какая версия python для работы с yahoo finance. Смотреть фото какая версия python для работы с yahoo finance. Смотреть картинку какая версия python для работы с yahoo finance. Картинка про какая версия python для работы с yahoo finance. Фото какая версия python для работы с yahoo finance

В дальнейшем эти данные можно проанализировать, создать торговую стратегию и оценить эффективность при помощи пакета pyfolio. В нем можно оценить коэффициент Шарпа, коэффициент Сортино, максимальную просадку и многие другие необходимые показатели.

Надеюсь, что мой перевод оригинальной статьи будет для Вас полезен. Код был проверен и все работает. Но пока для меня остался вопрос в возможности использования Alpha vantage для российского рынка.

Источник

yahoo_finance_async 0.1.1

pip install yahoo_finance_async Copy PIP instructions

Released: Aug 26, 2020

A Python async API wrapper for the deprecated (but currently still working) Yahoo Finance API

Navigation

Project links

Statistics

View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery

License: MIT License

Tags yahoo, finance, python, API, async

Requires: Python >=3.6

Maintainers

Classifiers

Project description

yahoo-finance-async

A simple Python async API wrapper for the deprecated (but currently still working) Yahoo Finance API.

Although the Yahoo Finance API has officially been closed down, it does still work and it provides a free access to a vast number of stocks.

Why async?

There are many Yahoo Finance API libraries available on PyPi which use synchronous functions. There do not seem to be async functions available yet (as far as I could find). I needed an async version for a simple project to collect candle data (OHLC) for various stocks.

Endpoints available

Note that currently this API wrapper does not cover all the Yahoo Finance endpoints. In fact currently it only covers:

Getting started

Install from PyPi using

Note that you import it into your module with underscores import yahoo_finance_async

This library has a simple class called OHLC which has a simple class method (actually an async coroutine) called fetch() which will fetch and parse the candle (OHLC) data.

You need to await the response of this coroutine.

For example to fetch this historical data for the stock AAPL:

The returned result is a dictionary with two parts:

Additional parameters

Additional parameters can be passed to the OHLC.fetch() class method

The Interval and History objects are Enums which show which time periods are available on the API.

Example notebook

To see a live example you can look at the attached notebook

Rate limits

Be careful and kind to the Yahoo Finance API and don’t hit it too hard.

Contributing

Currently this API is focused just on the OHLC candle data. If you wish to contribute and extend the functionality please do. Comments, suggestions and pull requests are welcome.

Developers should clone the GitHub repo, and then install the development dependencies in the requirement-dev.txt file. Run all tests with pytest.

If you do contribute please also keep tests and documentation up to date. Thanks.

Источник

Разработка онлайн-сервиса для инвесторов на pythonanywhere.com с использованием данных Yahoo Finance

какая версия python для работы с yahoo finance. Смотреть фото какая версия python для работы с yahoo finance. Смотреть картинку какая версия python для работы с yahoo finance. Картинка про какая версия python для работы с yahoo finance. Фото какая версия python для работы с yahoo finance

Немного об инвестициях

Интересоваться темой инвестиций я начал еще летом 2019 года и сразу же окунулся в море разнообразных публикаций и видеоблогеров, которые в разнобой давали советы на тему того, как и куда инвестировать. Стало ясно, что в мире инвестиций существует два основных способа принятия решений, которые основываются на фундаментальном и техническом анализе. Первый способ больше подходит для долгосрочных инвестиций, а второй для спекуляций.

Через какое-то время пришло понимание несомненной пользы от проигрывания различных исторических сценариев типа «а что было бы, если бы я инвестировал средства в таком-то году и на такой-то срок». Подобного рода анализ позволяет почувствовать разницу между ценными бумагами пригодными для инвестирования и спекуляций и формирует у начинающего инвестора понимание, в какие финансовые инструменты и на какие сроки стоит инвестировать.

Созревание идеи, выбор хоста и архитектуры веб-сервиса

С течением времени возникла идея создать сервис в форме сайта, который бы позволил проигрывать исторические сценарии инвестирования в разнообразные финансовые инструменты.

И следующим шагом стало определение трех ключевых моментов:

Что касается языков программирования, по поводу фронтенда никаких сомнений изначально не было. Все достаточно стандартно: html + css + javascript. Бэкенд было решено писать на python, так как это на сегодняшний день один из самых популярных и поддерживаемых языков быстрой разработки и прототипирования. Все последующие решения в какой-то мере являлись следствием выбора, сделанного выше.

В качестве хоста был выбран pythonanywhere.com, отличительная особенность которого заключается в том, что он заточен на программирование на python и предлагает относительно дешевый тариф в 5 долларов в месяц. Последующая разработка веб-сайта велась с использованием фреймворка Django. Данный фреймворк хотя и не считается самым простым, но зато снабжает разработчика развернутым инструментарием в виде представлений, шаблонов и подключаемых готовых приложений, что в сумме позволяет построить полноценный сайт.
В плане выбора источника данных, почти сразу мое внимание привлек такой сервис как Yahoo Finance и, соответственно, библиотека yfinance предоставляющая удобный API для python.

О некоторых возможностях pythonanywhere.com

Хостинг pythonanywhere позволяет работать в нескольких режимах:

Удобный дашборд дает быстрый доступ к файлам и папкам, к консоли и любым настройкам. Встроена поддержка https, подключаемых доменных имен, а также защита контента сайта паролем. Доступен мониторинг трафика, а также логи сервера по ссылке в дашборде.

Отдельно хотел бы отметить еще одно несомненное удобство для разработчика. Помимо логов сервера при возникновении ошибок на стороне бэкенда часто прямо в текущем окне браузера выдается трассировка и локальные значения переменных в момент вызова соответствующих функций и методов. Причем трассировку можно увидеть даже в окне браузера на смартфоне.
Подобного рода режим отладки лично мне много раз сильно помогал, позволяя исправлять ошибки в коде буквально на лету.

Еще один немаловажный момент, который, несомненно, стоит внимания, — это работа с системами управления версиями. Во встроенной консоли Bash доступны git, svn и hg/mercurial.

Работа с данными

Провайдера финансовой информации Yahoo Finance и библиотеку yfinance я выбрал по причине отсутствия абонентской платы и наличия доступа к ежедневным обновлениям биржевой информации. Через API yfinance онлайн-сервис на лету подтягивает информацию с трех американских бирж NASDAQ, NYSE и AMEX. Однако стоит сразу обратить внимание на то, что на сайте разработчика yfinance встречается предупреждение о запрете коммерческого использования.

Что касается технологии веб-серверного взаимодействия, первоначально в браузер грузится шаблон с html-разметкой. Следующим шагом запускается javascript, который методом get-запросов подтягивает всю необходимые данные с сервера. Обновление содержимого страницы выполняется по технологии Ajax через интерфейсы библиотеки jQuery.

Все данные онлайн-сервиса хранятся в двух форматах: csv и SQLite. Такой выбор позволил быстро приступить к реализации основной логики без необходимости устанавливать и настраивать сервер баз данных.

Немного про Django

Хотел бы еще отдельно остановиться на трех программных компонентах, которые были встроены в архитектуру сайта готовыми блоками, что существенно ускорило разработку. Я имею в виду панель администратора Django admin, модуль управления сессиями django.contrib.sessions и фреймворк «excontrib»/django_comments.

Django позволяет собирать проекты из отдельных программных компонент, называемых приложениями. Один раз написанные приложения можно многократно использовать в разных проектах. Для того чтобы встроить в проект указанные выше компоненты, необходимо их в явном виде указать в файле settings.py

Помимо этого, следует соответствующим образом настроить шаблоны URL для выполнения запросов со стороны браузера:

Как видно из приведенных фрагментов кода, встроить готовые компоненты не так уж и сложно, и в итоге они добавляют проекту существенную часть функционала.

Для запуска панели администратора после разворачивания фреймворка django требуется выполнить несколько простых шагов: проверить настройки файла settings.py, выполнить миграцию встроенных моделей данных и создать суперпользователя. Администратору задается свой персональный логин, пароль и почтовый ящик. По умолчанию доступ к панели администратора осуществляется путем добавления стандартного пути /admin/ к URL домена.
Внутри панели предусмотрен удобный интерфейс для управления встроенной базой данных. Эта база данных по умолчанию хранит в себе информацию о пользователях и группах пользователей. Это очень удобно, поскольку легко реализовать авторизацию пользователей на сайте. А если принципиально важна скорость запуска сайта, можно сэкономить время и не создавать отдельную страницу для того, чтобы заводить новых пользователей и предоставлять им права. Достаточно зайти в панель администратора и через UI добавить новую запись в базу. Однако такое решение годится только для малого числа пользователей, так как не дает пользователям возможность самим регистрироваться и сбрасывать пароль.

Еще одна особенность панели администратора заключается в том, что она дает доступ не только к данным о пользователях, но и в принципе к любым данным, которые хранятся в базе под управлением Django. Например, у меня помимо данных об авторизованных пользователях в базе частично хранится контент сайта и комментарии, оставленные посетителями.

Расскажу про лайфхак, которым я воспользовался для добавления на страницу «About myself» формы обратной связи. Для того чтобы не писать отдельный код ни для браузера, ни для обработки данных на сервере, вместо формы обратной связи в соответствующий html-шаблон был встроен стандартный блок комментариев, но при этом была удалена возможность просматривать историю. При таком подходе данные формы обратной связи обрабатываются и хранятся в той же таблице, что и комментарии посетителей сайта.

Управление сессиями было реализовано с использованием встроенного модуля django.contrib.sessions. В объектах сессий хранится информация о настройках, выбранных пользователями при посещении сайта. В частности, в сессиях хранится выбранный период инвестирования, исторический период для выполнения анализа, язык сайта.

Немного остановлюсь на том, как сделал сайт мультиязычным. Для меня было важно найти простое и быстрое решение, при котором можно было бы зайти в хостинг панель и отредактировать текст любой статьи буквально в два клика. Поэтому для хранения текстов статей выбрал формат независимых текстовых файлов, а не загрузку в базу. При условии небольшого количества статей (грубо говоря, до 10) и всего двух вариантов выборка языка (русский и английский) такое решение считаю вполне приемлемым. Опять-таки все зависит от масштаба.
И последнее, на чем хотел бы остановиться, — это применение шаблонов Django. Помимо всего прочего, шаблоны позволяют импортировать в html-страницу значения переменных непосредственно из кода на питоне, а также собирать html-страницы из нескольких независимых блоков. В качестве иллюстрации приведу пример непосредственно из своего кода.

Встраивание нескольких блоков с динамическим контентом в общий скелет html-страницы:

Здесь article_file_name, online_service_file_name и comments_file_name фактически представляют собой названия переменных, через которые передаются пути к html-файлам c добавляемым контентом.

Заключение. Полезный опыт самостоятельной разработки веб-сервиса

Платформа pythonanywhere является в целом удачным решением для разработки веб-приложений на основе Django. И, если у Вас есть собственные идеи, то двух-трех месяцев Вам будет вполне достаточно для того, чтобы разобраться в основах и реализовать какое-нибудь простое веб-приложение, даже если Вы не являетесь профессиональным веб-разработчиком.

Такой опыт может быть очень полезен менеджерам, аналитикам и всем, кому по долгу службы приходится иметь дело с веб-разработкой и веб-сервисами, особенно на этапе бета-тестирования. Вы сможете лучше понимать смысл сообщений об ошибках сервера, продуктивней общаться с технической поддержкой и представителями разработки.

Источник

Yahoo_fin Documentation

What is yahoo_fin?

Yahoo_fin is a Python 3 package designed to scrape historical stock price data, as well as to provide current information on market caps, dividend yields, and which stocks comprise the major exchanges. Additional functionality includes scraping income statements, balance sheets, cash flows, holder information, and analyst data. The package includes the ability to scrape live (real-time) stock prices, capture cryptocurrency data, and get the most actively traded stocks on a current trading day. Yahoo_fin also contains a module for retrieving option prices and expiration dates.

The latest version of yahoo_fin can also scrape earnings calendar history and has an additional module for scraping financial news RSS feeds.

If you like yahoo_fin and / or this blog, consider making a contribution here to support the project.

Table of Contents

For navigating yahoo_fin’s documentation, click on any of the links below.

To see in-depth examples, check out my video series on YouTube or the following posts:

Two intro videos in the series are below.

Installation & Getting historical / real-time stock prices

Easily scraping ticker lists

Updates

Update: July 9th, 2021

yahoo_fin 0.8.9.1 is the latest version of yahoo_fin. This includes a second collection of patches due to recent changes in Yahoo Finance’s website, which were affecting get_data, get_live_price, and several other methods. Please update to 0.8.9.1 if you are using an older version. Additionally, there are two new functions, get_company_info and get_company_officers, for scraping company-related data.

Update: July 2021

yahoo_fin 0.8.9 was released in July 2021. This release includes a patch fixing get request issues due to recent changes on Yahoo Finance. These updates affect several functions, including scraping options data, get_quote_table, and scraping financials information. If you are using an older version, please update to 0.8.9.

Update: March 2021

yahoo_fin 0.8.8 was released in March 2021. This release contains a patch for the tickers_dow method.

Update: Feb. 2021

yahoo_fin 0.8.7 was released in Feb. 2021. This version adds a collection of new features.

Update: July 11, 2020

Version 0.8.6 of yahoo_fin made the following changes:

Update: April 24, 2020

This update to yahoo_fin occurred on April 24, 2020 (version 0.8.5). This version updated the get_stats function, as well as added the get_stats_valuation function. Follow the guidance in the installation section below to upgrade yahoo_fin to the latest version.

Update: December 15, 2019

An update to this package was pushed on December 15, 2019. This update fixes the issues caused by a recent change in Yahoo Finance’s website. If you have a previously installed version of yahoo_fin, please follow the guidance below to upgrade your installation using pip.

Recommended Python Version

A few methods in yahoo_fin require a package called requests_html as a dependency. Since requests_html requires Python 3.6+, you’ll need Python 3.6+ when installing yahoo_fin.

yahoo_fin Installation

Yahoo_fin can be installed using pip:

If you have a previously installed version, you can upgrade like this:

Requirements

Yahoo_fin requires the following packages to be installed:

With the exception of requests_html, these dependencies come pre-installed with Anaconda. requests_html requires Python 3.6+ and is needed for several of the functions in yahoo_fin, as described above. To install requests_html, you can use pip:

However, the latest versions of yahoo_fin should automatically install the dependencies when using pip, so you shouldn’t have to manually install these other packages.

Methods

The yahoo_fin package has three modules. These are called stock_info, options, and news. stock_info has the below primary methods.

The methods for options are listed below:

The news module currently contains one method:

stock_info module

Any method from yahoo_fin’s stock_info module can be imported by running the follow line, with get_analysts_info replaced with the method of choice.

Alternatively, all methods can be imported at once like so:

get_analysts_info(ticker)

Scrapes data from the Analysts page for the input ticker from Yahoo Finance (e.g. https://finance.yahoo.com/quote/NFLX/analysts?p=NFLX. This includes information on earnings estimates, EPS trends / revisions etc.

Returns a dictionary containing the tables visible on the ‘Analysts’ page.

Possible parameters

get_balance_sheet(ticker, yearly = True)

Scrapes the balance sheet for the input ticker from Yahoo Finance (e.g. https://finance.yahoo.com/quote/NFLX/balance-sheet?p=NFLX.

Possible parameters

get_cash_flow(ticker, yearly = True)

Scrapes the cash flow statement for the input ticker from Yahoo Finance (e.g. https://finance.yahoo.com/quote/NFLX/cash-flow?p=NFLX.

Possible parameters

get_company_info(ticker)

Scrapes company information for ticker from Yahoo Finance: https://finance.yahoo.com/quote/aapl/profile?p=aapl

Possible parameters

get_company_officers(ticker)

Scrapes company officers for ticker from Yahoo Finance: https://finance.yahoo.com/quote/aapl/profile?p=aapl

Possible parameters

get_currencies()

Scrapes the currencies table Yahoo Finance: https://finance.yahoo.com/currencies

get_data(ticker, start_date = None, end_date = None, index_as_date = True, interval = “1d”)

Downloads historical price data of a stock into a pandas data frame. Offers the functionality to pull daily, weekly, or monthly data.

Possible parameters

If you want to filter by a date range, you can just add a value for the start_date and / or end_date parameters, like below:

Get weekly or monthly historical price data:

get_day_gainers()

Scrapes the top 100 (at most) stocks with the largest gains (on the given trading day) from Yahoo Finance (see https://finance.yahoo.com/gainers).

get_day_losers()

Scrapes the top 100 (at most) worst performing stocks (on the given trading day) from Yahoo Finance (see https://finance.yahoo.com/losers).

get_day_most_active()

Scrapes the top 100 most active stocks (on the given trading day) from Yahoo Finance (see https://finance.yahoo.com/most-active).

get_dividends(ticker, start_date = None, end_date = None, index_as_date = True)

Downloads historical dividend data of a stock into a pandas data frame.

Possible parameters

get_earnings(ticker)

Scrapes earnings information from Yahoo Finance’s financials page for a given ticker (see https://finance.yahoo.com/quote/NFLX/financials?p=NFLX). Returns a dictionary with quarterly actual vs. estimated earnings per share, quarterly revenue / earnings data, and yearly revenue / earnings data.

Possible parameters

get_earnings_for_date(ticker)

Returns a list of dictionaries. Each dictionary contains a ticker, its corresponding EPS estimate, and the time of the earnings release.
Possible parameters

get_earnings_history(ticker)

Scrapes earnings history information from Yahoo Finance’s financials page for a given ticker. Returns a list of dictionaries with quarterly actual vs. estimated earnings per share along with dates of previous earnings releases. Currently, this method can pull back data for over 20 years.

Possible parameters

get_earnings_in_date_range(ticker)

Returns a list of dictionaries. Each dictionary contains a ticker, its corresponding EPS estimate, and the time of the earnings release. The data is returned based upon what earnings occur in the input date range. The date range is inclusive of the start_date and end_date inputs.
Possible parameters

get_financials(ticker, yearly = True, quarterly = True)

Efficient method to scrape balance sheets, cash flow statements, and income statements in a single call from Yahoo Finance’s financials page for a given ticker (see https://finance.yahoo.com/quote/NFLX/financials?p=NFLX).

If you’re looking to get all of this information for a given ticker, or set of tickers, this function will be 3x faster than running get_balance_sheet, get_cash_flow, and get_income_statement separately. Yearly, quarterly, or both time-periods can be pulled.

Returns a dictionary with the following keys:

If yearly and quarterly are both set to be True, all six key-value pairs are returned.

Possible parameters

get_futures()

Returns the table of futures prices from Yahoo Finance here: https://finance.yahoo.com/commodities

get_holders(ticker)

Scrapes data from the Holders tab from Yahoo Finance (e.g. https://finance.yahoo.com/quote/NFLX/holders?p=NFLX for an input ticker.

Possible parameters

get_income_statement(ticker, yearly = True)

Scrapes the income statement for the input ticker, which includes information on Price / Sales, P/E, and moving averages (e.g. https://finance.yahoo.com/quote/NFLX/financials?p=NFLX.

Possible parameters

get_live_price(ticker)

Scrapes the live quote price for the input ticker.

Possible parameters

get_market_status()

Returns a status specifying whether the market is currently pre-market (“PRE”), open (“OPEN”), post-market (“POST”), or closed (“CLOSED”).

get_next_earnings_date(ticker)

Returns the next upcoming earnings date for a given ticker.

Possible parameters

get_premarket_price(ticker)

Returns the premarket price for a given ticker if available / applicable.

Possible parameters

get_postmarket_price(ticker)

Returns the postmarket price for a given ticker if available / applicable.

Possible parameters

get_quote_data(ticker)

Scrapes a collection of over 70 data points for an input ticker from Yahoo Finance (e.g. https://query1.finance.yahoo.com/v7/finance/quote?symbols=NFLX), including current real-time price, company name, book value, 50-day average, 200-day average, pre-market price / post-market price (if available), shares outstanding, and more. The results are returned as a dictionary.

Possible parameters

Scrapes the primary table found on the quote page of an input ticker from Yahoo Finance (e.g. https://finance.yahoo.com/quote/AAPL?p=AAPL)

Possible parameters

The following fields with their corresponding values are returned:

get_splits(ticker, start_date = None, end_date = None, index_as_date = True)

Downloads historical stock splits data of a stock into a pandas data frame.

Possible parameters

get_stats(ticker)

Scrapes data off the statistics page for the input ticker, which includes information on moving averages, return on equity, shares outstanding, etc. (e.g. https://finance.yahoo.com/quote/NFLX/key-statistics?p=NFLX.

Possible parameters

get_stats_valuation(ticker)

Scrapes the “Valuation Measures” data off the statistics page for the input ticker, which includes information on Price / Sales, P/E, and market cap (e.g. https://finance.yahoo.com/quote/NFLX/key-statistics?p=NFLX.

Possible parameters

get_top_crypto(ticker)

Scrapes data for top 100 cryptocurrencies by market cap (see https://finance.yahoo.com/cryptocurrencies).

Possible parameters

get_undervalued_large_caps

tickers_dow(include_company_data = False)

If no parameters are passed, returns a list of tickers currently listed on the Dow Jones. The tickers are scraped from Wikipedia (see https://en.wikipedia.org/wiki/Dow_Jones_Industrial_Average. If you set include_company_data = True, it will return the full table on this webpage.

tickers_ftse100(include_company_data = False)

If no parameters are passed, returns a list of tickers currently listed on the FTSE 100 index. Otherwise, setting include_company_data = True will return a table with ticker, sector, and company name. The tickers are scraped from here: https://en.wikipedia.org/wiki/FTSE_100_Index.

tickers_ftse250(include_company_data = False)

If no parameters are passed, returns a list of tickers currently listed on the FTSE 250 index. Otherwise, setting include_company_data = True will return a table with ticker and company name. The tickers are scraped from here: https://en.wikipedia.org/wiki/FTSE_250_Index.

tickers_nasdaq(include_company_data = False)

Returns a list of tickers currently listed on the NASDAQ. If you specify include_company_data = True, it will return a table containing the tickers, their corresponding company names, and several other attributes. This method, along with tickers_other, works by scraping text files from ftp://ftp.nasdaqtrader.com/SymbolDirectory/.

tickers_nasdaq scrapes the nasdaqlisted.txt file from the link above, while tickers_other scrapes the otherlisted.txt file.

tickers_nifty50(include_company_data = False)

Returns a list of tickers currently listed on the NIFTY50. This method scrapes the tickers from here: https://en.wikipedia.org/wiki/NIFTY_50. If include_company_data is set to True, a table containing the tickers and company names is returned.

tickers_niftybank()

Returns a list of tickers currently listed on the NIFTYBANK. No parameters need to be passed.

tickers_other(include_company_data = False)

See above description for tickers_nasdaq.

tickers_sp500(include_company_data = False)

Returns a list of tickers currently listed in the S&P 500. The data for this is scraped from Wikipedia:

If include_company_data is set to True, the tickers, company names, and sector information is returned as a data frame.

options module

We can import any method from options module like this:

Just replace get_options_chain with any other method. Also, we can import all methods at once like so:

get_calls(ticker, date = None)

Scrapes call options data for the input ticker from Yahoo Finance (e.g. https://finance.yahoo.com/quote/NFLX/options?p=NFLX.

Returns a pandas data frame containing the call options data for the given ticker and expiration date.

Possible parameters

get_expiration_dates(ticker)

Scrapes expiration dates for the input ticker from Yahoo Finance (e.g. https://finance.yahoo.com/quote/NFLX/options?p=NFLX.

Returns a list of expiration dates for the input ticker. This list is based off the drop-down selection box on the options data webpage for the input ticker.

Possible parameters

get_options_chain(ticker, date)

Scrapes calls and puts tables for the input ticker from Yahoo Finance (e.g. https://finance.yahoo.com/quote/NFLX/options?p=NFLX.

Returns a dictionary with two data frames. The keys of the dictionary are labeled calls (which maps to the calls data table) and puts (which maps to the puts data table).

Possible parameters

get_puts(ticker, date = None)

Scrapes put options data for the input ticker from Yahoo Finance (e.g. https://finance.yahoo.com/quote/NFLX/options?p=NFLX.

Returns a pandas data frame containing the put options data for the given ticker and expiration date.

Possible parameters

yahoo_fin news module

Currently the news module contains a single function, get_yf_rss, which retrieves the Yahoo Finance news RSS feeds for an input ticker.

To learn more about Python and / or open source coding, check out a new online Python course I co-created with 365 Data Science! You’ll learn all about web scraping, how to use APIs in Python, how to scrape JavaScript pages, and how to deal with other modern challenges like logging into websites! Check it out on Udemy here!

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *