Skip to content

Instantly share code, notes, and snippets.

@WillForan
Created March 4, 2019 17:17
Show Gist options
  • Save WillForan/0020f4ce134ba05b3bb7852f34ad57b0 to your computer and use it in GitHub Desktop.
Save WillForan/0020f4ce134ba05b3bb7852f34ad57b0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ######
# sample short code -- test features
# USAGE:
# pipenv run pylivetrader run -f AlpacaShortTest.py --backend-config config.yaml
# ######
import pylivetrader.backend.alpaca
def monkey_patch_api(version="/v2"):
origreq = pylivetrader.backend.alpaca.tradeapi.REST._request
pylivetrader.backend.alpaca.tradeapi.REST._request = \
lambda self, method, path, data=None, prefix=version, base_url=None: \
origreq(self, method, path, data, prefix, base_url)
monkey_patch_api()
from pylivetrader.api import (
order_percent, get_datetime,
get_open_orders, cancel_order,
schedule_function, order_target_percent,
date_rules, time_rules, symbol)
from pylivetrader.finance.execution import StopOrder
import logbook
from numpy import array
import talib
import numpy as np
import pandas as pd
import sys
from datetime import datetime
import yaml
import os
log = logbook.Logger('ShortTest')
# log.handlers.append(logbook.FileHandler('ShortTest.log', level='DEBUG'))
log.handlers.append(logbook.StreamHandler(sys.stdout, level='DEBUG'))
# setup api outside of pylivetrader
with open('config.yaml', 'r') as f:
c = yaml.safe_load(f)
os.environ['APCA_API_BASE_URL'] = c['base_url']
os.environ['APCA_API_KEY_ID'] = c['key_id']
os.environ['APCA_API_SECRET_KEY'] = c['secret']
api = pylivetrader.backend.alpaca.tradeapi.REST()
def initialize(context):
context.stocks = [symbol('CIFS'), symbol('AMZN'), symbol('AAPL')]
DT = datetime.now() # assume Eastern local clock
# get time in minutes relative to 9:30
t = (DT.hour - 9)*60 + (DT.minute - 30)
t = t + 1 # start one minute from now
schedule_function(ShortFunc, date_rules.every_day(),
time_rules.market_open(minutes=t),
True)
# buyback a minute later
schedule_function(BuybackFunc, date_rules.every_day(),
time_rules.market_open(minutes=t+1), True)
def ShortFunc(context, data):
ptrade = 1/len(context.stocks)
for sec in context.stocks:
if not data.can_trade(sec):
log.debug("cannot trade %s" % sec.symbol)
# # can_short is not a function/method
# if not data.can_short(sec):
# log.debug("cannot short %s" % sec.symbol)
curpri = data.current(sec, 'price')
log.info("looking at %s @ $%.02f" % (sec.symbol, curpri))
asset = api.get_asset(sec.symbol)
if not asset.shortable:
log.debug("%s cannot be shorted!" % sec.symbol)
log.info("trying to short %.0f%% at %s @ $%.02f" %
(ptrade*100, sec.symbol, curpri))
order_percent(sec, -1 * ptrade)
def BuybackFunc(context, data):
for sec in context.stocks:
curpri = data.current(sec, 'price')
log.info("buyback %s @ $%.02f" % (sec.symbol, curpri))
order_target_percent(sec, 0)
def before_trading_start(context, data):
# alpaca restarts might occur mid day
today = get_datetime().floor('1D')
if today == getattr(context, 'run_last', None):
log.warning("before_trading_start hit, but already run for today")
return
else:
log.info("before_trading_start hit")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment