|
| 1 | +''' |
| 2 | + A benchmark comparison to buying and holding SPY at 100%. |
| 3 | +
|
| 4 | + NOTE: This algo can run in minute-mode simulation and is compatible with LIVE TRADING. |
| 5 | +''' |
| 6 | + |
| 7 | +import pandas as pd |
| 8 | +from zipline.api import order_target_percent |
| 9 | + |
| 10 | +def initialize(context): |
| 11 | + set_long_only() |
| 12 | + set_symbol_lookup_date('2008-01-01') |
| 13 | + schedule_function(trade, |
| 14 | + date_rule=date_rules.every_day(), |
| 15 | + time_rule=time_rules.market_open()) |
| 16 | + |
| 17 | + context.secs = [symbol('SPY')] |
| 18 | + context.pcts = [1.0] |
| 19 | + context.ETFs = zip(context.secs, context.pcts) # list of tuples |
| 20 | + |
| 21 | +def handle_data(context, data): |
| 22 | + pass |
| 23 | + |
| 24 | +def trade(context, data): |
| 25 | + """ |
| 26 | + Make sure the porfolio is fully invested every day. |
| 27 | + """ |
| 28 | + threshold = 0.05 |
| 29 | + |
| 30 | + need_full_rebalance = False |
| 31 | + # rebalance if we have too much cash |
| 32 | + if context.portfolio.cash / context.portfolio.portfolio_value > threshold: |
| 33 | + need_full_rebalance = True |
| 34 | + |
| 35 | + # What we should do is first sell the overs and then buy the unders. |
| 36 | + if need_full_rebalance: |
| 37 | + # Get the current exchange time, in the exchange timezone |
| 38 | + exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern') |
| 39 | + # perform the full rebalance if we flagged the need to do so |
| 40 | + for sid, target in context.ETFs: |
| 41 | + order_target_percent(sid, target) |
| 42 | + log.info("Rebalanced at %s" % str(exchange_time)) |
| 43 | + |
0 commit comments