Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Developing an Investment Strategy

Hey guys, I will post here frequently to keep track on my work done in our Investment-Seminar in University.

First step is getting to know a bit about Quantopian and Phyton: Therefore I use a simple SMA Crossover Strategy and applying it trading the Google (or now Alphabet) Stock. It will buy the the stock if the 50 days SMA is higher than the 200 days SMA and sell the stock if the 50 days SMA is below the 200 days SMA. Starting date is the 01/04/2017, End date is 04/19/2018. Periodicity is minutely (which is automatically if you use Quantopian).

25 responses

Hello Jonathan,

Welcome. Make sure you take a look at our lectures page to see if anything might be helpful for you in your seminar.
https://www.quantopian.com/lectures

We also have example strategies there.
https://www.quantopian.com/lectures/example-long-short-equity-algorithm

Disclaimer

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 Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian 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.

Thank you very much, I will do that!

Hey guys, created now an Backtest applying the same algorithm as above. I did change the SMAs to 25 days and 100 days to see how it will influence the results. Integrated an standard schedule function as recommended by our lecturer for further tasks (but that should not influence the results).

Hey, I applied the Tutorial 2 from Quantopian using Pipeline to my SMA strategy above. Returns are lower than S&P Benchmark which could be due to the long - short strategy included in Tutorial 2.

Attached you find an basic algo using the Stochastic Oscillator applied for the Google Stock. Generating an oversold or overbought signal. Below 20 is commonly seen as a oversold indication, over 80 as overbought.
According to an interview with developer George Lane, the Stochastic Oscillator “doesn't follow price, it doesn't follow volume or anything like that. It follows the speed or the momentum of price. As a rule, the momentum changes direction before price.”

Edit: Framework for Quode used from Vladmir, thanks!: https://www.quantopian.com/posts/how-to-code-for-yesterdays-value

Trading Strategy using the Stochastic Oscillator, selling Google shares if over 80, buying if below 20. fastk 14, slowk and slowd are 3 as standard.

Applied a MACD- Strategy for trading the Apple stock. MACD uses two moving averages as lagging indicators to identify trend. Then, MACD takes the difference in values between those two Moving Averages (MACD Line) and an EMA of those Moving Averages (Signal Line) and plots that difference between the two lines as a histogram which oscillates above and below a center Zero Line.

fast 12 days, slow 26 days and signal 9 days as standard.

elif macd[-1] < macd[-2] > macd[-3] and macd[-1] < signal[-1] * .99:

thank you very much, that includes the Signal as well in the buy or sell code

Trading Strategy Q500 wih the MACD and RSI Indiators.

Jonathan

If you really are a student and just starting out down this road let me offer you a little advice. Although I may of course just be plain wrong. Many are now saying that machine learning and AI are the name of the game, not old fashioned indicators such as these.

You need to look at the arguments for and against. I'm not at all sure at this stage ML is going to lead very far in investment terms based on the most fundamental and top down view.

Markets are not a "fixed system" like the areas ML is seeing most success. EG Go and Chess and driverless cars. We do not know the rules of investment. We do not know if there are any long term rules or whether the rules simply keep changing with the years. Even if we did know all the rules (variables) it is doubtful we have the data or computing power to compute the relevant market forecasts. And that is to leave aside the question of whether markets are deterministic or random.

So frankly, these old fashioned trend following methods you are looking at may be as good as you can get at present. You need a trend to make money.

There are ways to make big money out of markets I believe but I do not think you will find them on this forum. Inside information, dealing ahead of clients, the bid offered spread at high frequency and so forth.

For long term investment I rather wonder whether people on this forum are not simply chasing their tails, including Quantopian. Long term investment is imply about following the trend of economic growth. I am not convinced there is much more to it that that. It is about diversification over world economies and currencies.

It may well be that attempts to improve on simple diversification and buy and hold are not terrribly useful. But it is fun to try.

First off, I hate those pseudonyms. It is like talking to a tree. They have no personality, can say whatever they want without being accountable for it. Just hate people hiding behind avatars. With that said.

The @Zenothestoic thing, whatever that is, is making goods points.

It should be considered futile to win in the short term if over the long term you lose or are not able to exceed the long-term indexer or averager. It would be a total waste of time or resources when you could have bought low-cost index funds to do a better long-term job.

Is the way your trading strategy designed able to outperform over the long term a benchmark, as in: Σ(H(a)∙ΔP) > Σ(H(spy)∙ΔP)?

