def get_pricing_data(td: ameritrade.AmeritradeAPI, symbol: str): """Fetch and format the pricing data.""" hist = td.GetPriceHistory(symbol=symbol, frequency=1, frequencyType='daily', period=2, periodType='year') if not isinstance(hist, dict) or hist['empty']: return buf = io.StringIO() pr = functools.partial(print, file=buf) pr("var data = [") for candle in hist['candles']: time = datetime.datetime.fromtimestamp(candle['datetime'] / 1000) year = time.year month = time.month day = time.day open = candle['open'] close = candle['close'] high = candle['high'] low = candle['low'] pr(f"{{ time: {{year: {year}, month: {month}, day: {day} }}, " f"open: {open}, high: {high}, low: {low}, close: {close} }},") pr("];") return buf.getvalue()
def GetMainAccount(api: td.AmeritradeAPI, acctype: Optional[str]=None) -> str: """Returns the largest account of a particular type.""" matching_accounts = [] for acc in api.GetAccounts(): for accname, accvalue in acc.items(): if acctype and accvalue['type'] != acctype: continue liq_value = accvalue['currentBalances']['liquidationValue'] matching_accounts.append((liq_value, accvalue['accountId'])) if not matching_accounts: raise ValueError("No matching accounts.") return next(iter(sorted(matching_accounts, reverse=True)))[1]
def GetReturns(api: AmeritradeAPI, symbol: str, periodType: str) -> Tuple[Array, Array]: """Get a series of returns for a particular period type.""" if periodType == 'daily1yr': kwargs = dict(period=1, periodType='year', frequency=1, frequencyType='daily') elif periodType == 'weekly3yr': kwargs = dict(period=3, periodType='year', frequency=1, frequencyType='weekly') elif periodType == 'monthly3yr': kwargs = dict(period=3, periodType='year', frequency=1, frequencyType='monthly') elif periodType == 'experimental': # Just searching around for parameters that would reproduce one of the # four betas found in the UI. kwargs = dict(period=3, periodType='year', frequency=1, frequencyType='weekly') elif periodType == 'recent': kwargs = dict(period=5, periodType='day', frequency=1, frequencyType='minute') else: raise ValueError("Invalid periodType: {}".format(periodType)) hist = api.GetPriceHistory(symbol=symbol, **kwargs) if 'candles' not in hist: print(hist, symbol, kwargs) candles = hist.candles time = numpy.fromiter((bar.datetime for bar in candles), dtype=int) open = numpy.fromiter((bar.open for bar in candles), dtype=float) close = numpy.fromiter((bar.close for bar in candles), dtype=float) time = time[1:] returns = (close[1:] - close[:-1]) / close[:-1] #returns2 = (close - open) / open return time, returns
def GetPositions(api: td.AmeritradeAPI, account_id: str) -> Any: """Fetch the account if of the main account. Return JSON.""" account = api.GetAccount(accountId=account_id, fields='positions') acc = next(iter(account.items()))[1] return acc['positions']
def GetBeta(api: AmeritradeAPI, symbol: str) -> float: """Get beta provided by portfolio fundamentals.""" inst = api.SearchInstruments(symbol=symbol, projection='fundamental') value = next(iter(inst.values())) return value.fundamental.beta