예제 #1
0
    def handle_data(self, data):
        if self.target_shares == 0:
            assert 0 not in self.portfolio.positions
            self.order(self.sid(0), 10)
            self.target_shares = 10
            return
        else:

            assert self.portfolio.positions[0].amount == \
                self.target_shares, "Orders not filled immediately."
            assert self.portfolio.positions[0].last_sale_price == \
                data.current(sid(0), "price"), \
                "Orders not filled at current price."

        self.order_percent(self.sid(0), .001)

        if isinstance(self.sid(0), Equity):
            price = data.current(sid(0), "price")
            new_shares = (.001 * self.portfolio.portfolio_value) / price
        elif isinstance(self.sid(0), Future):
            new_shares = (.001 * self.portfolio.portfolio_value) / \
                (data.current(sid(0), "price") *
                    self.sid(0).contract_multiplier)

        new_shares = int(round_if_near_integer(new_shares))
        self.target_shares += new_shares
예제 #2
0
    def handle_data(self, data):
        if not self.ordered:
            assert not self.portfolio.positions
        else:
            # Since you can't own fractional shares (at least in this
            # example), we want to make sure that our target amount is
            # no more than a share's value away from our current
            # holdings.
            target_value = self.portfolio.portfolio_value * 0.002
            position_value = self.portfolio.positions[0].amount * \
                self.sale_price

            assert (
                abs(target_value - position_value) <=
                self.sale_price
            ), "Orders not filled correctly"

            assert (
                self.portfolio.positions[0].last_sale_date ==
                self.get_datetime()
            ), "Orders not filled at current price."

        self.sale_price = data.current(sid(0), "price")
        self._order(sid(0), .002)
        self.ordered = True
예제 #3
0
def initialize(context):
    # Provide the bid-ask spread for each of the securities in the universe.
    spreads = {
        sid(24): 0.05,
        sid(3766): 0.08
    }

    # Initialize slippage settings given the parameters of our model
    set_slippage(PerStockSpreadSlippage(spreads))
예제 #4
0
def handle_data(context, data):
     
    for stock in data:
    	print stock, sid(stock)
    if not context.has_ordered:
 
        for stock in data:
            print stock
            order(sid(stock), 100)
        context.has_ordered = True
    print "==================="
예제 #5
0
 def handle_data(self, data):
     if self.incr == 0:
         assert 0 not in self.portfolio.positions
     else:
         assert self.portfolio.positions[0].amount == \
             self.incr, "Orders not filled immediately."
         assert self.portfolio.positions[0].last_sale_price == \
             self.last_price, "Orders was not filled at last price."
     self.incr += 1
     self.order_value(self.sid(0), data.current(sid(0), "price"))
     self.last_price = data.current(sid(0), "price")
예제 #6
0
def handle_data_api(context, data):
    if context.incr == 0:
        assert 0 not in context.portfolio.positions
    else:
        assert context.portfolio.positions[0].amount == context.incr, "Orders not filled immediately."
        assert context.portfolio.positions[0].last_sale_price == data.current(
            sid(0), "price"
        ), "Orders not filled at current price."
    context.incr += 1
    order(sid(0), 1)

    record(incr=context.incr)
예제 #7
0
    def handle_data(self, data):
        if self.incr == 0:
            assert 0 not in self.portfolio.positions
        else:
            assert self.portfolio.positions[0].amount == self.incr, "Orders not filled immediately."
            assert self.portfolio.positions[0].last_sale_price == data.current(
                sid(0), "price"
            ), "Orders not filled at current price."
        self.incr += 2

        multiplier = 2.0
        if isinstance(self.sid(0), Future):
            multiplier *= self.sid(0).multiplier

        self.order_value(self.sid(0), data.current(sid(0), "price") * multiplier)
예제 #8
0
    def handle_data(self, data):
        if self.target_shares == 0:
            assert 0 not in self.portfolio.positions
            self.order(self.sid(0), 10)
            self.target_shares = 10
            return
        else:
            assert self.portfolio.positions[0].amount == self.target_shares, "Orders not filled immediately."
            assert self.portfolio.positions[0].last_sale_price == data.current(
                sid(0), "price"
            ), "Orders not filled at current price."

        self.order_target_value(self.sid(0), 20)
        self.target_shares = np.round(20 / data.current(sid(0), "price"))

        if isinstance(self.sid(0), Equity):
            self.target_shares = np.round(20 / data.current(sid(0), "price"))
        if isinstance(self.sid(0), Future):
            self.target_shares = np.round(20 / (data.current(sid(0), "price") * self.sid(0).multiplier))
