def indicators(): tickers = get_tickers('IBOV') start, end = get_interval(365) df = get_data( tickers=tickers, columns=["Open", "High", "Low", "Adj Close"], start=start, end=end, ) ibov = get_data(tickers="^BVSP", columns=["Adj Close"], start=start, end=end) all_rsi = get_rsi_info(df.copy(), tickers) all_stochastic = get_stochastic_info(df.copy(), tickers) all_beta = get_beta_info(df.copy(), tickers, ibov["Adj Close"]) indicators = {} for ticker in tickers: ticker = ticker.replace(".SA", "") # Get nested data price = all_rsi[ticker]["price"] variation = all_rsi[ticker]["variation"] mme80_is_up = all_stochastic[ticker]["mme80_is_up"] mm50_is_up = all_rsi[ticker]["mm50_is_up"] beta = all_beta[ticker]["beta"] corr = all_beta[ticker]["corr"] std_asset = all_beta[ticker]["std_asset"] std_bench = all_beta[ticker]["std_bench"] # Delete unnecessary data del all_rsi[ticker]["price"] del all_rsi[ticker]["variation"] del all_rsi[ticker]["mm50_is_up"] del all_stochastic[ticker]["mme80_is_up"] del all_stochastic[ticker]["price"] del all_stochastic[ticker]["variation"] indicators[ticker] = { "price": price, "variation": variation, "mme80_is_up": mme80_is_up, "mm50_is_up": mm50_is_up, "beta": beta, "corr": corr, "std_asset": std_asset, "std_bench": std_bench, "rsi": all_rsi[ticker], "stochastic": all_stochastic[ticker], } return jsonify(indicators)
def api(): tickers = get_tickers('IBOV') start, end = get_interval(365) df = get_data(tickers=tickers, columns=["Open", "High", "Adj Close"], start=start, end=end) all_rsi = get_rsi_info(df, tickers) return jsonify(all_rsi)
def all_stochastic(): tickers = get_tickers('IBOV') start, end = get_interval(120) df = get_data(tickers=tickers, columns=["High", "Low", "Adj Close"], start=start, end=end) all_stochastic = get_stochastic_info(df, tickers) return jsonify(all_stochastic)
#!/usr/bin/python import utils from stockmarket import Stock, Market sap_tickers = utils.get_tickers() # Standard & Poor's tickers stocks = utils.get_stocks_from_tickerslist(sap_tickers) dates = utils.get_dates(stocks[0].ticker) market = Market(stocks) spread = [] market_performance = [] dates_shown = [] STEP = 30 for i in range(STEP, len(stocks[0].values)-STEP, STEP): previous = i - STEP now = i next = i + STEP strong_stocks = [s for s in stocks if s.getOffensive(previous, now) >= 100 and s.getDefensive(previous, now) <= 100] weak_stocks = [s for s in stocks if s.getOffensive(previous, now) <= 100 and s.getDefensive(previous, now) >= 100] mean_strong_performance = utils.mean([s.getPerformance(now, next) for s in strong_stocks]) mean_weak_performance = utils.mean([s.getPerformance(now, next) for s in weak_stocks]) spread.append(mean_strong_performance - mean_weak_performance) market_performance.append(market.getPerformance(previous, now)) # to look for correlations with the spread dates_shown.append(dates[now]) # dates to be shown in the X axis # format the data properly and save it in a file
#!/usr/bin/python import utils import urllib2 utils.download_sap_tickers() sap_tickers = utils.get_tickers() for ticker in sap_tickers: try: utils.download_historical_daily_data(ticker, 2000, 2009) except urllib2.HTTPError: print 'data not found for ticker: %s' % ticker
def run( min_share_price, max_share_price, min_dv, n_fast, n_slow, quick, n_retries, time_zone, ): tries = 0 url, key, secret = credentialing() conn = trade_api.StreamConn(base_url=url, key_id=key, secret_key=secret, data_stream="polygon") api = trade_api.REST(base_url=url, key_id=key, secret_key=secret) def create_dict(symbols): """ creates a master dictionary with each symbol pointing to a dataframe of data collected from the stream. """ dct = {} def create_dataframe(): """ Helper function to create a dataframe that is the value for each SYMBOL key in the dictionary """ column_names = ["open", "high", "low", "close", "volume"] def get_trading_start(): """ Helper function gets the start of the trading day """ today = datetime.today().date() start = datetime(today.year, today.month, today.day, hour=8, minute=30) return start idx = pd.date_range(get_trading_start(), periods=900, freq="T") df = pd.DataFrame(columns=column_names, index=idx) return df for symbol in symbols: dct[symbol] = create_dataframe() return dct symbols_to_watch = get_tickers(api, min_share_price, max_share_price, min_dv, quick=quick) logging.info(f"Tickers added.") master_dct = create_dict(symbols_to_watch) open_orders = {} positions = {} def cancel_old_orders(api, orders, symbol, timezone, order_expiration=2): """ Cancels orders that exceed order_expiration in minutes : param api: Alpaca REST endpoint : dict orders: a dictionary with symbols for keys and orders for values : str symbol: a string with the symbol for the stock : int order_expiration: int for minutes to leave orders open """ current_time = pd.Timestamp(datetime.now().astimezone(timezone)) order_for_symbol = orders.get(symbol, None) if order_for_symbol: if ((order_for_symbol.status == "held" or order_for_symbol.status == "new") and order_for_symbol.submitted_at + timedelta(minutes=order_expiration) > current_time): try: api.cancel_order(order_for_symbol.id) logging.info(f"Order Cancelled for {symbol}") except Exception as e: logging.debug(e) logging.debug( f"Unable to cancel order id {order_for_symbol}") @conn.on(r"^trade_updates$") async def handle_trade_update(conn, channel, data): symbol = data.order["symbol"] # get the last order, or return a None value last_order = open_orders.get(symbol, None) # if the value is None (there is no order for the symbol) then loop does not cover # if the last_order is True, then loop if last_order is not None: event = data.event """ ***we are testing with only buying 1 share for each positive signal. no partial fills yet*** if event == "partial_fill": qty = int(data.order["filled_qty"]) if data.order["side"] == "sell": qty = qty * -1 positions[symbol] = positions.get(symbol, 0) - partial_fills.get( symbol, 0 ) partial_fills[symbol] = qty positions[symbol] += qty open_orders[symbol] = data.order print(f"partial fill of {symbol}") """ if event == "fill": qty = int(data.order["filled_qty"]) if data.order["side"] == "sell": qty = qty * -1 positions[symbol] = positions.get( symbol, 0) # - partial_fills.get(symbol, 0) # partial_fills[symbol] = 0 positions[symbol] += qty open_orders[symbol] = None logging.info(f"Fill of {symbol}") elif event == "canceled" or event == "rejected": # partial_fills[symbol] = 0 open_orders[symbol] = None logging.info(f"{symbol} cancelled or rejected") # print(f"{symbol} cancelled or rejected.") @conn.on(r"^AM$") async def on_minute_bars(conn, channel, data): now = datetime.strptime(datetime.now().strftime("%y-%m-%d %H:%M"), "%y-%m-%d %H:%M") master_dct[data.symbol].loc[now] = { "open": data.open, "high": data.high, "low": data.low, "close": data.close, "volume": data.volume, } # if the macd is above one, make a purchase of 1 share closes = master_dct[data.symbol].close[:now] hist = macd(closes, n_fast=n_fast, n_slow=n_slow) order_history = {} # only buy if macd is positive and symbol not already bought or open_order submitted if hist[-1] > 0 and not (positions.get(data.symbol, None) or open_orders.get(data.symbol, None)): try: buy = api.submit_order( symbol=data.symbol, qty=1, side="buy", type="limit", time_in_force="gtc", limit_price=str(data.close), order_class="bracket", take_profit=dict(limit_price=f"{data.close * 1.02}"), stop_loss=dict( stop_price=f"{data.close * 0.99}", limit_price=f"{data.close * 0.99}", ), ) open_orders[data.symbol] = buy logging.info(f"Submitted order 1 share of {data.symbol}") except Exception as e: logging.debug(e) logging.debug(f"buy order for {data.symbol} not processed...") cancel_old_orders(api, open_orders, data.symbol, time_zone) channels_to_listen = [f"AM.{symbol}" for symbol in symbols_to_watch] channels_to_listen.insert(0, "trade_updates") def run_ws(conn, channels): try: print("listening") conn.run(channels) except Exception as e: print(e) conn.close() sleep(5) run_ws(conn, channels) run_ws(conn, channels_to_listen)