def __init__(self): self.KEY = os.environ["ALLY_CONSUMER_KEY"] self.SECRET = os.environ["ALLY_CONSUMER_SECRET"] self.TOKEN = os.environ["ALLY_OAUTH_TOKEN"] self.OATH_SECRET = os.environ["ALLY_OAUTH_SECRET"] self.ACCT = os.environ['ALLY_ACCOUNT_NBR'] self.a = ally.Ally()
def get_balances() -> pd.DataFrame: """Gets balance details for the account." Returns ------- pd.DataFrame Dataframe of transaction history """ a = ally.Ally() return a.balances(dataframe=True)
def get_history() -> pd.DataFrame: """Gets transaction history for the account." Returns ------- pd.DataFrame Dataframe of transaction history """ a = ally.Ally() return a.history(dataframe=True)
def get_holdings() -> pd.DataFrame: """Get holdings from Ally account in pandas df Returns ------- pd.DataFrame Dataframe of positions """ a = ally.Ally() return ally_positions_to_df(a.holdings(dataframe=True))
def initAlly(): ALLY_CONSUMER_KEY = os.getenv("ALLY_CONSUMER_KEY") ALLY_CONSUMER_SECRET = os.getenv("ALLY_CONSUMER_SECRET") ALLY_OAUTH_TOKEN = os.getenv("ALLY_OAUTH_TOKEN") ALLY_OAUTH_SECRET = os.getenv("ALLY_OAUTH_SECRET") if not (ALLY_CONSUMER_KEY and ALLY_CONSUMER_SECRET and ALLY_OAUTH_TOKEN and ALLY_OAUTH_SECRET): print("No Ally credentials given, skipping") return None a = ally.Ally() # Wow, that was easy! return a
def get_stock_quote(ticker: str) -> pd.DataFrame: """Gets quote for stock ticker Parameters ---------- ticker : str Ticker to get. Can be in form of 'tick1,tick2...' Returns ------- pd.DataFrame Dataframe of ticker quote """ a = ally.Ally() return a.quote( ticker, fields=["last", "bid", "ask", "opn", "dollar_value", "chg", "vl"], dataframe=True, )
def get_top_movers(list_type: str, exchange: str) -> pd.DataFrame: """ Gets top lists from ally Invest API. Documentation for parameters below: https://www.ally.com/api/invest/documentation/market-toplists-get/ Parameters ---------- list_type : str Which list to get data for exchange : str Which exchange to look at Returns ------- pd.DataFrame DataFrame of top movers """ a = ally.Ally() return a.toplists(list_type, exchange, dataframe=True)
def Test(t): t = int(t) print("TEST " + str(t)) a = ally.Ally() if t == 1: instrument = ally.instrument.Equity('TSLA') print(instrument) op = ally.instrument.Put(instrument, "2019-10-18", 55) print(op) orders = [ ally.order.Order(instrument=ally.instrument.Equity('spy'), quantity=ally.order.Quantity(100), timespan=ally.order.Timespan('day'), type=ally.order.Buy(), price=ally.order.Market()) ] for order in orders: print(a.submit_order(order)) elif t == 2: print(ally.utils.option_format("ibm", "2014-01-18", 200.00, "call")) print(ally.utils.option_format()) print(a.account_history()) elif t == 3: print(a.holdings_chart('graph.png')) elif t == 4: print(a.get_quote('nvda', 'bid,ask')) print(a.get_quote('nvda,chk,brk.b', 'bid,ask,vol')) print(a.get_quote(['nvda', 'chk,brk.b'], ['bid', 'ask', 'vol']))
def show_holdings(): a = ally.Ally() hold = a.holdings() stonks = list(hold.sym) last_prices = np.asarray(list(hold.lastprice.astype(float))).round(2) equity = list(round(hold.marketvalue.astype(float), 2)) # Loop to get previous close (ally api does not provide that) tickers = yf.Tickers(" ".join(stonks)) prev_closes = np.array([t.info["previousClose"] for t in tickers.tickers]) pct_changes = ((last_prices - prev_closes) / prev_closes).round(3) print("Stonk\t last price \t prev close \t equity \t % Change") for stonk, last_price, prev_close, eq, pct_change in zip( stonks, last_prices, prev_closes, equity, pct_changes): to_print = f"{stonk}\t {last_price}\t\t {prev_close}\t\t {eq}\t\t {pct_change}" if last_price >= prev_close: print(colored(to_print, "green")) else: print(colored(to_print, "red")) print("")
import concurrent.futures import logging import ally logger = logging.getLogger(__name__) a = ally.Ally() def job(): logger.info("Submitting job") return a.timesales("spy", startdate="2020-06-19", enddate="2020-06-19", block=False) with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: logger.info("Submitting requests") # Submit all our orders futures = {executor.submit(job): i for i in range(200)} logger.info("Submitted!") logger.info("Getting results...") for future in concurrent.futures.as_completed(futures): logger.info("%s #%s", future.result(), futures[future])
def Test(t): t = int(t) print("TEST " + str(t)) a = ally.Ally() if t == 1: instrument = ally.instrument.Equity('TSLA') print(instrument) op = ally.instrument.Put(instrument, "2019-10-18", 55) print(op) orders = [ ally.order.Order(instrument=ally.instrument.Equity('spy'), quantity=ally.order.Quantity(100), timespan=ally.order.Timespan('day'), type=ally.order.Buy(), price=ally.order.Market()) ] for order in orders: print(a.submit_order(order, verbose=True)) elif t == 2: print(ally.utils.option_format("ibm", "2014-01-18", 200.00, "call")) print(ally.utils.option_format()) print(json.dumps(a.account_history(), indent=4)) elif t == 3: print(a.holdings_chart('graph.png')) elif t == 4: print(a.get_quote('nvda', 'bid,ask')) print(a.get_quote('nvda,chk,brk.b', 'bid,ask,vol')) print(a.get_quote(['nvda', 'chk,brk.b'], ['bid', 'ask', 'vol'])) elif t == 5: print(a.get_quote('ally')) help(a.get_holdings) elif t == 6: orders = [ ally.order.Order(instrument=ally.instrument.Equity('nflx'), quantity=ally.order.Quantity(20), timespan=ally.order.Timespan('day'), type=ally.order.Sell(), price=ally.order.Limit(400)) ] ids = [ a.submit_order(order, preview=True, verbose=False) for order in orders ] for i in ids: # ensure we're only considering 200's if i['response']: print(json.dumps(i['response'], indent=4, sort_keys=True)) elif t == 7: # View prior orders o = ally.order.Cancel(sys.argv[2]) print(json.dumps(o, indent=4)) x = a.submit_order(o, verbose=True) print(json.dumps(x, indent=4)) elif t == 8: ts = a.timesales('spy', interval='1min', startdate='2020-03-26') print(json.dumps(ts, indent=4, sort_keys=True)) elif t == 9: print("Attempting market streaming") print(a.quote_stream(symbols='SPY')) elif t == 10: print("market info:", json.dumps(a.market_clock(), indent=4)) print("api server info:", json.dumps(a.api_status(), indent=4)) elif t == 11: print("timesales") n_pages = 10 for i in range(n_pages): print(i) x = a.timesales(symbols='spy', rpp=str(n_pages), interval='1min', index=str(i), startdate='2020-03-26') print("Found ", len(x), "ticks") print(json.dumps(x, indent=4)) df = pd.DataFrame(x) df['datetime'] = pd.to_datetime(df['datetime']) df = df.set_index('datetime') df.to_csv('/tmp/df.csv' + str(i)) elif t == 12: print("Get member information:") easyPrint(a.get_member()) elif t == 13: print("Get all watchlists") easyPrint(a.get_watchlists()) elif t == 14: print( "Add new watchlist: make sure to specify tests.py 14 NAME symbol1,symbol2,..." ) easyPrint(a.new_watchlist(sys.argv[2], sys.argv[3].split(','))) elif t == 15: print("view symbols in watchlist tests.py 15 NAME") easyPrint(a.watchlist(sys.argv[2])) elif t == 16: print("delete watchlist tests.py 16 NAME") easyPrint(a.delete_watchlist(sys.argv[2])) elif t == 17: print("delete symbol from watchlist test.py 17 NAME SYMBOL") easyPrint(a.delete_symbol(sys.argv[2], sys.argv[3])) elif t == 18: print( "Add symbol: make sure to specify tests.py 14 NAME symbol1,symbol2,..." ) easyPrint(a.add_symbol(sys.argv[2], sys.argv[3].split(','))) elif t == 20: print("Search for news on several symbols") print("Use like this: test.py 20 tsla,nvda,...") easyPrint( a.news_search( sys.argv[2].split(','), maxhits=10 # startdate = '03/18 00:00', # enddate = '03/21 00:00' )) elif t == 21: print("Toplists (not top-less!)") print("use like this: test.py 21 (toplist type) (exchange)") x = a.toplist(sys.argv[2], sys.argv[3]) print("Found", len(x), "entries!") easyPrint(x)
def return_holdings() -> pd.DataFrame: a = ally.Ally() hold = a.holdings() return ally_positions_to_df(hold)
def login(): try: ally.Ally() except Exception as e: print(e) print("")
def Test(t): t = int(t) print("TEST " + str(t)) a = ally.Ally() if t == 1: instrument = ally.instrument.Equity('TSLA') print(instrument) op = ally.instrument.Put(instrument, "2019-10-18", 55) print(op) orders = [ ally.order.Order( instrument=ally.instrument.Equity('spy'), quantity=ally.order.Quantity(100), timespan=ally.order.Timespan('day'), type=ally.order.Buy(), price=ally.order.Market() ) ] for order in orders: print(a.submit_order(order,verbose=True)) elif t == 2: print(ally.utils.option_format("ibm", "2014-01-18", 200.00, "call")) print(ally.utils.option_format()) print(a.account_history()) elif t == 3: print(a.holdings_chart('graph.png')) elif t == 4: print(a.get_quote('nvda','bid,ask')) print(a.get_quote('nvda,chk,brk.b','bid,ask,vol')) print(a.get_quote(['nvda','chk,brk.b'],['bid','ask','vol'])) elif t == 5: print(a.get_quote('ally')) help(a.get_holdings) elif t == 6: orders = [ ally.order.Order( instrument=ally.instrument.Equity('nflx'), quantity=ally.order.Quantity(20), timespan=ally.order.Timespan('day'), type=ally.order.Sell(), price=ally.order.Limit(400) ) ] ids = [ a.submit_order(order, preview=True, verbose=False) for order in orders ] for i in ids: # ensure we're only considering 200's if i['response']: print(json.dumps(i['response'], indent=4, sort_keys=True)) elif t == 7: # View prior orders o = ally.order.Cancel(sys.argv[2]) print(json.dumps(o, indent=4)) x = a.submit_order(o,verbose=True) print(json.dumps(x, indent=4))