예제 #9
0
 def handle_data(self, data):
     if self.target_shares == 0:
         assert 0 not in self.portfolio.positions
     else:
         assert self.portfolio.positions[0].amount == self.target_shares, "Orders not filled immediately."
         assert self.portfolio.positions[0].last_sale_price == data.current(
             sid(0), "price"
         ), "Orders not filled at current price."
     self.target_shares = 10
     self.order_target(self.sid(0), self.target_shares)
예제 #10
0
 def compute(self, today, asset_ids, out, *inputs):
     #print asset_ids
     #print maskset
     if asset_finder != None:
         assets = [_sid(id).symbol for id in asset_ids]
     else:
         assets = [sid(id).symbol for id in asset_ids]
     #print "--------------"
     #print pd.Series(assets)
     out[:] = pd.Series(assets).isin(maskdf.index)
예제 #11
0
    def handle_data(self, data):
        if self.incr == 0:
            assert 0 not in self.portfolio.positions
        else:
            assert self.portfolio.positions[0]['amount'] == \
                self.incr, "Orders not filled immediately."
            assert self.portfolio.positions[0]['last_sale_price'] == \
                data.current(sid(0), "price"), \
                "Orders not filled at current price."
        self.incr += 2

        multiplier = 2.
        if isinstance(self.sid(0), Future):
            multiplier *= self.sid(0).multiplier

        self.order_value(
            self.sid(0),
            data.current(sid(0), "price") * multiplier
        )
예제 #12
0
 def handle_data(self, data):
     if self.incr == 0:
         assert 0 not in self.portfolio.positions
     else:
         assert self.portfolio.positions[0]["amount"] == self.incr, "Orders not filled immediately."
         assert self.portfolio.positions[0]["last_sale_price"] == data.current(
             sid(0), "price"
         ), "Orders not filled at current price."
     self.incr += 1
     self.order(self.sid(0), 1)
예제 #13
0
 def handle_data(self, data):
     if self.incr == 0:
         assert 0 not in self.portfolio.positions
     else:
         assert self.portfolio.positions[0].amount == \
             self.incr, "Orders not filled immediately."
         assert self.portfolio.positions[0].last_sale_price == \
             data.current(sid(0), "price"), \
             "Orders not filled at current price."
     self.incr += 1
     self.order(self.sid(0), 1)
예제 #14
0
 def handle_data(self, data):
     if self.target_shares == 0:
         assert 0 not in self.portfolio.positions
     else:
         assert self.portfolio.positions[0].amount == \
             self.target_shares, "Orders not filled immediately."
         assert self.portfolio.positions[0].last_sale_price == \
             data.current(sid(0), "price"), \
             "Orders not filled at current price."
     self.target_shares = 10
     self.order_target(self.sid(0), self.target_shares)
예제 #15
0
def handle_data(context, data):
    # 获取股票的收盘价
    close_data = history(12,'1d','close')
    # 取得过去五天的平均价格
    ma5 = close_data[-6:-2].mean()
    # 取得过去10天的平均价格
    ma10 = close_data[-11:-2].mean()
    # 取得当前的现金

    print get_datetime(),ma5,ma10
    cash = context.portfolio.cash
    
    #print ma5[sid(symbol(context.security))],ma10[sid(stock)],cash,symbol(context.security)
    #如果当前有余额,并且五日均线大于十日均线
    if ma5[sid(symbol(context.security))] > ma10[sid(symbol(context.security))]:
         order_value(symbol(context.security), cash)
    # 如果五日均线小于十日均线,并且目前有头寸
    elif ma5[sid(symbol(context.security))] < ma10[sid(symbol(context.security))]:
        # 全部卖出
        order_target(symbol(context.security), 0)
예제 #16
0
    def handle_data(self, data):
        if self.target_shares == 0:
            assert 0 not in self.portfolio.positions
            self.order(self.sid(0), 10)
            self.target_shares = 10
            return
        else:
            assert self.portfolio.positions[0].amount == \
                self.target_shares, "Orders not filled immediately."
            assert self.portfolio.positions[0].last_sale_price == \
                data.current(sid(0), "price"), \
                "Orders not filled at current price."

        self.order_target_value(self.sid(0), 20)
        self.target_shares = np.round(20 / data.current(sid(0), "price"))

        if isinstance(self.sid(0), Equity):
            self.target_shares = np.round(20 / data.current(sid(0), "price"))
        if isinstance(self.sid(0), Future):
            self.target_shares = np.round(
                20 / (data.current(sid(0), "price") * self.sid(0).multiplier))
