Hi there,
I've come up with a simple moving average buy signal, and I ran the test for the code just to see if there were any bugs, with the start date on 4 May 2016 and end date 10 May 2016. The stock I chose was CMG, and for some strange reason, it makes a double purchase at the same time 10:14am. My algo sets the order at purchasing close to $10,000 worth of stock, but I end up with close to $20,000.
I have tried this code on a) other days and b) other stocks, and there hasn't been this situation arising. Just wanted to check if there was a unique reason for it that I'm not catching it in my algo, or I need to rework my ordering process.
Thanks for your help :)
def initialize(context):
"""
Called once at the start of the algorithm.
"""
context.security = sid(28016)
def handle_data(context,data):
# Create variables for the Fast:9, Medium:25 and Slow:50 tick MAs
fast = 9
medium = 25
slow = 50
# Define the price history
price_hist_fast = data.history(context.security, 'price', fast, '1m')
price_hist_medium = data.history(context.security, 'price', medium, '1m')
price_hist_slow = data.history(context.security, 'price', slow, '1m')
# Define the moving averages and current price
mavg_fast = price_hist_fast.mean()
mavg_medium = price_hist_medium.mean()
mavg_slow = price_hist_slow.mean()
current_price = data.current(context.security, 'price')
# Rule to enter into the position
if context.portfolio.positions[context.security].amount == 0:
if mavg_fast > mavg_medium:
if mavg_medium > mavg_slow:
if current_price > mavg_fast:
try:
order_value(context.security, 10000)
except Exception as e:
print(str(e))
record('Leverage', context.account.leverage)