Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Begginer SMA algorithm

Hi everyone,

I'm posting my very basic algorithm. At the moment it seems to be working, but I have problems with the leverage. As far as I understand, there should not be leverage (debt) involved, but drawdawns of over 100% (and the backtests detailed analysis) point otherwise. Understanding and solving this issue will be my next step.

Of course, any comment/help will be highly appreciated.

2 responses

Hi Ricardo,

I made some changes to your code and posted below. Here are a few notes:

  1. I don't think it makes sense to iterate over the scheduling functions. This may create weird behavior. Typically, you would only call a scheduling function once. Since it looks like you want to run the algo logic once every minute, you do not need to schedule a function. Simply, define a function called handle_data(context, data). The IDE will run this once per minute.

  2. I moved your parameters into the initialize function and set them as attributes using the context variable. This is just considered best practice. See the following link for reference: https://www.quantopian.com/posts/why-is-context-dot-constant-preferred-vs-simply-defining-a-global-constant

Try this:

def initialize(context):  
    # Parameters  
    context.shorto = 15   #  shorter period average  
    context.longo = 25   #  longer period average  
    context.assets = 0.5 #  times my capital  
    # Set comissions  
    set_commission(commission.PerShare(cost=0.000, min_trade_cost=0.0))

    # Choosing the stock and benchmark  
    context.stock = symbol('JPM')  
    set_benchmark(context.stock) 

def handle_data(context, data):  
    MovingAvg1 = data.history(context.stock, 'price', context.shorto,'1m').mean()  
    MovingAvg2 = data.history(context.stock, 'price', context.longo,'1m').mean()  
    if (MovingAvg1 < MovingAvg2):  
        order_target_percent(context.stock, 0)  
    if (MovingAvg1 > MovingAvg2) :  
        order_target_percent(context.stock, context.assets)  

Hope this helps.

Thank you very much, Michael.
I was able to incorporate your code. It really is much simpler and easier to understand.

As the algorithm wasn't behaving as expected, I set the slipagge to zero, and now I get something I can understand. So my algorithm, even without any commision or slippage, on the time-frame I'm backtesting, looses money. I also tried the opposite logic and it becomes profitable!

So my next steps are further revising the algorithm parameters and logic, to make sure I have something rational and profitable, and then add comissions and slippage to make the model more realistic.

I'm attaching the results in case they can be of help to someone else.