Skip to content

Commit

Permalink
saving get_quotes_rh progress
Browse files Browse the repository at this point in the history
  • Loading branch information
lockefox committed Aug 1, 2017
1 parent 3021763 commit bbdcbe7
Showing 1 changed file with 121 additions and 13 deletions.
134 changes: 121 additions & 13 deletions prosper/datareader/stocks/prices.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,47 @@
LOGGER = G_LOGGER
HERE = path.abspath(path.dirname(__file__))

RH_PRICE_QUOTES = 'https://api.robinhood.com/quotes'
RH_HEADERS = {
'Cache-Control': 'no-cache',
'Postman-Token': '96582a54-0734-946c-a9f6-165739d7f939'
}
def ticker_list_to_str(ticker_list):
"""parses/joins ticker list
Args:
ticker_list (:obj:`list` or str): ticker(s) to parse
Returns:
(str): list of tickers
"""
if isinstance(ticker_list, str):
return ticker_list.upper()
elif isinstance(ticker_list, list):
return ','.join(ticker_list).upper()
else:
raise TypeError

def cast_str_to_int(dataframe):
"""tries to apply to_numeric to each str column
Args:
dataframe (:obj:`pandas.DataFrame`): dataframe to adjust
Returns:
(:obj:`pandas.DataFrame`)
"""
columns = list(dataframe.columns.values)
for col in columns:
try:
dataframe[col] = pd.to_numeric(dataframe[col])
except Exception:
pass

return dataframe

RH_PRICE_QUOTES = 'https://api.robinhood.com/quotes/'
def fetch_price_quotes_rh(
ticker_list,
uri=RH_PRICE_QUOTES,
Expand All @@ -29,7 +69,20 @@ def fetch_price_quotes_rh(
(:obj:`list`): results from endpoint, JSONable
"""
pass
ticker_list_str = ticker_list_to_str(ticker_list)
logger.info('fetching quote data for %s -- Robinhood', ticker_list_str)

params = {
'symbols': ticker_list_str
}

req = requests.get(uri, params=params)
req.raise_for_status()

data = req.json()
logger.debug(data)

return data

RH_FUNDAMENTALS = 'https://api.robinhood.com/fundamentals/'
def fetch_fundamentals_rh(
Expand All @@ -51,12 +104,21 @@ def fetch_fundamentals_rh(
(:obj:`dict`): company fundamental data, JSONable
"""
pass
logger.info('fetching fundamentals data for %s -- Robinhood', ticker)

fundamental_url = '{uri}{ticker}/'.format(uri=uri, ticker=ticker.upper())
req = requests.get(fundamental_url)
req.raise_for_status()

data = req.json()
logger.debug(data)

return data

RH_INSTRUMENTS = 'https://api.robinhood.com/instruments'
#RH_INSTRUMENTS = 'https://api.robinhood.com/instruments'
def fetch_instruments_rh(
company_uid,
uri=RH_INSTRUMENTS,
instrument_url,
#uri=RH_INSTRUMENTS,
logger=LOGGER
):
"""fetch instrument data for stock
Expand All @@ -74,9 +136,46 @@ def fetch_instruments_rh(
(:obj:`dict`): trading data for company, JSONable
"""
pass
logger.info('fetching instruments data for %s -- Robinhood', instrument_url.split('/')[-1])

SUMMARY_KEYS = ['symbol', 'simple_name', 'PE', 'change_pct', 'last', 'short_ratio', 'time']
req = requests.get(instrument_url)
req.raise_for_status()

data = req.json()
logger.debug(data)

return data

def market_is_open(
market_uri,
logger=LOGGER
):
"""checks if market is open right now
Args:
market_uri: (str): link to market info
logger (:obj:`logging.logger`, optional): logging handle
Returns:
(bool): https://api.robinhood.com/markets/{market}/hours/{date}/['is_open']
"""
market_name = market_uri.split('/')[-1]
logger.info('fetching market info for %s -- Robinhood', market_name)

market_req = requests.get(market_uri)
market_req.raise_for_status()
market_data = market_req.json()

logger.info('--checking todays_hours')
hours_req = requests.get(market_data['todays_hours'])
hours_req.raise_for_status()
hours_data = hours_req.json()

return hours_data['is_open']

SUMMARY_KEYS = [
'symbol', 'simple_name', 'pe_ratio', 'pct_change', 'current_price', 'updated_at']
def get_quote_rh(
ticker_list,
keys=SUMMARY_KEYS,
Expand All @@ -86,27 +185,36 @@ def get_quote_rh(
Args:
ticker_list (:obj:`list`): list of tickers to look up
keys (:obj:`list`, optional): which keys to present in summary
logger (:obj:`logging.logger`, optional): logging handle
Returns:
(:obj:`pandas.DataFrame`): stock info for the day, JSONable
{'ticker', 'company_name', 'price', 'percent_change', 'PE', 'short_ratio', 'quote_datetime'}
"""
summary_raw_data = []
logger.info('Generating quote for %s -- Robinhood', ticker_list_to_str(ticker_list))

## Gather Required Data ##
summary_raw_data = []
quotes = fetch_price_quotes_rh(ticker_list, logger=logger)
for quote in quotes:
for quote in quotes['results']:
fundamentals = fetch_fundamentals_rh(quote['symbol'], logger=logger)
instruments = fetch_instruments_rh(quote['instrument'], logger=logger)

stock_info = {**quote, **fundamentals, **instruments}
stock_info = {**quote, **fundamentals, **instruments} #join all data together
stock_info['is_open'] = market_is_open(instruments['market'])

summary_raw_data.append(stock_info)
if stock_info['is_open']:
stock_info['current_price'] = stock_info['last_trade_price']
else:
stock_info['current_price'] = stock_info['last_extended_hours_trade_price']

summary_raw_data.append(stock_info)

summary_df = pd.DataFrame(summary_raw_data)
summary_df = cast_str_to_int(summary_df)

#TODO: calc pct_change
summary_df['pct_change'] = (summary_df['current_price'] - summary_df['previous_close']) / summary_df['previous_close'] * 100

return summary_df[keys]

0 comments on commit bbdcbe7

Please sign in to comment.