17
import yfinance as yf

stock = yf.Ticker("ABEV3.SA")

data1= stock.info


print(data1)

There is "bid" and "ask", but no actual stock price.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Tiago Godoy
  • 221
  • 1
  • 2
  • 7
  • There is another way to get the stock price, you can use requests to get a response from a free stock api, i could give few example lines its very simple. – beepbeep-boop Apr 08 '20 at 15:32
  • Unless you specifically care about the last price the stock actually traded at, people usually just use the average of bid and ask for this. – Karl Knechtel Apr 09 '20 at 00:06

12 Answers12

22

I used this filtering combination to get only the last quote.

import yfinance as yf

tickers = ['ABEV3.SA']
for ticker in tickers:
    ticker_yahoo = yf.Ticker(ticker)
    data = ticker_yahoo.history()
    last_quote = data['Close'].iloc[-1]
    print(ticker, last_quote)
pelelter
  • 518
  • 4
  • 14
16

Try this:

import yfinance as yf

stock = yf.Ticker("ABEV3.SA")
price = stock.info['regularMarketPrice']
print(price)
 
cgrtamb
  • 161
  • 1
  • 3
  • 1
    Note that `currentPrice` is also available which returns the same value as of version `0.1.74` – alphazwest Aug 10 '22 at 16:24
  • Weirdly, sometimes it's one or the other so I'll use `stock.info.get('regularMarketPrice', stock.info.get('currentPrice'))` – Tox Apr 11 '23 at 14:21
10

This method returns the most updated value in my testing.

def get_current_price(symbol):
    ticker = yf.Ticker(symbol)
    todays_data = ticker.history(period='1d')
    return todays_data['Close'][0]

print(get_current_price('TSLA'))
Pranjal
  • 299
  • 3
  • 10
4

To get the last closing price use this:

import yfinance as yf

tickerSymbol = 'AMD'

tickerData = yf.Ticker(tickerSymbol)
todayData = tickerData.history(period='1d')
todayData['Close'][0] #use print() in case you're testing outside a interactive session
2

Try this:

import datetime
import yfinance as yf
now = datetime.datetime.now().strftime("%Y-%m-%d")
data = yf.Ticker("ABEV3.SA")
data = data.history(start="2010-01-01",  end=now)
print(data)
Joseph Farah
  • 2,463
  • 2
  • 25
  • 36
Quinn
  • 39
  • 6
2

this is what looks like realtime quote to me:

import yfinance as yf
yca = yf.Ticker("YCA.L").history(interval="1m", period = "1d")
yca['Close'][-1]
user1050755
  • 11,218
  • 4
  • 45
  • 56
1

The bid and ask prices are actually what are quoted on the exchange. A bid price is what a market maker is prepared to pay to buy shares, an ask is the price market makers require before selling. The spread is the difference between bid and ask.

What is usually referred to as the stock price is an average of the bid and ask prices. How the average is calculated depends on the exchange. If your feed does not offer a mid price provided by the exchange, then for many purposes it is sufficient to take the mean of the bid and ask.

Opening and closing prices are also determined by the exchange and may not be the first or last trades, but an average of the first or last 15 minutes trading, or may include after-hours prices.

Some details of how the LSE specifies ticker data: LSE ticker data

And, if you want to get into the nitty-gritty, a bit more detail on how orders are matched and generate price data:

Idiots Guide to the London Stock Exchange's SETSmm

AlDante
  • 336
  • 3
  • 8
1

Try this to get current price for multiples stocks:

stocks = ['PETR4.SA', 'ELET3.SA', 'VALE3.SA']

df = yf.download(' '.join(stocks), period='1d', progress=False)
df = df['Close']

for stock in stocks:
    if stock not in df or len(df[stock]) == 0: # this verification is important if trading session is closed
        continue
    quote = df[stock][0]
    print('%s = %.2f'%(stock, quote))

Fábio A.
  • 31
  • 1
0

yfinance has download function which let's you download the stock price data for a specified period. for e.g. I'll use the same stock that you wanted data for.

import yfinance as yf
data = yf.download("ABEV3.SA", start="2020-03-01", end="2020-03-30")

above line downloads data for march month as the specified date is that.

the data will be a pandas dataframe so you can directly use that for operation.

hope this helps.

  • 1
    Thanks for sharing, it seems that this only returns historical data at least when I try this `d = yf.download('DHER.DE', start='2020-03-01', end='2020-12-09')` it return only the data until yesterday. Is there any way to access the current bid? – b00r00x0 Dec 09 '20 at 08:48
  • For getting the current price in yahoo, you can take a look at this repository: [excel_stock_webscrape](https://github.com/rodionlim/excel_stock_webscrape) – darkvalance Dec 14 '20 at 03:46
0

Below code will get current price for list of symbols and add all result in dict.

import yfinance as yf

symbols = ["TSLA", "NIO"]
result = {}
for symbol in symbols:
    data = yf.Ticker(symbol)
    today_data = data.history(period='1d')
    result[symbol] = round((today_data['Close'][0]),2)
print(result)
Eslamspot
  • 77
  • 5
  • 4
    Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it works better than what the OP provided. See [answer]. – ChrisGPT was on strike Mar 03 '21 at 01:04
0

I know this is a few years late but for people looking for a solution to this question.

import yfinance as yf

def current_price(instrument):
    data = yf.Ticker(instrument).history(period="1d", interval="1m")
    return data["Close"].iloc[-1]

print(current_price("TSLA"))

This example gets the data in minute intervals and returns the latest "Close" data.

  • I should have added that this method will get the data in 1 minute intervals and the last 'Close' data will be from the last minute interval. – Isaac Stewart Jul 18 '23 at 16:49
-1

Okay, so you want to obtain the current (latest) value.
That's relatively simple, just one single line that gets the history of the stock of 1 day.

symbol = "AAPL"
stock = yf.Ticker(symbol)
latest_price = stock.history(period='1d')['Close'][0]

# Completely optional but I recommend having some sort of round(er?).
# Dealing with 148.60000610351562 is a pain.
estimate = round(latest_price, 2) 

print (estimate)

You should also put this in a function to make it more universal.

NOTE: My previous answer recommended the use of AlphaAdvantage, still an option on the table but it's limited to 5 reqs per minute. I changed my answer but you can get a TL;DR of it here:
Use requests and json, pull data, format, list comprehension(?)

I know theres better answers than this and probably very similar ones to this, this is just a personal method I prefer.

beepbeep-boop
  • 204
  • 1
  • 2
  • 11
  • i have actaully no clue why my answer is being disliked could anyone brief why? – beepbeep-boop Apr 08 '20 at 15:50
  • Completely off-topic: I was about to post an answer to your [CSV Conversion for nested dictionary and re-arrange few aspects](https://stackoverflow.com/questions/64946826/csv-conversion-for-nested-dictionary-and-re-arrange-few-aspects?noredirect=1#comment114823661_64946826) question when you deleted it. Please undelete it. – martineau Nov 21 '20 at 20:55
  • well after a year of more python i now realise why my answer is so down voted, i however cant seem to delete it so we're in a bit of a pickle. as i'm a bit unfamiliar with stack overflow, if i were to completely change my answer but ensure it's still right would that be valid? – beepbeep-boop Aug 29 '21 at 06:03