The trader's expectation is: E[Σ(H(a)∙ΔP))] → Σ(H(spy)∙ΔP), or less due to frictional costs. There is enough literature on this that it should have been unnecessary to even mention it.

Nonetheless, trading can produce a lot more than its benchmark. It will all be in the methodology used, the strategy used: H(a). The how you slice and dice every time series in the portfolio for the duration. Not just two years, but over 20+ years where it counts. It is your long-term balance account that is the ultimate goal in this game. As if all of this is just waiting to get there. What we have to do is design our trading strategies in such a way as to make sure we get there and exceed the indexer's path to average returns. We need to know our trading strategies will do this even before we start to play.

Some of the trading methods I see here are counterproductive, some are right out designed to fail no matter what, and some just shoot themselves in the foot with so-so assumptions and premises.

Look at those that have succeeded over the long term, find out how they did it, and try to do the same or better. It is not that hard a recipe. Go for it, you can stand on the shoulders of the best of them or at least alongside.

My two cents. Well, more like a dime due to inflation.

My preferred reading on the topic would be as follows:

Stockmarkets as a complex adaptive system

Burton Malkiel

They have no personality, can say whatever they want without being accountable for it. Just hate people hiding behind avatars.

You will find my entire philosophy of life on my website.
I hide because I do not wish to become any sort of guru.

I have little that is worth saying. I am a sceptic as well as a stoic who over the course of a reasonably long life recognises he is invariably wrong about most things.

@Zenothestoic, you say: “ I hide because I do not wish to become any sort of guru.” On that, don't worry, be happy.

Nice looking site by the way. At least, you now have a personality.

Thanks for the discussion guys. Appreciated that you highlighted the possible mistakes made by trading such indicators. Currently for me its just to getting to know phyton and Quantopian and pass the course, no trading planed. Anyway I am kind of sceptical when it comes to trading any sort of indicator or technical analysis in general. My background is more from the " other side " of investment philosophy.

Using the previous Algo trading the MACD and RSI but including a ranking formular for top/bottom and selecting the stocks with a fundamental filter (Free Cashflow Yield and Book to Value).

Try experimenting around with some of this

I just wanted to pop in to say that Zenothestoic and Guy make great points. Others should read their comments above. The one addition I will make is that buying long term market exposure is very cheap, like Guy says. So the goal of strategies sometimes isn't to beat an index, but rather to provide a diversified return stream for those already heavily invested in a board market index.

Hi Jonathan -

You might have a look at this:

https://blog.quantopian.com/a-professional-quant-equity-workflow/

It is the architecture Quantopian has implemented.

Thanks Blue Seahawk, that seems a lot more structured than my previous Algo. Looks like you removed a redundant line from my previous MACD calculation and added qutite some usefull log info?

Delaney, Grant: thanks guys, will look at it.

On the business of the market being essentially efficient, I'd refer folks to Ed Thorp:

In May 1998, Thorp reported that his personal investments yielded an annualized 20 percent rate of return averaged over 28.5 years.

Regarding trading on inside information, this is a fascinating read:

Black Edge: Inside Information, Dirty Money, and the Quest to Bring Down the Most Wanted Man on Wall Street

The protagonist is providing up to $250M for the 1337 Street Fund (the Quantopian hedge fund).

Some of the changes:
QTradableStocksUS (toward the contest) instead of Q500US
Fundamentals (newer, faster, simpler) instead of morningstar
Progressively adding to the mask (m)
150 stocks each instead of 25 (just set num to try others)
.dropna() on pipeline output Yes, logging of pipeline values
target_weights currently directly from rank, compute_target_weights() is unused
fcf and bvy not yet used, try adding them again

Just tried replacing .rank with .zscore in pipeline and returns went up some.

On line 103 instead of 'rank', try macd, rsi, fcf, bvy for each of those as weights directly.

Here's some code where you can vet consistency of fundamentals, fcf_yield and book_value_yield

Using again a ranking of MACD and RSI indicators as a trading algo. Fundamental filter is now changed to PE Ratio and Return on Asset (ROA). The PE Ratio as a valuation metric is aiming to filter out for stocks which appear to be cheap (Price/EPS). The ROA as an performance metric is aiming to filter for stocks which appear to generate good returns on their employed capital (Net Income / Average Total Assets).

Focusing this week on fundamental filter. Using the Debt to Equity Ratio to filter out companies with low debt level and ROIC to filter out the companies with good return.