PacktPublishing / Learn-Algorithmic-Trading

Learn Algorithmic Trading, Published by Packt
MIT License
802 stars 302 forks source link

Error in ch4_turtle_trading.py? #1

Open FerusAndBeyond opened 4 years ago

FerusAndBeyond commented 4 years ago

In this part of ch4_turtle_trading.py, shouldn't in the last two elif statements "short_exit" and "long_exit" be swapped? Since if position > 0 then we are long and there should be a long exit and not a short exit and vice versa.

init=True
    position=0
    for k in range(len(signals)):
        if signals['long_entry'][k] and position==0:
            signals.orders.values[k] = 1
            position=1
        elif signals['short_entry'][k] and position==0:
            signals.orders.values[k] = -1
            position=-1
        elif signals['short_exit'][k] and position>0:
            signals.orders.values[k] = -1
            position = 0
        elif signals['long_exit'][k] and position < 0:
            signals.orders.values[k] = 1
            position = 0
        else:
            signals.orders.values[k] = 0

    return signals
Emptytolose commented 3 years ago

I had the same doubt, yet after reviewing the code I think it is correct the way it is. If you look at the line where it defines the long_exit signal, you will see that it is triggered by the price going below the window average, identifying a possible downtrend. In that case the position we are interested in exiting is the one we are short in, in the sense that we need to actually buy the stock (now that it is cheap) to cover our short position. What tricked me is that the term long_exit refers to exiting a position "by buying" not exiting a long position (thus by selling).

quant4life commented 2 years ago

I think there is a problem with the conditions. For example, the first iteration is a short signal, which means that the position will be -1. In the next iteration, it will be in the "signals['long_exit'][k] and position < 0". The problem is that it will be triggered only when adj close is below average, which is ALWAYS. that's why when you see in the graph, you will find out that the short position is immediatly closed after. Correct me if I am wrong. Have a nice day !