Yahoo Finance API to get Stocks tickers data in python.
Yahoo finance API is very helpful to get information about stocks. We can use it to get stock tickers' live data. For downloading historical data we can follow these steps.
- Go to Yahoo Finance.
- Enter a quote into the search field.
- Select a quote in the search results to view it.
- Click Historical Data.
- Select a Time Period, data to Show, and Frequency.
- Click Apply.
- To use the data offline, click Download Data.
Installation
You will be required some packages to run. Python is an obvious first thing.
- pandas_datareader
You can install this using the following command.
pip install pandas-datareader
2. yfinance
You can install this using the following command
pip install yfinance
or
conda install -c postelrich yahoo-finance
Python code
You can find below the code for stock data using yahoo API in python.
from pandas_datareader import data as pdr
from datetime import date
import yfinance as yf
yf.pdr_override()
import pandas as pd
# Tickers list
# We can add and delete any ticker from the list to get desired ticker live data
ticker_list=['DJIA', 'DOW', 'LB', 'EXPE', 'PXD', 'MCHP', 'CRM', 'JEC' , 'NRG', 'HFC', 'NOW']
today = date.today()
# We can get data by our choice by giving days bracket
start_date= "2017–01–01"
end_date="2019–11–30"
files=[]
def getData(ticker):
print (ticker)
data = pdr.get_data_yahoo(ticker, start=start_date, end=today)
dataname= ticker+'_'+str(today)
files.append(dataname)
SaveData(data, dataname)
# Create a data folder in your current dir.
def SaveData(df, filename):
df.to_csv('./data/'+filename+'.csv')
#This loop will iterate over ticker list, will pass one ticker to get data, and save that data as file.
for tik in ticker_list:
getData(tik)
for i in range(0,11):
df1= pd.read_csv('./data/'+ str(files[i])+'.csv')
print (df1.head())
Your data will be saved in the data folder. You can automate this process to keep getting live data. Cheers. Cheers :)
Feel free to contact me at:
LinkedIn https://www.linkedin.com/in/junaidraza52/
Whatsapp +92–3225847078
Instagram https://www.instagram.com/iamjunaidrana/