Beginner Algo

OK guys, tell me what you think. It's not elegant or complicated, and certainly nothing that any of you high fliers would use, but remember what it was intended for - someone new to algorithmic trading that is anxious to dip a toe into the water (like me. :) Criticism is welcome, and name calling will be ignored, so let me have it!
Update Backtest

Cool algo. Noticed you use liquidate()... Just curious - I read somewhere that liquidate() only liquidates your positions at the end of day instead of instantly. Can anyone confirm this?

@BlueGreen liquidate() simply closes that respective position. So it places an exact opposite trade with all shares that you currently have of the current symbol.


Order("AAPL", 100);

Buys 100 shares of AAPL

Now I can close this position in two different ways:

1: Order("AAPL", -100);

2: Liquidate("AAPL");

So Liquidate() simply liquidates all shares that you are currently holding (or borrowing).

Looks nice. Curious what your reasoning was to mix SMA and EMA for your slow and fast moving averages.

@Blue - I'll wait for someone that really knows what they are talking about to answer, but my experiments pointed to it working immediately. I like Liquidate() because it takes everything to flat - sells long positions and covers shorts for all symbols. Sort of cleans the slate! JP B is right, adding a symbol in the parenthesis makes it work for a specific stock but not for other positions you may have.

@ Levi - I like the mix because the EMA is weighted more toward recent bars and SMA is the "official" moving average which is flatter. I find this gives a better (for me anyway) indication of direction changes. Using 2 of either would work, but I like this mix. Since this algo is geared toward a beginner that probably has a cash account (no $25,000 minimum balance requirement) and can't short (SEC rules), it only goes long. The time delay allows for settling funds from the sale before you buy again. This EMA/SMA cross insures that the stock is going up at least at the time it orders. Of course it may crash on the next bar, but that is trading!!! :)

@OranChristian Be careful with proclaiming those trading requirements to others: they are not correct.

Margin accounts can already be opened with as little as $2000. So with as little as $2000, one can already take short positions. The settlement of funds is only a problem for round trades within the same day. Such t+3 settlement is enforced on all accounts that are lower than 25k or haven't applied for a daytrading account. However, the settlement periods differ between the products that you trade. Options only have T+1 settlement for intraday round trades. Besides, one could allocate different parts of the available funds as to capture multiple trading opportunities. Or even use multiple brokers. Also, the settlement rule is not always enforced in other countries. So some people use overseas brokers to get around the restriction.

As a comment to your strategy, the current setup is clearly not profitable and the statistics can definitely be improved. Try different combinations of moving averages and try to adjust your input parameters to the stock at hand (without overfitting). Also, make sure that you include some sort of risk management logic to quickly cut losing trades. If your prediction fails, acknowledge this and act accordingly. Don't keep positions that are based on unconfirmed premises.

@JP B - I stand corrected. I did not know that any broker would open a margin account for $2K. But then, I have only used 3 brokers in all my trading, and never checked others, and certainly none in other countries. The t+3 settlement always bugged me before I got a margin account, so I just got used to waiting 3 days between trades. Once I went full "daytrader" it wasn't a problem, but then the $25K requirement came into account. As I said, this algo was designed for someone that does not have $25K to open a daytrading account, or want to deal with multiple brokers. And yes, options settle in one day. I trade a lot of options, and I "dream" of one day settlement for stocks, but ... I never tried Forex or futures or anything else, but those are all open to traders. I wrote this for the little guy just getting started, not the "pros".

I agree that the statistics for this algo can be improved, and that it has times when it is not profitable because the stock it bought went down. But a loss only becomes a loss when you sell. This is designed to hold the stock until it becomes profitable. Yes, the experienced trader uses risk management to cut losing trades quickly, but how many newcomers do this? That comes later as they mature. Or maybe I was just a dumba-- when I got started. That is certainly a possibility :) Different combinations of moving averages and adjusting parameters could make this work better with different stocks, but there again you are thinking like a pro, not a beginner.

@JP B - Now you have got me thinking (and that hurts :). I understand working with multiple brokers when trading manually, but can you set an algorithm to split an account into pieces that it trades with multiple brokers? I am intrigued!

@Oran Christian I'm not going to jump on all your comments, but I just have to say something about the following statement:

"But a loss only becomes a loss when you sell. This is designed to hold the stock until it becomes profitable."

In my opinion, this is the absolute worst you can do! What you are basically saying is the following:

"If I take any position in any stock and it turns out that my prediction was wrong, I can always just hold the stock forever until it becomes profitable. Simply because if I don't sell, I haven't realized the loss (yet)."

DON'T DO THIS! You won't be able to hold all positions until profitability and some stocks never return to previous levels. If you follow such a strategy, one of your trades will eventually blow up your whole account. Don't even consider doing this. It's even a worse idea than the martingale strategy. If you want to be profitable, follow the following (sound) logic:

1. Make a prediction, following some initial strategy
2. Enter a position in line with the prediction
3. If the prediction is confirmed by some confirmation factor (e.g. price movement), hold the position
4. If the prediction is not confirmed, liquidate the position and take the (small) losses
5. Liquidate the confirmed position according to some exiting logic (e.g. changing environment)

That is the only way to make sure that you won't blow up your account. Position sizing can work too, but you should be very careful with this because a small losing trade can quickly turn into a big loss if the stock persists in the opposite direction.

Just my two cents.

@OranChristian Sorry if my last comment felt kind of harsh, it wasn't meant that way. So I apologize if it looked that way. I just wanted to make sure that you are careful with your money and don't make the same mistakes we did! :)