예제 #17
0
def handle_data_api(context, data):
    if context.incr == 0:
        assert 0 not in context.portfolio.positions
    else:
        assert context.portfolio.positions[0]['amount'] == \
            context.incr, "Orders not filled immediately."
        assert context.portfolio.positions[0]['last_sale_price'] == \
            data[0].price, "Orders not filled at current price."
    context.incr += 1
    order(sid(0), 1)

    record(incr=context.incr)
예제 #18
0
def handle_data_api(context, data):
    if context.incr == 0:
        assert 0 not in context.portfolio.positions
    else:
        assert (context.portfolio.positions[0].amount == context.incr
                ), "Orders not filled immediately."
        assert (context.portfolio.positions[0].last_sale_date == context.
                get_datetime()), "Orders not filled at current datetime."
    context.incr += 1
    order(sid(0), 1)

    record(incr=context.incr)
예제 #19
0
def handle_data_api(context, data):
    if context.incr == 0:
        assert 0 not in context.portfolio.positions
    else:
        assert context.portfolio.positions[0]['amount'] == \
            context.incr, "Orders not filled immediately."
        assert context.portfolio.positions[0]['last_sale_price'] == \
            data[0].price, "Orders not filled at current price."
    context.incr += 1
    order(sid(0), 1)

    record(incr=context.incr)
예제 #20
0
    def zmq_event_gen(self, port=5555):
        context = zmq.Context()
        price_socket = context.socket(zmq.REQ)
        price_socket.connect('tcp://localhost:%s' % port)

        orders_socket = context.socket(zmq.PUB)
        orders_socket.bind('tcp://*:%s' % (port+1))

        for dt in self.sim_params.trading_days:
            prices = []

            # Investigate the asset_finder class. How might data be stored?
            for sid_id in self.trading_environment.asset_finder.sids:
                prompt =  "{}  [{}]".format(dt, sid(sid_id))
                price_socket.send_string(prompt)
                data = price_socket.recv_string()
                price = float(data)

                # Look at DataFrameSource to see that the dataframe input
                # quickly gets turned into a series of events (that are yielded)
                event = {
                    'dt': dt,
                    'sid': sid(sid_id),
                    'price': float(price),
                    'volume': 1e9,
                    'type': DATASOURCE_TYPE.TRADE,
                }
                event = Event(event)
                prices.append(event)

            # We return a generator. Zipline makes heavy use of `yield` and generators
            # to build an event-driven model that runs syncronously].
            # How could we modify an algoithm to run async?
            yield dt, prices

            # What columns are being displayed?
            # Why might some orders have a commission and others are NAN?
            # 'orders' is a collection of all orders placed.
            # How could we change this to include open_orders?
            show_orders(self.blotter.orders, orders_socket)
예제 #21
0
    def handle_data(self, data):
        if self.incr == 0:
            assert len(self.portfolio.positions.keys()) == 0

            method_to_check = getattr(self, self.method_name)
            method_to_check(self.sid(133), data.current(sid(0), "price"), style=StopLimitOrder(10, 10))

            assert len(self.blotter.open_orders[self.sid(133)]) == 1
            result = self.blotter.open_orders[self.sid(133)][0]
            assert result.limit == 10
            assert result.stop == 10

            self.incr += 1
예제 #22
0
    def handle_data(self, data):
        if not self.ordered:
            assert 0 not in self.portfolio.positions
        else:
            # Since you can't own fractional shares (at least in this
            # example), we want to make sure that our target amount is
            # no more than a share's value away from our current
            # holdings.
            target_value = self.portfolio.portfolio_value * 0.002
            position_value = self.portfolio.positions[0].amount * \
                self.sale_price

            assert abs(target_value - position_value) <= self.sale_price, \
                "Orders not filled correctly"

            assert self.portfolio.positions[0].last_sale_price == \
                data.current(sid(0), "price"), \
                "Orders not filled at current price."

        self.sale_price = data.current(sid(0), "price")
        self.order_target_percent(self.sid(0), .002)
        self.ordered = True
예제 #23
0
 def findSector(self, assets):
     sector_list = []
     for msid in assets:
         stock = sid(msid).symbol
         try:
             industry = basic.loc[stock].industry
             sector_no = sector_dict[industry]
             sector_list.append(sector_no)
         except:
             #print "stock %s in industry %s not find in default sector set, set zero" % (stock,industry)
             sector_list.append(self.missing_value)
         else:
             pass
     return sector_list
 def compute(self, today, assets, out, *inputs):
     if trigger_date != None and today != pd.Timestamp(trigger_date,
                                                       tz='UTC'):
         return
     if os.path.splitext(source)[1] == '.csv':
         df = pd.read_csv(source, index_col=0, parse_dates=True)
         # df = df[df.index >= pd.Timestamp(str(today))]
         print today, df
     else:
         raise ValueError
     new_index = [sid(asset).symbol + "_return" for asset in assets]
     df = df.reindex(columns=new_index)
     out[:] = df.ix[0].values
     print "RNNpredict:", today, out
