Skip to content

Instantly share code, notes, and snippets.

@gSrikar
Last active March 3, 2021 07:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gSrikar/4728aff00399314f80785a6ef207c316 to your computer and use it in GitHub Desktop.
Save gSrikar/4728aff00399314f80785a6ef207c316 to your computer and use it in GitHub Desktop.
Fetch the stock prices from yahoo and save the data frame to the local machine. For more detailed explanation, check out my blog post https://www.gsrikar.com/2020/02/how-to-fetch-and-save-stock-price.html
1. Fetch the stock prices using pandas_datareader libray.
2. Use pandas to save the data frame to csv file or xlsx file.
3. Fetch and save for the desired ticker symbol between any date range.
# Get the dates
import datetime
# Find relative dates of the past or of the future
from dateutil.relativedelta import relativedelta
from stock_price import StockPrice
def stock_price():
# 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(".", "_"))
if __name__ == '__main__':
stock_price()
# 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
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 the csv file
self.write_csv(df, file_name)
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")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment