How to Fetch and Save Stock Price

Historical stock prices are available on a significant number of websites to download but wouldn't it be easier to use a script to fetch these prices and save it to our local machine?

In this article, we will learn how to fetch the historic stock prices of a company using Python. Let's first import the required dependencies to perform the actions.

# Get the dates
import datetime
# Create files in the operating system
import os

# Convert data frames to file formats
import pandas as pd
# Fetch the stock prices
import pandas_datareader as web
# Find relative dates of the past or of the future
from dateutil.relativedelta import relativedelta

Now, create a StockPrice class with a helper function fetch to fetch the stock price and save function to save the stock prices to the local folder.

class StockPrice:
    """
    Provide functionality to fetch the historical stock prices and save it to a path
    """

    def __init__(self):
        """
        Entry point to the class
        """
        self.data_source = 'yahoo'
        self.path = 'data/'

    def fetch(self, ticker_symbol, start, end):
        """
        Fetch the data from pre-defined source between the start and end time
        :param ticker_symbol:
        :param start: start time in yyyy-mm-dd
        :param end: end time in yyyy-mm-dd
        :return: data frame with the historical stock prices
        """
        return web.DataReader(ticker_symbol, self.data_source, start, end)

    def save(self, df, file_name):
        """
        Save the data frame to a csv file in the local folderz
        :param df: data frame with historical stock prices
        :param file_name: name of the csv files
        """
        # Create the path
        created = self.create_path()
        print('New Path created', created)

        # Create and write to a csv file
        self.write_csv(df, file_name)
        # Create and write to an excel file
        self.write_excel(df, file_name)

    def create_path(self):
        """
        Create a path in the system
        :return: True if the path was created because it doesn't exist and false otherwise
        """
        if not os.path.exists(self.path):
            # Path doesn't exists, create the path
            os.makedirs(self.path)
            return True
        return False

    def write_excel(self, df, file_name):
        """
        Create a file of format xlsx
        :param df: data frame with historical stock prices
        :param file_name: name of the csv files
        """
        writer = pd.ExcelWriter(self.path + file_name + ".xlsx", datetime_format='dd/mm/yyy')
        df.to_excel(writer)
        writer.close()

    def write_csv(self, df, file_name):
        """
        Create a file of format csv
        :param df: data frame with historical stock prices
        :param file_name: name of the csv files
        """
        df.to_csv(self.path + file_name + ".csv")

To fetch the stock price, we use DataReader function which is part of pandas_datareader library. It takes a source, ticker symbol and start time, end time in yyyy-mm-dd format. We can pass today's date as the end time using datetime.date.today and n years old date as the start time by subtracting relativedelta from the today's date.

We are using the source as yahoo in this example, instead of that, we can also use robinhood, quandl or any other available source.

DataReader returns a pandas data frame object and this can be saved in the csv format using to_csv or in the xlsx format using to_excel functions. One thing to note is that if the path passed to these functions doesn't exist, they will throw FileNotFoundError. So it is a good practice to check whether the path exists or not before creating the files.

# Assign a ticker symbol
ts = 'BAJFINANCE.NS'

# Create an instance of the class
stockPrice = StockPrice()
# Fetch the stock price
df_ts = stockPrice.fetch(
    ts,
    datetime.date.today() - relativedelta(years=10),
    datetime.date.today()
)
# Print the first 5 rows
print(df_ts.head())
# Print the last 5 rows
print(df_ts.tail())
# Save the stock price
stockPrice.save(df_ts, ts.replace(".", "_"))

Running the above script creates two files; BAJFINANCE_NS.csv and BAJFINANCE_NS.xlsx in the data folder. Most of the time, we work with either of the file formats, so we can choose to use either write_csv or write_excel function.

Popular posts from this blog

How to Read Metadata from AndriodManifest File

Mr Phone - Find The Next Best Phone You Want To Buy

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Add Options Menu to Activity and Fragment

Create Assets Folder, Add Files and Read Data From It