Created
May 29, 2018 18:09
-
-
Save mempirate/699b9140b69367641a6cb03ee552c4f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def handle_data(context, data): | |
RSI_periods = 14 | |
context.i += 1 | |
if context.i < RSI_periods: | |
return | |
RSI_data = data.history(context.asset, | |
"price", | |
bar_count = RSI_periods, | |
frequency = "30T") | |
# compute RSI | |
oversold = 30 | |
overbought = 70 | |
deltas = RSI_data.diff() | |
seed = deltas[:RSI_periods + 1] | |
up = seed[seed >= 0].sum() / RSI_periods | |
down = -seed[seed < 0].sum() / RSI_periods | |
RS = up / down | |
RSI = 100 - (100 / (1 + RS)) | |
# get current price | |
price = data.current(context.asset, "price") | |
if context.base_price == None: | |
context.base_price = price | |
price_change = (price - context.base_price) / context.base_price | |
record(price = price, | |
cash = context.portfolio.cash, | |
price_change = price_change, | |
RSI = RSI) | |
orders = context.blotter.open_orders | |
if len(orders) > 0: | |
return | |
if not data.can_trade(context.asset): | |
print("Cannot trade right now") | |
return | |
pos_amount = context.portfolio.positions[context.asset].amount | |
# strategy logic | |
if pos_amount == 0 and RSI <= oversold: | |
order_target_percent(context.asset, 1) | |
elif pos_amount < 0 and RSI <= 40: | |
order_target_percent(context.asset, 0) | |
elif pos_amount == 0 and RSI >= overbought: | |
order_target_percent(context.asset, -1) | |
elif pos_amount > 0 and RSI >= 60: | |
order_target_percent(context.asset, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment