Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import talib
- from math import sqrt
- import numpy as np
- def initialize(context):
- schedule_function(trade_long, date_rules.every_day(), time_rules.market_close(minutes=5))
- #schedule_function(trade_short, date_rules.every_day(), time_rules.market_close(minutes=5))
- context.spy = sid(8554)
- context.long_stop_price = 0
- context.short_stop_price = np.inf
- def trade_long(context, data):
- #hist and transforms and rolling vol dataframe
- prices = data.history(context.spy, 'price', 20, '1d')
- current_price = data.current(context.spy, 'price')
- basis = context.portfolio.positions[context.spy].cost_basis
- #This is just an example breakout logic to get us in a position
- #This entry logic can be anything (breakout, MA cross, RSI pullback, etc)
- if current_price > prices[:-1].max() and context.portfolio.positions[context.spy].amount == 0:
- order_target_percent(context.spy, 0.50)
- print('buy', current_price, prices[:-1].max())
- if current_price < prices[:-1].min() and context.portfolio.positions[context.spy].amount > 0:
- order_target_percent(context.spy, 0.0)
- print('sell', current_price, prices[:-1].min())
- #If long, exit when price hits trailing stop
- if context.portfolio.positions[context.spy].amount > 0:
- context.long_stop_price = max(context.long_stop_price, (current_price * 0.95))
- print('long_stop_price',context.long_stop_price)
- if current_price < context.long_stop_price:
- order_target_percent(context.spy , 0.0)
- print('Trailing Stop Hit' , current_price, context.long_stop_price,)
- context.long_stop_price = 0
- def trade_short(context, data):
- prices = data.history(context.spy, 'price', 20, '1d')
- current_price = data.current(context.spy, 'price')
- basis = context.portfolio.positions[context.spy].cost_basis
- if current_price < prices[:-1].min() and context.portfolio.positions[context.spy].amount == 0:
- order_target_percent(context.spy, -0.5)
- print('sell', current_price, prices[:-1].min())
- #If Short, exit when price hits trailing stop
- if context.portfolio.positions[context.spy].amount < 0:
- context.short_stop_price = min(context.short_stop_price, (current_price * 1.05))
- print('short_stop_price',context.short_stop_price)
- if current_price > context.short_stop_price:
- order_target_percent(context.spy , 0.0)
- print('Trailing Stop Hit' , current_price, context.short_stop_price)
- context.short_stop_price = np.inf
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement