Hello
This is my first go around with writing an algo using quantopian / robinhood. I use the R language mostly for doing my custom work and work with my external data sources. I am looking to implement a simple strategy. fetch an external csv, my signals are pre-generated using R. They are in a signal column in the .csv. 1 = long and 0 = no position. When we meet a signal 1, an order to buy next days open is to be generated. After long is initiated, sell after fixed 'n' days. That is all that is required.
My attempt at putting the logic together for this is below:
def initialize(context):
# Robinhood settings
set_long_only()
set_commission(commission.PerShare(cost=0, min_trade_cost=0))
#set_benchmark(symbol('UPRO'))
context.upro_long = symbol('UPRO')
context.allocation = 0.95 # Robinhood requires either limit orders or a 5% margin on orders.
context.bought = False
context.sold = False
# Schedule/ rebalance??
# Algo needs to run each day.... check for signal = 1...
# Load External CSV
def initialize(context):
fetch_csv('http url/.csv', symbol='signal') #signal column is either 1 or 0, 1 is a long
def handle_data(context, data):
# get the signal for this date
current_signal = data.current('signal')
# Buy when signal == 1, buy next days market open
signal = current_signal == 1
if signal == 1 and not context.bought:
order_target_percent(context.upro_long, context.allocation) # need to set: buy next day open
context.bought = True
context.sold = False
# After long initiated, Sell after fixed 'n' days
# Sell at market close or 1 minute before market close
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
set_universe(universe.DollarVolumeUniverse(40, 45)) #??????
context.countdown = {}
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
# Implement your algorithm logic here.
# data[sid(X)] holds the trade event data for that security.
# context.portfolio holds the current portfolio state.
# Place orders with the order(SID, amount) method.
# TODO: implement your own logic here.
num_of_days_to_sell = 30
for sid in data:
# check if we should sell
if sid in context.countdown and context.countdown[sid] != []:
days_left = context.countdown[sid][0]
if days_left > 0:
context.countdown[sid][0] = days_left - 1
else:
context.countdown[sid].pop(0)
# sell the stock
order(sid, -100)
message = 'sell {n} shares {s}.'
log.info(message.format(n = 100, s = sid.symbol))
It for sure needs a lot more work, wondering if anyone would be able to assist? I can be contacted too at [email protected] for some 1-1 guidance!
Thanks
Andrew