Get stock price python

stockquotes 2.0.1

stockquotes is a simple Python module for collecting stock quotes and historical data from Yahoo! Finance. It’s perfect for developers who can’t afford the (often high) prices charged by many stock data APIs.

Requirements

Installation

Usage

First, import the stockquotes module.

To get a stock quote, instantiate a stockquotes.Stock object. The only parameter is the ticker symbol to look up.

kroger = stockquotes.Stock('KR') 

Basic data

To get the current price of a share, get the Stock ‘s current_price .

kroger_price = kroger.current_price 

To get the day gain in dollars, get the Stock ‘s increase_dollars .

kroger_gain_dollars = kroger.increase_dollars 

The same value as a percent is available in the increase_percent property. To indicate losses, these values are negative.

Historical data

The historical data for a stock can be accessed through the Stock ‘s historical property. This is an array of dict s, with the first item representing the most recent quote. The dict ‘s date property is a datetime object representing the date the quote is from. open is the opening price for that day. high and low are the high and low prices, respectively, for that day. close and adjusted_close are the closing price. The difference is that adjClose is adjusted for splits and dividends, whereas close is adjusted only for splits. volume is the stock’s volume for that day.

Читайте также:  Php for apache2 ubuntu

Typically, this should give at least a month of data. Obviously, it gives less for recent IPOs. Also, a known but unexplained bug causes it to only give two days of data for some stocks.

Exceptions

stockquotes.StockDoesNotExistError is raised when the stock does not exist.

stockquotes.NetworkError is raised when a connection to Yahoo! Finance cannot be established.

License

Copyright (c) 2019 ScoopGracie. All rights reversed. This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Источник

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

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

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

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

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

Yahoo Finance

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

# Import the yfinance. If you get module not found error the run !pip install yfianance from your Jupyter notebook import yfinance as yf # Get the data for the stock AAPL data = yf.download('AAPL','2016-01-01','2019-08-01') # Import the plotting library import matplotlib.pyplot as plt %matplotlib inline # Plot the close price of the AAPL data['Adj Close'].plot() plt.show() 

image

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

# Define the ticker list import pandas as pd tickers_list = ['AAPL', 'WMT', 'IBM', 'MU', 'BA', 'AXP'] # Import pandas data = pd.DataFrame(columns=tickers_list) # Fetch the data for ticker in tickers_list: data[ticker] = yf.download(ticker,'2016-01-01','2019-08-01')['Adj Close'] # Print first 5 rows of the data data.head() 

image

# Plot all the close prices ((data.pct_change()+1).cumprod()).plot(figsize=(10, 7)) # Show the legend plt.legend() # Define the label for the title of the figure plt.title("Adjusted Close Price", fontsize=16) # Define the labels for x-axis and y-axis plt.ylabel('Price', fontsize=14) plt.xlabel('Year', fontsize=14) # Plot the grid lines plt.grid(which="major", color='k', linestyle='-.', linewidth=0.5) plt.show() 

image

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

image

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

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

image

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

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

Источник

Get Stock Price Data using Python

thecleverprogrammer

As machine learning practitioners, we need to collect stock price data for regression analysis and time series analysis. We can easily download it from Yahoo Finance. But imagine if we want to create an application where we can analyze the real-time stock prices, we need to collect the latest dataset instead of using the downloaded dataset. So if you want to learn how to get the stock price data between any time interval by using the Python programming language, this article is for you. In this article, I will take you through how to get stock price data using Python.

Get Stock Price Data using Python

Get Stock Price Data using Python

Yahoo Finance is one of the most popular websites to collect stock price data. You need to visit the website, enter the company’s name or stock symbol, and you can easily download the dataset. But if you want to get the latest dataset every time you are running your code, you need to use the yfinance API. yfinance is an API provided by Yahoo Finance to collect the latest stock price data.

To use this API, you need to install it by using the pip command in your terminal or command prompt as mentioned below:

I hope you have easily installed this API. Now below is how you can get the latest stock price data using Python:

import pandas as pd import yfinance as yf import datetime from datetime import date, timedelta today = date.today() d1 = today.strftime("%Y-%m-%d") end_date = d1 d2 = date.today() - timedelta(days=360) d2 = d2.strftime("%Y-%m-%d") start_date = d2 data = yf.download('AAPL', start=start_date, end=end_date, progress=False) print(data.head())
 Open High . Adj Close Volume Date . 2020-12-28 133.990005 137.339996 . 135.852509 124486200 2020-12-29 138.050003 138.789993 . 134.043640 121047300 2020-12-30 135.580002 135.990005 . 132.900681 96452100 2020-12-31 134.080002 134.740005 . 131.876999 99116600 2021-01-04 133.520004 133.610001 . 128.617111 143301900 [5 rows x 6 columns]

The above code will collect the stock price data from today to the last 360 days. In this dataset, Date is not a column, it’s the index of this dataset. To use this data for any data science task, we need to convert this index into a column. Below is how you can do that:

data["Date"] = data.index data = data[["Date", "Open", "High", "Low", "Close", "Adj Close", "Volume"]] data.reset_index(drop=True, inplace=True) print(data.head())
 Date Open High . Close Adj Close Volume 0 2020-12-28 133.990005 137.339996 . 136.690002 135.852524 124486200 1 2020-12-29 138.050003 138.789993 . 134.869995 134.043640 121047300 2 2020-12-30 135.580002 135.990005 . 133.720001 132.900696 96452100 3 2020-12-31 134.080002 134.740005 . 132.690002 131.876999 99116600 4 2021-01-04 133.520004 133.610001 . 129.410004 128.617096 143301900 [5 rows x 7 columns]

So as you can see, the final dataset is just like the dataset that we download from Yahoo Finance. This is how we can get stock price data using Python.

Summary

So this is how you can collect the latest stock price dataset between any time interval, using the Python programming language. If you want to get the latest dataset every time you are running your code, you need to use the yfinance API. yfinance is an API provided by Yahoo Finance to collect the latest stock price data. I hope you liked this article on how to get stock price dataset using Python. Feel free to ask your valuable questions in the comments section below.

Источник

Оцените статью