예제 #25
0
def get_sectors_no(mids):
    basic = load_tushare_df("basic")
    _class, _ = get_sector_class()
    no_ = []
    missing_value = 0
    for msid in mids:
        stock = sid(msid).symbol
        try:
            industry = basic.loc[stock].industry
            sector_no = _class[industry]
            no_.append(sector_no)
        except:
            # print "stock %s in industry %s not find in default sector set, set zero" % (stock,industry)
            no_.append(missing_value)
    return no_
예제 #26
0
    def handle_data(self, data):
        if self.incr == 0:
            assert len(self.portfolio.positions.keys()) == 0

            method_to_check = getattr(self, self.method_name)
            method_to_check(self.sid(133),
                            data.current(sid(0), "price"),
                            style=StopLimitOrder(10, 10))

            assert len(self.blotter.open_orders[self.sid(133)]) == 1
            result = self.blotter.open_orders[self.sid(133)][0]
            assert result.limit == 10
            assert result.stop == 10

            self.incr += 1
예제 #27
0
def initialize(context):
    """
    Called once at the start of a backtest, and once per day at
    the start of live trading.
    """
    # Attach the pipeline to the algo
    algo.attach_pipeline(make_pipeline(), 'pipeline')

    algo.set_benchmark(algo.sid('FIBBG000BDTBL9'))

    # Rebalance every day, 30 minutes before market close.
    algo.schedule_function(
        rebalance,
        algo.date_rules.every_day(),
        algo.time_rules.market_close(minutes=30),
    )
예제 #28
0
def handle_data_api(context, data):
    if context.incr == 0:
        assert 0 not in context.portfolio.positions
    else:
        assert (
            context.portfolio.positions[0].amount ==
            context.incr
        ), "Orders not filled immediately."
        assert (
            context.portfolio.positions[0].last_sale_date ==
            context.get_datetime()
        ), "Orders not filled at current datetime."
    context.incr += 1
    order(sid(0), 1)

    record(incr=context.incr)
예제 #29
0
 def _find_sector(self, asset):
     sector_no = 0
     sector_name = ""
     if asset_finder != None:
         stock = _sid(asset).symbol
     else:
         stock = sid(asset).symbol
     try:
         industry = basic.loc[stock].industry
         sector_no = sector_dict[industry]
         sector_name = industry
     except:
         #print "stock %s in not find in default sector set, set zero" % (stock)
         pass
     else:
         pass
     return sector_no, sector_name
예제 #30
0
def bonds(context, data):
    logger.debug('buying bonds on: %s', algo.get_datetime())
    logger.debug('num open orders: %s', len(algo.get_open_orders()))
    logger.debug('len existing portfolio (afer ejection): %s',
                 len(context.portfolio.positions))
    logger.debug('cash: %s', context.portfolio.cash)
    logger.debug('portfolio_value: %s', context.portfolio.portfolio_value)
    logger.debug('num_positions: %s', len(context.portfolio.positions))
    logger.debug('positions: %s', context.portfolio.positions)

    if logger.level is logging.DEBUG:
        for equity, values in context.portfolio.positions.items():
            logger.debug(
                'context.portfolio.positions - equity: %s, amount: %s, cost_basis: %s, sold_on: %s, sold_at_price: %s',
                equity, values.amount, values.cost_basis,
                values.last_sale_date, values.last_sale_price)

    if context.portfolio.cash > 0 and context.trend_filter is False:
        logger.debug('converting all cash to bonds')
        order_target_value(algo.sid('FIBBG000NTFYM5'), context.portfolio.cash)
예제 #31
0
    def handle_data(self, data):
        if self.incr == 0:
            assert 0 not in self.portfolio.positions
        else:
            assert (
                self.portfolio.positions[0].amount ==
                self.incr
            ), "Orders not filled immediately."
            assert (
                self.portfolio.positions[0].last_sale_date ==
                self.get_datetime()
            ), "Orders not filled at current datetime."
        self.incr += 2

        multiplier = 2.
        if isinstance(self.sid(0), Future):
            multiplier *= self.sid(0).multiplier

        self.order_value(
            self.sid(0),
            data.current(sid(0), "price") * multiplier
        )