In any case, waiting for a position to turn profitable is a mistake (a pitfall!) that many traders (even professionals) still make. I've also been guilty of it; that's why I saw your statement as a red flag and wanted to warn you about it as quickly as possible. I probably should have phrased it differently.

In any case, we are all here to learn so asking questions is always a good thing. Happy trading!

@JP B, So you're saying that you would like to see a stop loss incorporated. Ok, I can live with that. The problem that I have with stop losses is that everyone you talk to will have a different opinion on where they should be set - and you know what they say about opinions ... But I think I can add one, I'll work on it anyway. I know what it is, I'm just not sure offhand how to code it.

You are a much more experienced coder than I am, so let me ask a question. I could probably figure out a simple stop loss, which is what I would use in this algo. However, thinking down the road for another idea I am toying with, is there a way to code it so that when the stop loss fires it liquidates the position - and freezes the algorithm so that it does not enter another order until you (the owner) manually looks at what's going on and release it. That adds a level of complication that I am not sure my coding skills are up to yet. Any thoughts?

No offense taken - I have thick skin. And after all, I did say criticism is welcome. I would still like an answer to my question above on trading with multiple brokers.

And I understand what you are saying, I have had my share of Enrons too :)

@OranChristian I am not a fan of stop losses either. I always prefer sound logic to cut losses quickly, like you mentioned in your first comment.

Answer to your question:
I don't think trading live with multiple brokers is possible in QC as of now.

Enclosed is a little backtest I tried to do with your demo algorithm (both long and short). As you can see, it isn't very successful. This is largely due to your time frame: moving averages do not work well on intra-day frequencies. Perhaps you should consider trading less frequently if you want to use moving averages. In either case, you can still use my algorithm to maybe learn a little bit about adding exiting logic. Also, my algorithm plots the moving averages so you can better adjust your strategy! Click on "MAs" to view the plots after you run the backtest.

@JP B - Man, your (still basic) additions just zoomed over my head like an F-16 with afterburners blazing! I'm going to have to study all that - for a month or two! I'll also consider your suggestion to switch to daily resolution. Gotta play with that one too. So much to do, so little time...

@JP B - I'm curious why you don't think moving averages work well for intra-day frequences. I use them every day with my manual trading. Is that an algorithmic thing, or am I missing something (Verry, verrrry possible) ?

@JP B - I have been studying your suggestions and (I think) I am beginning to follow your logic. Not the plotting stuff, I have never worked with any of that, but it's on my bucket list.

But you (perhaps unknowingly) answered 2 dilemmas that have been perplexing me for some time. I knew it could be done, but I had no idea of how to do it. I do now. I just wanted to say THANK YOU!

@OranChristian Don't have that much time right now but moving averages don't work that well intra-day by construction. That is, moving averages are very simple mathematical formulas that have the following objective:

- To represent prices in a 'smoother' way as to extract their general direction (also called 'trends')

Moving averages such as SMA/ EMA therefore have the following issues:

- They are lagged (they are slow to converge to new market conditions)
- They try to locate trends. Meaning that they implicitly assume that pricing dynamics are persistent.

Both of these last two issues are a problem for intra-day trading. This because (1) prices are not persistent (trends are less obvious in the intra-day domain than in the long-term domain) and (2) price movements are relatively small. Given that the indicators are lagged, it is very difficult to profit from such small movements. Simply because the 'move' will have ended by the time the moving averages indicate the new general direction.

Nevertheless, moving averages are great visual tools because they give a quick overview of the general direction of the price without being distracted by small (seemingly random) deviations. Also, they are one of the only ways to extract a price's general direction using an algorithm:

if (newMA - oldMA > 0) : general price is going up
if (newMA - oldMA < 0) : general price is going down

That's why, often, they are still a necessity for algorithmic traders. However, it's very important to realise that a strategy based on moving averages alone is weak: moving averages aren't really meant that way. They should be used as confirmation instead. E.g. let's say your strategy is based on the book-to-market ratio. If the book-to-market ratio is high, the stock is undervalued. So you want to buy the stock (long-term). But when should you buy it? Certainly it's not a good idea to do this while the stock is going down. So better to wait until a moving average confirms that the general direction of the stock is up. That's how moving averages are most useful.


Btw, had to look up your "Enron" reference! Nice little metaphor :)

@JP B, I didn't think there was anyone in the trading world that wouldn't catch that one! Maybe I'm just showing my age, or you are flaunting your youth to make me envious (it's working by the way :), but I remember well when that one was going on. Enron was the dog that all the talking heads couldn't stop talking about. Jobs were lost, fortunes lost, lives lost, people went to jail - it was a mess! It remains, to us old timers at least, a shining example of what can happen to a stock that appears to be good - until fraud is exposed :) :)

No, I didn't lose anything in Enron, but there have been a couple of others that went down similarly, though maybe not into complete obliteration, that I did get caught in. Check out Dry Ships "DRYS", 10 years ago. That one bit me big time :)

Live and learn; those lessons are well remembered!

@OranChristian Interesting story! Always fascinating to get the perspective of someone who actually traded the stock at those times. I guess it's age indeed that I didn't know it.

Found it funny to see that the analyst ratings remained very bullish until the very end:

Clearly shows that sometimes you just really need to trust your "gut" feeling instead of those "claim-to-be" analyst ratings.

Also looked up DRYS, another disaster indeed. No matter how good an algorithm, anyone picks such a stock to trade and you pay for a very expensive lesson :)

Little typo, I meant: "claim-to-be objective analyst ratings".

Update Backtest


The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


This discussion is closed