I am trying to fetch the stock history data of nifty 50 companies from the website and converting them to CSV. I need to update the same on daily basis. Is there any way, where I can append the current date data to the existing CSV without needing to download it again and again. My code goes like this:-
import os
import csv
import urllib.request as urllib
import datetime as dt
import pandas as pd
import pandas_datareader.data as web
import nsepy as nse
def saveNiftySymbols():
url = "https://www.nseindia.com/content/indices/ind_nifty50list.csv"
# pretend to be a chrome 47 browser on a windows 10 machine
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}
req = urllib.Request(url, headers = headers)
# open the url
x = urllib.urlopen(req)
sourceCode = x.read().decode('utf-8')
cr = csv.DictReader(sourceCode.splitlines())
l = [row['Symbol'] for row in cr]
return l
def fetchDataFromNse(l):
if not os.path.exists('stock_dfs'):
os.makedirs('stock_dfs')
start = dt.datetime(2000, 1, 1)
end = dt.datetime.today()
for symbol in l:
if not os.path.exists('stock_dfs/{}.csv'.format(symbol)):
df=nse.get_history(symbol,start, end)
df.to_csv('stock_dfs/{}.csv'.format(symbol))
else:
print('Already have {}'.format(symbol))
fetchDataFromNse(saveNiftySymbols())