예제 #32
0
 def compute(self, today, assets, out, *inputs):
     if trigger_date != None and today != pd.Timestamp(
             trigger_date, tz='UTC'
     ):  # 仅仅是最重的预测factor给定时间执行了,其他的各依赖factor还是每次computer调用都执行,也流是每天都执行! 不理想
         return
     if os.path.splitext(source)[1] == '.db':
         conn = sqlite3.connect(
             source, check_same_thread=False)  #预测过程由外部程序完成,结果写入到数据库中
         query = "select * from predict where date >= '%s' order by date limit 1 " % str(
             today)[:19]
         df = pd.read_sql(query, conn)
         df = df.set_index('date')
         conn.close()
     elif os.path.splitext(source)[1] == '.csv':
         df = pd.read_csv("predict.csv", index_col=0, parse_dates=True)
         df = df[df.index >= pd.Timestamp(str(today))]
         print today, df
     else:
         raise ValueError
     new_index = [sid(asset).symbol + "_return" for asset in assets]
     df = df.reindex(columns=new_index)
     out[:] = df.ix[0].values
     print "RNNpredict:", today, out
예제 #33
0
import pytz
from datetime import datetime
from zipline.api import order, symbol, record, order_target, sid
from zipline.algorithm import TradingAlgorithm
from zipline.utils.factory import load_bars_from_yahoo
from zipline import api

