def run(self, symbols): symbols = [i.upper() for i in symbols] # Instantiate API class config = ib_web_api.Configuration() config.verify_ssl = False client = ib_web_api.ApiClient(config) api = MarketDataApi(client) for symbol in symbols: print('===> ' + symbol) # Get last 15 minutes data # TODO: Catch here points = api.iserver_marketdata_history_get( Company(symbol).get_conid(), '15min', bar='1min').data # Get just volume vol = [p.to_dict()['v'] for p in points] # Min/max/mean volume points, perc increase from mean to hi lo = min(i for i in vol if i > 0) hi = max(vol) m = mean(vol) perc = ((hi - m) / m) * 100 # Print stats print('LO: ' + str(lo)) print('HI: ' + str(hi)) print('ME: ' + str(round(m, 2))) print('PERC: ' + str(round(perc, 2)) + '%') print('CONID: ' + Company(symbol).get_conid())
def get_contracts_cheaper_than(price, redownload=False): try: # Get cheap symbols # returns: # - price # - category # - industry symbols = get_symbols_cheaper_than(price) except Exception as e: raise Exception('Could not get cheap symbols:', e) res = {} for symbol, price in symbols.items(): # Get contracts try: company = Company(symbol) contract = company.get_contract(redownload=redownload) res[symbol] = { 'price': price, 'category': contract['category'], 'industry': contract['industry'], } except Exception as e: print('Could not get contract', symbol, ':', e) return res
def get_quote(symbol): global debug # Download conid and quote from IB # Also, update count percentage if debug: log('Start %s' % symbol) try: global count_done global count_perc global count_total global dir_quote ret = {} c = Company(symbol) quote = c.get_quote(period='3d', bar='1d') count_done += 1 if (count_done / count_total) * 10 >= count_perc: log(str(count_perc * 10) + '%') count_perc = count_perc + 1 with open(dir_quote + '/' + symbol + '.json', 'w') as f: # Save quote to dir f.write(json.dumps(quote)) if debug: log('End %s' % symbol) return { 'symbol': symbol, 'data': quote, } except Exception as e: # Failed to get conid, print the ticker raise Exception('symbol: %s: %s' % (symbol, e))
def get_quote(symbol): # Init client conid = Company(symbol).get_conid() company = ICompany(conid) try: quote = ICompany(conid).get_quote('2d', '1min') except Exception as e: raise Exception('Could not get symbol %s' % symbol) return {symbol: quote}
def get_winners_lt_perc(price, perc_increase): # Winners price less than PRICE, increase higher than PERC # TODO: Finish this # Return: { symbol: { price, perc }, ... } out = {} try: # Get cheap symbols symbols = get_symbols_cheaper_than(price) except Exception as e: print('Could not get winners', price, ',', perc_increase, ':', e) # TODO: Get here the difference, perc, hi/lo # Wrong. Need to use the day data for symbol in symbols: company = Company(symbol) quote = company.get_quote_single() print('l', quote['l']) print('h', quote['h']) pass return symbols
def down_day(symbol): global count_total global count_progress log('%s: Down' % symbol) try: quote = Company(symbol).get_quote(period='1d', bar='1min') # Log progress count_progress += 1 log('Progress: %i/%i' % (count_progress, count_total)) except Exception as e: raise Exception('%s: Could not get symbol: %s' % (symbol, e)) return {'symbol': symbol, 'data': quote}
def __init__(self, description="", price=0.0, cost=0.0, actual_balance=0.0, weight=0.0, getin="", cod="", min_sales=0.0, company=Company()): self.description = description self.price = price self.cost = cost self.actual_balance = actual_balance self.weight = weight self.getin = getin self.cod = cod self.min_sales = min_sales self.company = company
def get_conid(symbol): # Download conid and quote from IB # Also, update count percentage if debug is True: log('Start %s' % symbol) try: global count_done global count_perc global count_total global dir_quote ret = {} c = Company(symbol) conid = c.conid count_done += 1 if (count_done / count_total) * 10 >= count_perc: log(str(count_perc * 10) + '%') count_perc = count_perc + 1 if debug: log('End %s' % symbol) return conid except Exception as e: # Failed to get conid, print the ticker raise Exception('symbol: %s: %s' % (symbol, e))
# Parse args parser = argparse.ArgumentParser( description='Display last day data for symbol') parser.add_argument('symbol', metavar='SYMBOL', type=str, help='Symbol, e.g. AAPL') parser.add_argument('-s', dest='small', action='store_true', help='Print only result (category), without the symbol') args = parser.parse_args() symbol = args.symbol ### MAIN ### c = Company(symbol) day = Company(symbol).get_quote(period='1d', bar='1min') #print(json.dumps(day)) vol_non_zero = [e['v'] for e in day if e['v'] != 0.0] vol = [e['v'] for e in day] stats = { 'vol_len': len(day), 'vol_non_zero_len': len(vol_non_zero), 'vol_avg': round(mean(vol), 2), 'vol_median': round(median(vol), 2), 'vol_median_non_zero': round(median(vol_non_zero), 2), 'vol_min': min(vol_non_zero), 'vol_max': max(vol), } print(json.dumps(stats))
# Run as: ./script.py TICKER # Example: ./script.py AAPL # OS import argparse import json import os import urllib3 # Local import sys, os sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../')) from lib.company import Company # Config urllib3.disable_warnings() ### MAIN ### # Parse args parser = argparse.ArgumentParser( description='Get quote for symbol') parser.add_argument('symbol', metavar='SYMBOL', type=str, help='Symbol, e.g. AAPL') args = parser.parse_args() symbol = args.symbol # Get quote c = Company(symbol) quote = c.get_quote(period='3d', bar='1d') print(quote)
debug = False # Parse args parser = argparse.ArgumentParser( description='Display last day data for ticker') parser.add_argument('symbol', metavar='SYMBOL', type=str, help='Symbol, e.g. AACG') args = parser.parse_args() symbol = args.symbol # Main try: # Get symbol day data # ret: ? company = Company(symbol) data = company.disk_find('day') except Exception as e: print('ERROR: Could not get day data:', e) exit(1) try: # Get perc increase for point in data: print(point['l']) pass except Exception as e: print('ERROR: Could not get day perc increase:', e) exit(1)
symbol: info for symbol, info in contracts.items() if info['industry'] == industry } symbols = symbols_contracts.keys() print(symbols_contracts) print('Got %i symbols' % len(symbols)) except Exception as e: print('ERROR: Could not get contracts:', e) exit(1) try: # Generate JSON data days_info = {} print('Generate report data') for symbol in symbols: c = Company(symbol) day = c.get_day_cache() vol_non_zero = [e['v'] for e in day if e['v'] != 0.0] vol = [e['v'] for e in day] days_info[symbol] = { 'price': symbols_contracts[symbol]['price'], 'vol_len': len(day), 'vol_non_zero_len': len(vol_non_zero), 'vol_avg': round(mean(vol), 2), 'vol_median': round(median(vol), 2), 'vol_median_non_zero': round(median(vol_non_zero), 2), 'vol_min': min(vol_non_zero), 'vol_max': max(vol), } except Exception as e: print('ERROR: Could not build report: %s' % e)
def __init__(self, product=Product(), company=Company()): self.product = product self.company = company self.model = None self.product_learning = ProductLearning()
#!/usr/bin/env python3 # Get ohlc history for given symbol # Run as: ./$0 TICKERS # Example: ./$0 HTBX import argparse import json # Local from lib.company import Company # Parse args parser = argparse.ArgumentParser( description='Display last day data for symbol') parser.add_argument('symbol', metavar='SYMBOL', type=str, help='Symbol, e.g. HTBX') args = parser.parse_args() symbol = args.symbol ## MAIN history = Company(symbol).get_quote('1m', '5min') print(json.dumps(history, indent=2))
#!/usr/bin/env python3 # Download contracts # TODO: Make this about re-downloading contracts, as already getting # in download-conids # run time: 3m47s # Local import sys, os sys.path.append( os.path.join(os.path.dirname(os.path.realpath(__file__)), '../')) from lib.company import Company from lib.filters import get_contracts_cheaper_than from lib.util import get_symbols # Main try: print('Get symbols') symbols = get_symbols() except Exception as e: print('ERROR: Could not get symbols:', e) exit(1) try: print('Get contracts') for symbol in symbols: c = Company(symbol) except Exception as e: print('ERROR: Could not get contracts:', e) exit(1)
# TODO: get_winners_lt_perc does not actually use perc_increase winner_symbols = get_winners_lt_perc(price_max, perc_increase) if debug: print('Got %i winner symbols' % len(winner_symbols)) except Exception as e: print('ERROR: Could not get winners:', e) exit(1) # Populate data out = {} for symbol, price in winner_symbols.items(): out[symbol] = { 'price': price, 'industry': None, } try: # Get industry from symbols for symbol, price in winner_symbols.items(): try: out[symbol].update({'industry': Company(symbol).industry}) except Exception as e: error('ERROR: Could not get industry', e) except Exception as e: error('ERROR: Could not get industries', e) exit(1) # Final print print(len(out)) print(out['REFR']) #print(json.dumps(out))