Back to Community
Why

Why bet correctly at the beginning when price>ma100 but close the position too late when price<ma100 instead of price<ma10 as the script call?
Where I'm wrong?
Thanks and please forgive my poor english

Clone Algorithm
1
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
def initialize(context):
    context.stocks = symbols('CLNE')
    context.max_expo = 100000.1 #max position size long
    context.min_expo = -100000.0 #max position size short
    context.bet_amount = 100000 / len(context.stocks) #max per stock 
    
def handle_data(context, data):
    for stock in data:
        ma10 = data[stock].mavg(10)
        ma100 = data[stock].mavg(100)
        price = data[stock].price  #security current price
        position = context.portfolio.positions[stock].amount
        value = context.portfolio.positions[stock].amount * price
        record(STOCK=data[symbol('CLNE')].price, MA10=ma10, MA100=ma100)
           
        if (price > ma100):
            if position == 0:
                if value < context.max_expo:
                    nos = int(context.bet_amount/price)
                    order(stock, nos)
        elif (price < ma10):
            if position > 0:
                order_target(stock, 0)
  
        
There was a runtime error.
3 responses

I believe this is due to the order of your if statements. The ma10 condition is only checked when the "if" condition is not met. This is because of how "elif" (else-if) works. Just change the order if you want to give the ma10 signal higher priority.

Thanks very much
..I apologize... I feel very newby

Of course, and it's no problem, I did not know this until a few days ago either.