dow_constituents = [
    ["1999-11-01", sid(4922), 1],  # Minnesota Mining & Manufacturing/3M Company
    ["1999-11-01", sid(2), 1],
    ["1999-11-01", sid(679), 1],
    ["1999-11-01", sid(7289), 1],  # AT&T Corporation
    ["1999-11-01", sid(698), 1],
    ["1999-11-01", sid(1267), 1],
    ["1999-11-01", sid(1335), 1],
    ["1999-11-01", sid(4283), 1],
    ["1999-11-01", sid(2119), 1],
    ["1999-11-01", sid(2482), 1],
    ["1999-11-01", sid(8347), 1],
    ["1999-11-01", sid(3149), 1],
    ["1999-11-01", sid(3246), 1],
    ["1999-11-01", sid(3735), 1],
    ["1999-11-01", sid(3496), 1],
    ["1999-11-01", sid(25090), 1],  # AlliedSignal Incorporated/Honeywell
    ["1999-11-01", sid(3951), 1],
    ["1999-11-01", sid(3766), 1],
    ["1999-11-01", sid(3971), 1],
    ["1999-11-01", sid(25006), 1],
    ["1999-11-01", sid(4151), 1],
    ["1999-11-01", sid(4707), 1],
    ["1999-11-01", sid(5029), 1],
예제 #34
0
def handle_data(context, data):
    print context
    #raw_input()

    #输出每天持仓情况

    if not context.has_ordered:
        for stock in data:
            #openprice=history(3, '1d', 'open')
            closeprice = history(5, '1d', 'close')
            #-2:昨天,-3 前天.-4 大前天
            print get_datetime(), closeprice[sid(stock)][0], closeprice[sid(
                stock)][1], closeprice[sid(stock)][2], closeprice[sid(
                    stock)][3], closeprice[sid(stock)][4]
            #print closeprice,closeprice[sid(stock)][1]
            if closeprice[sid(stock)][-2] > closeprice[sid(
                    stock)][-3] and closeprice[sid(stock)][-3] > closeprice[
                        sid(stock)][-4]:
                print "buy", get_datetime()
                order(stock, 300)
            elif closeprice[sid(stock)][-2] < closeprice[sid(
                    stock)][-3] and closeprice[sid(stock)][-3] < closeprice[
                        sid(stock)][-4]:
                print "sell", get_datetime()
                order(stock, -300)
예제 #35
0
def initialize(context):
    """
    Called once at the start of the algorithm.
   
    """
    # STANDARD SETTINGS
    # set_benchmark(sid(8554)) #SPY
    # set_slippage(slippage.FixedSlippage(spread=0.00))
    # set_commission(commission.PerShare(cost=0.0, min_trade_cost=0))

    # DAILY, WEEKLY, MONTHLY
    context.rebalance_frequency = RebalanceFrequency.DAILY

    # Must be a positive integer, refer to parameters of each function
    # rebalance_number = 5 if RebalanceFrequency.DAILY and you want to rebalance every 5 days
    # rebalance_number = 3 if RebalanceFrequency.MONTHLY and you want to rebalance every 3 months
    context.rebalance_number = 1

    context.lookback = 42

    # Default universe

    context.securities = [
        (sid(19662)),  #XLY
        (sid(21652)),  #IYR
        (sid(21647)),  #IYG
        (sid(19656)),  #XLF
        (sid(19658)),  #XLK
        (sid(19655)),  #XLE
        (sid(19661)),  #XLV
        (sid(19657)),  #XLI
        (sid(19659)),  #XLP
        (sid(19654)),  #XLB
        (sid(19660))  #XlU
    ]

    # Run at the start of each month, when the market opens and rebalance

    zipline.schedule_function(rebalance,
                              context.rebalance_frequency,
                              time_rule=zipline.time_rules.market_open())
예제 #36
0
def rebalance(context, data):
    """
    Execute orders according to our schedule_function() timing.
    """
    logger.debug('rebalancing on: %s', algo.get_datetime())

    context.trend_filter = False

    # new_portfolio = algo.pipeline_output('pipeline').dropna(subset=['overall_rank']).sort_values('momentum', ascending=False)

    new_portfolio = algo.pipeline_output('pipeline').dropna(
        subset=['overall_rank']).sort_values('momentum', ascending=False)

    for equity, row in new_portfolio.iterrows():
        logger.debug('new portfolio (before filtering) - equity: %s', equity)

    # print(new_portfolio)

    # new_portfolio = new_portfolio[new_portfolio['overall_rank'].notna() & new_portfolio['momentum'] > 40][:20]

    # new_portfolio = new_portfolio[(new_portfolio['momentum_decile'] > 8)][:20]

    new_portfolio = new_portfolio.nlargest(
        20, ['overall_rank', 'momentum'])  #<- $600K PL in 10 years

    # new_portfolio = new_portfolio.nlargest(20, ['momentum', 'overall_rank'])  #<- 1M PL in 10 years

    if logger.level is logging.DEBUG:
        for equity, row in new_portfolio.iterrows():
            logger.debug('new portfolio - (after filtering) equity: %s',
                         equity)

    # print(len(new_portfolio.index))

    # volatility driven weights
    # new_portfolio['inverse_volatility'] = new_portfolio['volatility'].apply(lambda x: 1 / x)
    # inv_vola_sum = new_portfolio['inverse_volatility'].sum()
    # new_portfolio['target_weight'] =  new_portfolio['inverse_volatility'].apply(lambda x: x / inv_vola_sum)

    # portfolio size driven weights
    # num_equities = len(new_portfolio.index)
    # new_portfolio['target_weight'] =  1 / num_equities\

    # logger.info('len existing portfolio: %s', len(context.portfolio.positions))

    if logger.level is logging.DEBUG:
        for equity, values in context.portfolio.positions.items():
            logger.debug(
                'context.portfolio.positions - equity: %s, amount: %s, cost_basis: %s, sold_on: %s, sold_at_price: %s',
                equity, values.amount, values.cost_basis,
                values.last_sale_date, values.last_sale_price)

    order_target(algo.sid('FIBBG000NTFYM5'), 0)
    logger.debug('selling all bonds')

    for equity in context.portfolio.positions:
        if equity is algo.sid('FIBBG000NTFYM5'):
            continue
        if equity not in set(new_portfolio.index.tolist()):
            # logger.info('selling %s', equity)
            order_target_percent(equity, 0)

    stock_weights = 1.0 / max(len(context.portfolio.positions),
                              len(new_portfolio.index))

    logger.debug('len existing portfolio (afer ejection): %s',
                 len(context.portfolio.positions))
    logger.debug('len new portfolio: %s', len(new_portfolio.index))
    logger.debug('stock_weights: %s', stock_weights)

    # print(context.portfolio.positions.get(algo.sid('FIBBG000NTFYM5')))

    # spy = context.portfolio.positions.get(algo.sid('FIBBG000NTFYM5'))

    # if (spy is not None) and (spy.amount > 0):
    #     order_target_percent(algo.sid('FIBBG000NTFYM5'), 0)

    for equity, row in new_portfolio.iterrows():
        if row.trend_filter is True:
            # logger.info('buying %s', equity)
            context.trend_filter = True
            order_target_percent(equity, stock_weights)
        else:
            context.trend_filter = False

    logger.debug('cash: %s', context.portfolio.cash)
    logger.debug('portfolio_value: %s', context.portfolio.portfolio_value)
    logger.debug('num_positions: %s', len(context.portfolio.positions))
    logger.debug('positions: %s', context.portfolio.positions)
예제 #37
0
def handle_data(context, data):
    log.info(f"Trade date {data.current_session}")

    # look for existing strategies to exit first which avoids immeditely
    # exiting an entered strategy
    if context.complex_positions:
        log.info(f"Found positions to trade: {context.complex_positions}")

        for complex_position in context.complex_positions:
            log.info(f"Processing {data.current_session}")

            # check if any date to exit trade has been exceeded. using any
            # covers the case where there are uneven expirations. this is a bad
            # approach because naively takes dte without considering trading days
            # if trade_exit_dte_breached is true, exit trade (covered in if below)
            dte_session_ = partial(
                dte_session,
                context.trading_calendar,
                context.backtest_params["trade_exit_dte"],
            )
            trade_exit_dte_reached = any([
                context.datetime >= dte_session_(
                    sid(leg.option).expiration_date)
                for leg in complex_position
            ])

            # compute the cost basis of the position which is used to decide whether
            # to exit position based on the position stop loss. execution price
            # would be better than cost_basis but this value doesn't seem to exist
            cost_basis = sum([
                context.portfolio.positions[leg.option].cost_basis *
                np.copysign(1, context.portfolio.positions[leg.option].amount)
                for leg in complex_position
            ])

            # aggregate the current value of the position based on the last_sale_price
            # which is the mid price. mid is probably a decent estimate of the closing
            # price for atm liquid options
            current_value = sum([
                context.portfolio.positions[leg.option].last_sale_price *
                np.copysign(1, context.portfolio.positions[leg.option].amount)
                for leg in complex_position
            ])

            # if the curent value of the position, which is negative if a credit,
            # gets closer to 0 e.g. increases e.g. spreads start to collapse, we're
            # making money. therefore if the current_value is greater than the
            # basis minus what money we want to make, we buy back the position at
            # a winner
            # if the current value of the position, which is negative if a credit,
            # goes further negative e.g. spreads continue to widen, we're losing
            # money. therefore if the current_value is less than the basis
            # plus the stop loss percent, we buy back the position at a loser
            is_debit = is_long = cost_basis > 0
            stop_reached, limit_reached = check_order_triggers(
                current_value,
                is_debit,
                is_long,
                stop_price=context.stop_percent * cost_basis,
                limit_price=context.limit_percent * cost_basis,
            )
            print(
                f"current_value={current_value} stop_price={context.stop_percent * cost_basis} limit_price={context.limit_percent * cost_basis}"
            )
            if stop_reached or limit_reached or trade_exit_dte_reached:
                print("in exit ")
                [order(leg.option, -leg.amount) for leg in complex_position]
                context.complex_positions.remove(complex_position)

    chain = option_chain(context.root_symbol, data.current_session)
    ic = IronCondors(chain, **context.backtest_params)
    trades = ic.get_trades()

    if not trades.empty:

        for _, trade in trades.iterrows():
            sids = trade[[
                "short_call_sid", "long_call_sid", "short_put_sid",
                "long_put_sid"
            ]].values
            amounts = trade[[
                "short_call_amount",
                "long_call_amount",
                "short_put_amount",
                "long_put_amount",
            ]].values

            # add the orders
            [order(sid(s), a) for s, a in zip(sids, amounts)]

            # track the orders
            context.complex_positions.append(
                [Leg(sid(s), a) for s, a in zip(sids, amounts)])
예제 #38
0
def initialize(context):
    context.aapl = sid(24)
    schedule_function(ma_crossover_handling, date_rules.every_day(),
                      time_rules.market_open(hours=1))
예제 #39
0
def initialize(context):
    dates = pd.date_range('2018-01-01', '2018-09-28')
    # assets = bundle_data.asset_finder.lookup_symbols(['A', 'AAL'], as_of_date=None)
    # assets = bundle_data.asset_finder
    sids = bundle_data.asset_finder.sids
    assets = [sid(item) for item in sids]

    # The values for Column A will just be a 2D array of numbers ranging from 1 -> N.
    column_A_frame = pd.DataFrame(
        data=np.arange(len(dates) * len(assets), dtype=float).reshape(len(dates), len(assets)),
        index=dates,
        columns=sids,
    )

    # Column B will always provide True for 0 and False for 1.
    column_B_frame = pd.DataFrame(data={sids[0]: True, sids[1]: False}, index=dates)

    loaders = {
        MyDataSet.column_A: DataFrameLoader(MyDataSet.column_A, column_A_frame),
        MyDataSet.column_B: DataFrameLoader(MyDataSet.column_B, column_B_frame),
    }

    def my_dispatcher(column):
        return loaders[column]

    # Set up pipeline engine

    # Loader for pricing
    pipeline_loader = USEquityPricingLoader(
        bundle_data.equity_daily_bar_reader,
        bundle_data.adjustment_reader,
    )

    def choose_loader(column):
        if column in USEquityPricing.columns:
            return pipeline_loader
        return my_dispatcher(column)

    engine = SimplePipelineEngine(
        get_loader=choose_loader,
        calendar=trading_calendar.all_sessions,
        asset_finder=bundle_data.asset_finder,
    )

    p = Pipeline(
        columns={
            'price': USEquityPricing.close.latest,
            'col_A': MyDataSet.column_A.latest,
            'col_B': MyDataSet.column_B.latest
        },
        screen=StaticAssets(assets)
    )

    df = engine.run_pipeline(
        p,
        pd.Timestamp('2016-01-07', tz='utc'),
        pd.Timestamp('2016-01-07', tz='utc')
    )

    df = df.sort_values(by=['price'], axis=0, ascending=False)

    print(df)
def initialize(context):
    bundle_data = bundles.load('quandl')
    sids = bundle_data.asset_finder.sids
    symbols = [sid(item) for item in sids]
예제 #41
0
def handle_data(context, data):
    if not context.has_ordered:
        for stock in data:
            order(sid(stock), 100)
        context.has_ordered = True
예제 #42
0
def handle_data(context, data):
    if not context.has_ordered:
        for stock in data:
            order(sid(stock), 100)
        context.has_ordered = True
예제 #43
0
    def __init__(self):
        '''
        this is a utility class that can return the list of Dow30 stocks for a given date.
        the input date must be >= 1999-11-01.
        source: http://www.djindexes.com/mdsidx/downloads/brochure_info/Dow_Jones_Industrial_Average_Historical_Components.pdf
        '''

        raw_constituents = [
            ["1999-11-01", sid(4922), 1],  # Minnesota Mining & Manufacturing/3M Company
            ["1999-11-01", sid(2), 1],
            ["1999-11-01", sid(679), 1],
            ["1999-11-01", sid(7289), 1],  # AT&T Corporation
            ["1999-11-01", sid(698), 1],
            ["1999-11-01", sid(1267), 1],
            ["1999-11-01", sid(1335), 1],
            ["1999-11-01", sid(4283), 1],
            ["1999-11-01", sid(2119), 1],
            ["1999-11-01", sid(2482), 1],
            ["1999-11-01", sid(8347), 1],
            ["1999-11-01", sid(3149), 1],
            ["1999-11-01", sid(3246), 1],
            ["1999-11-01", sid(3735), 1],
            ["1999-11-01", sid(3496), 1],
            ["1999-11-01", sid(25090), 1],  # AlliedSignal Incorporated/Honeywell
            ["1999-11-01", sid(3951), 1],
            ["1999-11-01", sid(3766), 1],
            ["1999-11-01", sid(3971), 1],
            ["1999-11-01", sid(25006), 1],
            ["1999-11-01", sid(4151), 1],
            ["1999-11-01", sid(4707), 1],
            ["1999-11-01", sid(5029), 1],
            ["1999-11-01", sid(5061), 1],
            ["1999-11-01", sid(4954), 1],
            ["1999-11-01", sid(5938), 1],
            ["1999-11-01", sid(6653), 1],  # SBC Communications Incorporated/AT&T Incorporated
            ["1999-11-01", sid(7883), 1],
            ["1999-11-01", sid(8229), 1],
            ["1999-11-01", sid(2190), 1],
            ["2004-04-08", sid(7289), 0],
            ["2004-04-08", sid(2482), 0],
            ["2004-04-08", sid(3971), 0],
            ["2004-04-08", sid(239), 1],
            ["2004-04-08", sid(5923), 1],
            ["2004-04-08", sid(21839), 1],
            ["2008-02-19", sid(4954), 0],
            ["2008-02-19", sid(25090), 0],
            ["2008-02-19", sid(700), 1],
            ["2008-02-19", sid(23112), 1],
            ["2008-09-22", sid(239), 0],
            ["2008-09-22", sid(22802), 1],  # KRFT/MDLZ
            ["2009-06-08", sid(1335), 0],
            ["2009-06-08", sid(3246), 0],
            ["2009-06-08", sid(7041), 1],
            ["2009-06-08", sid(1900), 1],
            ["2012-09-24", sid(22802), 0],
            ["2012-09-24", sid(7792), 1],
            ["2013-09-23", sid(700), 0],
            ["2013-09-23", sid(3735), 0],
            ["2013-09-23", sid(20088), 1],
            ["2013-09-23", sid(35920), 1],
            ["2015-03-18", sid(6653), 0],
            ["2015-03-18", sid(24), 1]
        ]

        # translate the date string into a datetime.date
        self.data = []
        for equity in raw_constituents:
            self.data.append((
                datetime.datetime.strptime(equity[0], "%Y-%m-%d").date(),
                equity[1],
                equity[2]
            ))