Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the best way to get stock data using Python?
In this article, we will learn the best way to get stock data using Python.
The yfinance Python library will be used to retrieve current and historical stock market price data from Yahoo Finance API. This library is free to use and requires no API key.
Installation of Yahoo Finance (yfinance)
Yahoo Finance is one of the best platforms for acquiring stock market data. You can install yfinance using pip with the following command ?
Syntax
pip install yfinance
The best part about the yfinance library is that it's completely free to use and no API key is required.
Getting Current Stock Data
To get current stock data, we need to find the ticker symbol of the stock. The following example shows how to get current market price and previous close price for Google (GOOGL) ?
Example
import yfinance as yf
ticker = yf.Ticker('GOOGL').info
market_price = ticker['regularMarketPrice']
previous_close = ticker['regularMarketPreviousClose']
print('Ticker Value: GOOGL')
print('Market Price Value:', market_price)
print('Previous Close Price Value:', previous_close)
Ticker Value: GOOGL Market Price Value: 92.83 Previous Close Price Value: 93.71
Getting Historical Stock Data
By providing start date, end date, and ticker symbol, we can obtain historical price data for any time period ?
Example
import yfinance as yf # Define date range start_date = '2015-03-01' end_date = '2017-03-01' ticker = 'GOOGL' # Download historical data stock_data = yf.download(ticker, start_date, end_date) # Display last 5 rows print(stock_data.tail())
[*********************100%***********************] 1 of 1 completed
Open High Low Close Adj Close Volume
Date
2017-02-22 42.400002 42.689499 42.335499 42.568001 42.568001 24488000
2017-02-23 42.554001 42.631001 42.125000 42.549999 42.549999 27734000
2017-02-24 42.382500 42.417999 42.147999 42.390499 42.390499 26924000
2017-02-27 42.247501 42.533501 42.150501 42.483501 42.483501 20206000
2017-02-28 42.367500 42.441502 42.071999 42.246498 42.246498 27662000
Data Transformation for Analysis
The Date is an index rather than a column in the downloaded data. To perform analysis, convert the index to a proper column ?
Example
import yfinance as yf # Define parameters start_date = '2015-03-01' end_date = '2017-03-01' ticker = 'GOOGL' # Download data stock_data = yf.download(ticker, start_date, end_date) # Convert date index to column stock_data["Date"] = stock_data.index # Reorder columns stock_data = stock_data[["Date", "Open", "High", "Low", "Close", "Adj Close", "Volume"]] # Reset index stock_data.reset_index(drop=True, inplace=True) # Display first 5 rows print(stock_data.head())
[*********************100%***********************] 1 of 1 completed
Date Open High Low Close Adj Close Volume
0 2015-03-02 28.350000 28.799500 28.157499 28.750999 28.750999 50406000
1 2015-03-03 28.817499 29.042500 28.525000 28.939501 28.939501 50526000
2 2015-03-04 28.848499 29.081499 28.625999 28.916500 28.916500 37964000
3 2015-03-05 28.981001 29.160000 28.911501 29.071501 29.071501 35918000
4 2015-03-06 29.100000 29.139000 28.603001 28.645000 28.645000 37592000
Exporting Data to CSV
Use the to_csv() method to export the DataFrame to a CSV file for further analysis ?
Example
import yfinance as yf
# Download stock data
start_date = '2015-03-01'
end_date = '2017-03-01'
ticker = 'GOOGL'
stock_data = yf.download(ticker, start_date, end_date)
print("Data downloaded successfully!")
# Export to CSV file
stock_data.to_csv("googl_stock_data.csv")
print("Data exported to googl_stock_data.csv")
[*********************100%***********************] 1 of 1 completed Data downloaded successfully! Data exported to googl_stock_data.csv
Multiple Stocks at Once
You can download data for multiple stocks by providing ticker symbols as a space-separated string ?
Example
import yfinance as yf # Download data for multiple stocks tickers = "GOOGL AAPL MSFT" data = yf.download(tickers, start="2023-01-01", end="2023-02-01") # Display closing prices print(data['Close'].head())
Key Features
| Feature | Description | Use Case |
|---|---|---|
| Current Data | Real-time market prices | Live trading applications |
| Historical Data | Past price movements | Technical analysis |
| Multiple Stocks | Batch data download | Portfolio analysis |
| CSV Export | Data persistence | Offline analysis |
Conclusion
The yfinance library is the best way to get stock data in Python due to its simplicity and free access to Yahoo Finance data. Use it for both current and historical stock analysis, and export data to CSV for further processing.
