Querying stock price with Yahoo Finance in Python | ดึงข้อมูลราคาหุ้นจาก Yahoo Finance ด้วย Python (3.0)

Suebsak Rochanarat, FRM
2 min readJan 19, 2021

Market data plays indispensable roles in financial analysis. It is essential to have cost-free resource to retrieve such data. In this article, I will show you how to query stock price with Python 3.0. The example will be based on stocks in the Stock Exchange of Thailand.

First, install yfinance library

pip install yfinance

Then, import essential library

import yfinance as yfimport pandas as pdimport seaborn as sns

Specify tickers we want to query (check the tickers from Yahoo finance website if you are not sure)

ticker_list = ['PTT.BK','PTTEP.BK','PTTGC.BK','TOP.BK']

Generate blank a DataFrame to store our data.

data_df = pd.DataFrame()

Then, create a loop to the data, and the code will look like this.

Price query with yahoo finance

Note that there are easier ways to do this, but, for Python beginners, it is worth to get familiar with the loops and data handling method. The link to documentation below from ‘yfinance’ shows how to query multiple securities by simply using ‘pandas_datareader’ override.

Now, let’s check the data a little bit.

import matplotlib.pyplot as pltdata_df['2015':].plot(figsize=(12,6))plt.legend(loc='upper left')
Adjusted close price since 2015

From the cumulative return angle, the code and the graph will look like this

(data_df['2015':].pct_change()+1).cumprod().plot(figsize=(12,6))plt.ylabel('Growth of hypothetical 1 Bt.')plt.savefig('CumRet_since2015.png')
Cumulative returns since 2015

Thanks for reading 😃

--

--

Suebsak Rochanarat, FRM

Investment Analytics Analyst 🇹🇭. Certified Financial Risk Manager. Python Novice. Investment Management and Data Science.