Machine Learning - How to get stock historic data

화이티 ·2023년 12월 20일
0

Machine Learning

목록 보기
14/23

1. import library

pip install yfinance

2. Get Current Stock Price Data

Method 1:

import yfinance as yf
ticker = yf.Ticker('GOOGL').info
market_price = ticker['regularMarketPrice']
previous_close_price = ticker['regularMarketPreviousClose']
print('Ticker: GOOGL')
print('Market Price:', market_price)
print('Previous Close Price:', previous_close_price)
import yfinance as yf
ticker = yf.Ticker('GOOGL').info
print(ticker.keys())

Method2:
You can get all the historical price data by providing the start date, end date, and ticker.

# Importing the yfinance package
import yfinance as yf
 
# Set the start and end date
start_date = '2020-01-01'
end_date = '2022-01-01'
 
# Set the ticker
ticker = 'GOOGL'
 
# Get the data
data = yf.download(ticker, start_date, end_date)
 
# Print the last 5 rows
print(data.tail())

If you want to pull data of multiple tickers at once, you can do so by providing the tickers in the form of a space-separated string.

import yfinance as yf
start_date = '2020-01-01'
end_date = '2022-01-01'
 
# Add multiple space separated tickers here
ticker = 'GOOGL MSFT TSLA'
data = yf.download(ticker, start_date, end_date)
print(data.tail())

3. Transforming Data for Analysis

import yfinance as yf
start_date = '2020-01-01'
end_date = '2022-01-01'
ticker = 'GOOGL'
data = yf.download(ticker, start_date, end_date)
data["Date"] = data.index
 
data = data[["Date", "Open", "High",
             "Low", "Close", "Adj Close", "Volume"]]
 
data.reset_index(drop=True, inplace=True)
print(data.head())

4.Storing the Received Data in a CSV File

import yfinance as yf
start_date = '2020-01-01'
end_date = '2022-01-01'
ticker = 'GOOGL TSLA'
data = yf.download(ticker, start_date, end_date)
print(data.tail())

# Export data to a CSV file
data.to_csv("GOOGL.csv")
profile
열심히 공부합시다! The best is yet to come! 💜

0개의 댓글