Skip to content

Instantly share code, notes, and snippets.

@lebedov
Last active February 20, 2024 09:44
Show Gist options
  • Save lebedov/f09030b865c4cb142af1 to your computer and use it in GitHub Desktop.
Save lebedov/f09030b865c4cb142af1 to your computer and use it in GitHub Desktop.
Retrieve intraday stock data from Google Finance.
#!/usr/bin/env python
"""
Retrieve intraday stock data from Google Finance.
"""
import csv
import datetime
import re
import pandas as pd
import requests
def get_google_finance_intraday(ticker, period=60, days=1):
"""
Retrieve intraday stock data from Google Finance.
Parameters
----------
ticker : str
Company ticker symbol.
period : int
Interval between stock values in seconds.
days : int
Number of days of data to retrieve.
Returns
-------
df : pandas.DataFrame
DataFrame containing the opening price, high price, low price,
closing price, and volume. The index contains the times associated with
the retrieved price values.
"""
uri = 'http://www.google.com/finance/getprices' \
'?i={period}&p={days}d&f=d,o,h,l,c,v&df=cpct&q={ticker}'.format(ticker=ticker,
period=period,
days=days)
page = requests.get(uri)
reader = csv.reader(page.content.splitlines())
columns = ['Open', 'High', 'Low', 'Close', 'Volume']
rows = []
times = []
for row in reader:
if re.match('^[a\d]', row[0]):
if row[0].startswith('a'):
start = datetime.datetime.fromtimestamp(int(row[0][1:]))
times.append(start)
else:
times.append(start+datetime.timedelta(seconds=period*int(row[0])))
rows.append(map(float, row[1:]))
if len(rows):
return pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date'),
columns=columns)
else:
return pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date'))
@atulsahire
Copy link

what is the symbol for NIFTY50 data

@syedshahab698
Copy link

what is the symbol for NIFTY50 data

Yahoo finance symbol for nifty 50 = '^NSEI'

@sairam18814
Copy link

import requests
import pandas as pd
import arrow
import datetime

def get_quote_data(symbol , data_range='1d', data_interval='1m'):
res = requests.get('https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?range={data_range}&interval={data_interval}'.format(**locals()))
data = res.json()
body = data['chart']['result'][0]
dt = datetime.datetime
dt = pd.Series(map(lambda x: arrow.get(x).to('Asia/Calcutta').datetime.replace(tzinfo=None), body['timestamp']), name='Datetime')
df = pd.DataFrame(body['indicators']['quote'][0], index=dt)
dg = pd.DataFrame(body['timestamp'])
df = df.loc[:, ('open', 'high', 'low', 'close', 'volume')]
df.dropna(inplace=True)
df.columns = ['OPEN', 'HIGH','LOW','CLOSE','VOLUME']

return df

for s in symbol:
data = get_quote_data(s,'1d','1m')
data.to_csv(s.strip(".NS")+'.csv')

this is for multiple stock symbols

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment