To read Yahoo Finance stock data and save it to an SQLite database, you'll need to use a combination of libraries in Python. Specifically, we'll use:
yfinance to fetch Yahoo Finance stock data.
sqlite3 to interact with the SQLite database.
First, ensure you have the required libraries installed. You can install them using pip if you haven't already:
pip install yfinance
sqlite3 is part of the Python Standard Library, so you don't need to install it separately.
Here's a step-by-step example code that fetches stock data for a specified ticker (e.g., Apple - AAPL), and then saves this data to an SQLite database:
import yfinance as yf
import sqlite3
from sqlite3 import Error
# Function to create a database connection
def create_connection(db_file):
"""
Establishes a connection to the SQLite database.
:param db_file: The path to the SQLite database file.
:return: Connection object if successful, otherwise None.
"""
conn = None
try:
# Attempt to connect to the SQLite database
conn = sqlite3.connect(db_file)
print(f"Connected to SQLite Database {db_file}")
return conn
except Error as e:
# Handle any errors that occur during connection
print(f"Error connecting to the database: {e}")
return conn
# Function to create table
def create_table(conn, table_name, ticker):
"""
Creates a table in the database if it does not already exist.
:param conn: The connection object to the database.
:param table_name: The base name of the table.
:param ticker: The stock ticker symbol (used to make table name unique).
"""
# SQL query to create the table with the required columns
sql_create_table = f""" CREATE TABLE IF NOT EXISTS {table_name}_{ticker} (
date TEXT PRIMARY KEY,
open REAL NOT NULL,
high REAL NOT NULL,
low REAL NOT NULL,
close REAL NOT NULL,
adj_close REAL NOT NULL,
volume INTEGER NOT NULL
); """
try:
# Execute the SQL query to create the table
c = conn.cursor()
c.execute(sql_create_table)
print(f"Table {table_name}_{ticker} created successfully.")
except Error as e:
# Handle any SQL errors during table creation
print(f"Error creating table: {e}")
# Function to insert data into the table
def insert_data_into_table(conn, table_name, ticker, data):
"""
Inserts the provided data into the specified table.
:param conn: The connection object to the database.
:param table_name: The base name of the table.
:param ticker: The stock ticker symbol (for table naming).
:param data: A list of tuples containing the data to be inserted.
:return: The rowid of the last inserted row, or None if an error occurs.
"""
# SQL query to insert data into the table
sql_insert_data = f""" INSERT INTO {table_name}_{ticker}(date,open,high,low,close,adj_close,volume)
VALUES(?,?,?,?,?,?,?) """
try:
# Execute the query to insert multiple rows at once
c = conn.cursor()
c.executemany(sql_insert_data, data)
conn.commit() # Commit the changes
print("Data inserted successfully.")
return c.lastrowid
except Error as e:
# Handle any errors during data insertion
print(f"Error inserting data: {e}")
# Main execution
if __name__ == '__main__':
db_file = "stock_market.db" # Name of the SQLite database file
ticker = "AAPL" # Stock ticker symbol (e.g., AAPL for Apple)
table_name = "stock_data" # Base name for the table
# Establish a connection to the database
conn = create_connection(db_file)
if conn is not None:
# Create the table if it does not exist
create_table(conn, table_name, ticker)
try:
# Fetch stock data from Yahoo Finance
data = yf.Ticker(ticker)
hist_data = data.history(period="max") # Fetch maximum available history
# Prepare data for insertion (convert index to column and reset)
hist_data.reset_index(inplace=True)
# Convert DataFrame to list of tuples for insertion
data_to_insert = list(hist_data[['Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume']].itertuples(index=False, name=None))
# Check for missing data
if hist_data.isnull().values.any():
print("Warning: The fetched data contains missing values. It is recommended to handle these before inserting into the database.")
# Insert data into the table
insert_data_into_table(conn, table_name, ticker, data_to_insert)
except Exception as e:
# Handle any errors that occur during data fetching or processing
print(f"Error fetching or processing data: {e}")
finally:
# Close the database connection
conn.close()
print("Database connection closed.")
else:
print("Error! Cannot create the database connection.")
Key Points:
- Database Name: The script will create a database named
stock_market.db in the same directory as your script. Change db_file variable as needed.
- Ticker Symbol: The script fetches data for Apple (AAPL) by default. Change the
ticker variable to fetch data for a different stock.
- Table Name: The base table name is
stock_data, and the actual table will be named with the format stock_data_<Ticker>.
- Data Period: The
yfinance.history() function is set to fetch the maximum available history. You can adjust the period parameter (e.g., "1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max") based on your requirements.
- Error Handling: The script includes error handling for database connections, SQL operations, and data fetching. It also checks for missing data in the fetched dataset.