Anyone found a substantial momentum effect?

I keep trying various ways of framing possible momentum stocks, but I keep failing to find any substantial effect which I would want to invest in. I've tried some relative momentum, some absolute time-series momentum, but nothing has really stuck. Does anyone have a good example of a way to isolate stock momentum with incontrovertible evidence of the effect?

Simon.

78 responses

It sounds pretty similar to mean reversion, except in the opposite direction. For example, if a stock is trading above its mean, one would expect it to go higher (rather than revert downward to its mean), and if a stock is trading below its mean, it should go lower (rather than revert upward to its mean). So, one approach would be to formulate the problem in a similar fashion to the OLMAR optimization (http://arxiv.org/ftp/arxiv/papers/1206/1206.4626.pdf), except that you need to devise a model for the expected return due to the momentum effect (the inequality constraint, 4.2. Formulation, Optimization Problem: OLMAR). I'm not sure how it would help you screen for individual "momentumish" stocks, but you could do the optimization on bunch of portfolios until you land on one that seems to be the right mix. One problem is that you can end up all long or all short in stocks, so if you need to be market-neutral, you'll need an ETF or something, too.

I am pretty skeptical of OLMAR, though I know people here seem to love it, and as you say, it doesn't help with screening.

I was more curious if there is anyone who has gotten anything to work at all, I feel like I am missing some important piece of the momentum puzzle, but I am starting to suspect it might be the data from 1950->2002 :/

My only suggestion in this case is to try momentum as an addition to another screen. Say you have some fundamental factor, and now within the stocks selected by the first screen you try to use a momentum signal. It's very possible that momentum is no longer a profitable signal, as many firms probably adopted it as papers were published and it may be completely arbitraged now.

Another option is to do momentum or mean reversion on an other time series than price. New data sources seem to me to be a far more viable source of alpha than the already mined price data set. There may be opportunities to feed in, say, how full the parking lots are for a given retail chain and try to extract a momentum signal out of that.

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.

Yeah, I've had even less luck with momentum as an additional screen or filter... it's possible that it has been arbitraged away, but I was hoping someone here could disprove that idea!

My humble opinion is that a good way to approach it is to look for new ranking factors based on very new academic research. Many of them will be overfit, but I suspect a few will carry water. Momentum is a factor that has been around forever, and the newer factors are where the signals may lie. I will now shamelessly plug the thread I made listing some interesting papers from the last conference I was at.

Yeah, a sector allocation model based on a basket of predictors in a regression of some kind is on my list. I am hesitant to investigate any of the new data feeds; to keep the cost of a $50 feed under 0.5% p.a., a reasonable maximum for management fees, you'd need to use it in an algo funded with$120k. That seems out of my reach. Conceivably there are models out there based on those data sets with annual returns >10% CAR which might justify the fees, but I have other models to automate before digging into the new data.

Simon, Are you looking for an indicator or algo? Probably you know about ADX and DMI indicators to help you to measure the strength of the trend

EG

Yeah, I've tried those, moving averages, ROC, classic 12-1 momentum, but I have failed to find anything investable among equities...

This is somewhat related I have found that using long term MA crossovers to determine weighting of long short strategies has some water. For instance if you use a 200 and 50 to determine bull and bear markets then weight 40% long and 60% short in a bear market and vice versa seems to hold water (at least in seemed to be in the case of the few strategies I tested). Haven't dug into it extensively yet because I've been working on polishing my contest entries for next month and tackling school, but take a peek at adding that filter into your long short strategies.

Simon, I'd encourage you and other readers to give more consideration to the data from our partners.

1) We've done all the work to integrate the data for you. Symbols are mapped to sids and the data is ready to use. The effort to cleanse and map and generally manage this data is significant. Your time is valuable so I don't think this should be discounted. A skilled engineer in North America can freelance at rates between $100 -$250/hr. Almost all this data, per month, is less than one hour of your time.

2) We've convinced each of these data partners to provide free samples for very large swaths of time -- all but 1 or 2 years of their historical data. So you can assess and explore the signal in the data without spending a single cent.

3) If you want access to the latest data from these sets, the subscription term is month-to-month. You can cancel at any time. So if the free sample passes your first level filter, you can use the full set for research or backtesting for one month for a single month's fee.

Thanks
Josh

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.

Also Simon I agree with your statement regarding the data fees it does seem to get the 6 month out of sample data on a strategy you would need to spend $300 dollars on a strategy that may not even hold any water after it goes live. I have to believe that many other Quantopian users feel the same way. Maybe I will feel differently myself if my hobby starts to bring in serious money, but as of yet that hasn't happened. Yeah, for sure - at a certain level of revenue all these costs become relative. I'd love a Bloomberg too, and one day I'll probably treat myself, but not any time soon! Hi Guys, I have been trying to come up with a viable momentum-based algorithm for more than half a year, which is essentially my entire Quantopian "career", and have been unable to produce a decent algorithm that would stand a chance in the competition. Since I am really an amateur in this arena and a nobody that does not say much, but I would desperately like to know whether that means that everybody is essentially focusing on mean reversal and above all pair trading. Are these the only games in town? I know that it is a lot to ask of you to reveal your basic strategy, but I would greatly appreciate being able to avoid another fruitless half a year. You may say that it is not in Quantopian's interest for everybody to follow the same approach, of course, but I assume the ways of implementing pair trading are still very varied and independent of each other. Or is it perhaps that fundamentals can produce a competition-grade algorithm? Many thanks in advance, Tim The real problem here is that everyone is searching for the sort of return profile only achieved in real life by Bernie Madoff or those with inside advantages such as the HFT fraternity. Beta is bad, so called alpha is good. The reality is that beta is very probably all we have in the long term and alpha a fable. Quantopian understandably is in search of a magical solution to provide its hedge fund with super smoothe returns with low drawdown and little correlation to markets. Good luck. Many of the punters here are likely to be fooled by randomness. Particularly in view of the very short time scales over which they are running back tests. Quantopian won't want to hear me but they should perhaps take a look at what index providers are calling smart beta. A stock rotation strategy based on momentum can look very attractive compared to a traditional market cap weighted index. Capacity need not present an insurmountable problem. The sort of rainbow chasing performed here is likely to lead to the typical scenario seen so often before in the history of Trading and investment. Stellar returns for a period by sheer chance and the inevitable crash and burn which follows. Excuse my scepticism but the guys backing this outfit are HFT players who benefit from algorithms of an entirely different sort! My competition algo was a leveraged hedged ETF strategy. Next month I am personally going live with two strategies, if all goes well; one is a simple global asset allocation algorithm with naive risk parity, and the other is a tactical volatility ETF trading algorithm, again using a vola-weighting scheme. On my list to thoroughly investigate: • medium-term momentum (1-6 months) • short-term mean-reversion • pairs/basket trading To echo Anthony, I don't really think I am looking for alpha, just hoping that some tried and true professional strategies, applied to tiny stocks with which the professionals can't be bothered, will be enough to eventually bootstrap my algo trading business. There is sufficient empirical finance to suggest momentum (and mean reversion) have not been “arbitraged away.” But I, too, have had frustrating experiences with traditional momentum strategies …similar to those expressed by others in this thread. What has puzzled me is not so much whether momentum matters, moreover when does it matter and how much does it matter? Since credible trading signals are unknown ex ante, that is, cannot be accurately foreseen - I’m stuck in a state of wonder. I wish I had something more optimistic to say about momentum …but I would have to agree with Anthony: HFT algorithms calculate momentum much differently than cumulative raw return over months 􏰀t − 12 and 􏰀t − 2. Wishing you luck with your volatility work, which I continue to follow and admire. That seems like a just cause. Thank you all for your openness and very valuable advice and insights. There is so much I still need to learn. My real problem, I suppose, is that I am looking at various strategies too superficially and without enough preparatory (data) analysis, mainly going straight to back-testing. But hey, on the other hand, it is a hobby for me and as such it is supposed to be fun. : -) Just one more off-the-cuff remark when it comes to momentum indicators: I suppose what one is interested in is ultimately the "trend", i.e. some sort of a (smoothed) derivative of the price movement. Has anyone looked at Savitzky-Golay filters in this regard? Of course there is always the problem of the lagging of any sort of filter ... Spent the weekend researching this, still nothing to write home about. On individual stocks, the effect seems volatile and random, and on country ETFs, there's nothing there at all, that I could find anyway. Jim Simon's mentioned in passing that time-series momentum hasn't worked since the 80s - is everyone still publishing papers about something that basically hasn't worked in 30 years?? I still hold out hope that it works in futures, due (perhaps) to persistent carry/roll-yield. I might try and see if there's anything when applied to individual commodities futures ETPs, but their history is so short it might be futile. focus on broad market etfs across different asset classes using relative momentum along with an absolute momentum test and you will see very strong results over the last 10-15 years..not too sensitive to lookback period..can be 3-9 months. single stocks are so highly correlated and when they reverse its pain! Hmm okay I will give it a shot again, but I really haven't seen anything beyond the capm beta. Do you have any notebooks which demonstrate this? This simple, slightly modified Mebane Faber's Tactical Asset Allocation style strategy may be considered as a momentum strategy and as working. 140 Loading notebook preview... Try momentum on the top 200 to 300 US stocks by market cap or dollar turnover. As soon as I have Zipline working I'll publish something. It works beautifully for a greater return at less vol an DD than a conventional index. You will want one or two filters as per my website. Take a look at the DJTMNMO index Its simply the top 20% vs bottom 20% of Top 1000 stocks Does pretty well 80% of the time..but can have huge draw downs after bear markets end when shorts double .. Using Risk adjusted returns with multiple time frames and running a sector neutral strategy to rank helps.. But its still basically trading momentum on one asset class vs multiple strategies on multiple asset classes Commercial index providers and people like AQR who publish their methodology are a very good starting point. It is essential to download and read the full methodology document. In most cases they do not contain a simple filter or two which can greatly improve performance and in most cases the weighting is market cap weighting even in momentum indices. Which means the tilt towards a momentum factor is very small indeed. One exception is the Guggenheim equal weighted ETF which I think uses the S&P equal weighted 500 index. The problem if course is liquidity but this can be ameliorated in ways not usually used by the index providers. Is this beta or alpha? The concepts are a little silly really but people get very het up and didactic about it. What is "the market"? Why should you define the market as the performance of a particular index? If I create a better index is that how do you rank it? As against a market cap index such as the S&P 500? In which case I may have created a little alpha in that respect and so on. It's all a little arse about face. To use an old fashioned British term of art. Anthony could you expand on your statement above "One exception is the Guggenheim equal weighted ETF which I think uses the S&P equal weighted 500 index.". Also, as a total novice, have not AQR and others pretty well established that momentum EXISTS, and after all how long has the " trend is your friend" been around. This thread at some level confuses me. Most "momentum" indices out there don't achieve much since they are not equally weighted but market cap weighted.... Therefore they actually differ very little than their market cap weighted counterparts. This is a liquidity issue. You will find better results from equally weighting the top 300 stocks by momentum than if you market cap weighted those top 300. There is absolutely no doubt that momentum does exist. And always has done it would seem. The guys on this forum are mostly trying to cook up a low vol, low S&P correlated algo to satisfy the requirements of the Quantopian competition. Momentum trading is mostly hi vol hi DD although I have frequently pointed out ways to ameliorate this. Also, historically trading non stock instruments such as bond and commodity futures has been non correlated to stock markets. Momentum on a small group of individual stocks is a fools game. You need a big portfolio or ETFs. The focus here on Quantopian is highly probably chasing the end of the rainbow. Especially given the absurdly short back test periods most of these chaps look at. Hedge funds in general have not lived up to their promise of absolute return. Most rise and fall as their favoured methods come in and out of profitability. I think most of us, certainly myself included, have been fooled by randomness and some stage or another. In other words fooled into thinking we have discovered the philosophers stone only to realise it was luck. I think many people here are still looking for the stone. I have traded momentum for years. It works. But no one at Quantopian will be very impressed by the results. Their particular search is for Madof or HFT like returns and impossibly low drawdown. Good luck to them. They are presamably influenced by the success of their HFT backers. We are given to understand by Michael Lewis and others that hi frequency trading involves apparently legal "insider" trading - having prior knowledge of orders before the slow old dinosaurs not colocated at an exchange get a chance to deal. I have no idea whether this is true or not. But I do believe that Quantopians aims are unrealistic. They may as well stick to a high bond allocation and trade momentum with the balance. Bond like vol and DD will give bond like returns. Not trying to be rude. It's just that I have seen it all before so many, many times with so many, many hedge fund strategies which work well for a time and then go wonky. HFT[1] trading firms certainly trade momentum. Many algorithmic strategies monitor depth imbalances to anticipate price movement. The appearance of depth imbalance are tracked against the directions of mid-price jumps and then interpreted as short-term momentum occurrences. If the imbalances are large and/or volatile, they are considered stronger momentum signals and the machines engage in trend-chasing. Whether you call it order flow or transaction volume, (high volume / short delta t) is an indication of a directional auction. [1] EU regulations define HFT as positions held < 500 milliseconds. Frequency is not an industry issue; latency is. (viz. low-latency liquidity consumption) Yes, on those grounds my criticism of Quantopian's aim is probably unjustified. It's all about time scale and mean reversion and trending probably both exist and are not mutually exclusive. It is merely about timing. If I go long of a market which is upwardly directional and exit when it's starts to go down and reap profit I have benefitted from momentum in this timescale. If we were able to inspect infinite time series what would we discover? Brownian motion? No idea, and clearly the relatively short history of markets does not really entitle me to say that trends "exist". Trends can only be defined in terms of the timeline. To wax philosophical, perhaps in the long term nature itself is mean reverting or perhaps random. Human society certainly seems to be. Take empires and religions: they rise and then they fall. You may be able to profit from long or short positions on the rise and fall depending on your timing. We don't really know any of the answers. We can only stumble along in the dark and pick up what we can as we go along. The very existence of the human race may very probably prove transient, or mean reverting. As may the universe we inhabit. Trend following requires a method of deciding when to enter and exit a trade. My time scale is months, HFTs is milliseconds. My trends may be no more durable or reliable than shorter or longer timescales. My algorithms may be just as ephemeral but it will take me longer to find that out. Incidentally though, it would be interesting to look at the long term P&L of firms such as Getco or hedge funds such as Renaissance. Maybe their track records are not super smooth with very low drawdown. I seem to recall getting hold of the track record a few years back for the Medallion fund and being surprised at the volatility and drawdown. And then look at Knight capital. Perhaps it truly is a case of fooled by randomness. We have a profitable spell. Perhaps for a few years. And then our algorithms become unsuited to prevailing conditions and we fail to adapt. Back to randomness and or predictability and or determinism. Despite Bell, some such as David Deutsch claim true randomness does not exist. Stephen Hawking's claims that free will is an illusion. If we don't even know whether nature itself is random (and unpredictable) or deterministic (and hence in theory predictable) how can any of us make such bold statements about something so paltry and ultimately insignificant as financial markets. I should more accurately have said: "For the periods I have been trading and in the time frame I have been using, following tends using simple trend identifying techniques has made me a profit". Who knows? We can only live for the day. Carpe Diem. In the long term we are probably all wrong. So if a momentum effect is real, one would look at AAPL and say "Yeah, there must have been periods of momentum." So, how would one show that AAPL, as a specific example, was momentum-ish? In other words, I could apply my momentum meter and isolate the momentum factor from other factors, and then determine my momentum profit, exclusive of profits due to other factors affecting AAPL returns. Seems tricky, especially since unlike physics, I'm free to pick my own definition of momentum. So, I just end up deluded. No you would not look at AAPL. Not if you knew what was good for you. You would look at many thousands of instruments including stocks, mutual funds, commodities and any other trade-able you could get your hands on. And you would get histories going back as far as you could. Some data providers claim to have grain prices going back to ancient Babylon. Personally, I like to test on random samples out of the 33,000 mutual funds in my database. I have certainly designed and tested random data as well. You may then conclude that over time and a wide range of instruments applying a trend following strategy seems to work. Or perhaps not. Looking at one stock will tell you precisely nothing. Other than that, then yes, sure you can isolate momentum from any other factor, since net price movement results from a combination of all factors. Sure, define a trend anyway you want. There are thousands of ways and trends exist in every time scale. But if you take one particular time scale (you want your trade to last an hour, day, year or decade) you will find any method of deciding when to enter or exit a trade will tend to come up with very similar results. @Simon This research piece published on Friday, November 6. Here's an excerpt from the paper's introduction: "The existence of significantly positive excess returns from momentum strategies is well established in the literature. However, there is no consensus over what drives these returns. Finding a risk-based explanation for the momentum effects is a tremendously difficult task and momentum constitutes perhaps 'the toughest challenge for rational theories of the cross-section of stock returns'." I hope, if you get a chance to read it, that the full piece might contain something of value to you. http://www.priceactionlab.com/Blog/2015/11/trend-following/ This concurs with my basic experience trying to find trend-following systems; that said, I went live with one yesterday, which is decidedly mediocre, but which I believe is slightly better than completely random. I hold out hope that trend-following in futures will still work, provided that one focuses on those futures with high carry, and perhaps as interest rates rise, increasing the yield of the collateral balance. I like Michael's writing but I confess I am totally baffled. It's rather like the "flat earthers" denial. While human society prospers, technical advance will continue to ensure up and coming new companies. By following the fortunes of such companies as the rise and by ditching those which fall from grace you are likely to profit. That is the stock index for you. And that is trend following. In the long term nothing in the universe seems to last. Hence my comments about infinite time series. Perhaps stock markets in the very long term are mean reverting like empires or human life. Dust to dust, ashes to ashes. But even if that is the case, there has been plenty if time to benefit from the industrial revolution and hence rising stock prices. Trends have existed in stocks hence stock indices have gone up for a couple of hundred years. If we are about to enter an industrial, economic, social or political apocalypse then the game is over. If not, the you can continue to ride the wave, even if in the long term human society, hence markets, revert to the stone age or worse. Please excuse the rant but perhaps there are times when one simply has to play the historian. The problem on this forum really is short termism. It is like the mutual find industry where there is huge pressure to perform to prevent assets walking out of the door. Most here focus on single stocks and the very short term. I have been running tests on Quantopian today with a simple momentum rotation system switching monthly into the 300 best performers out of the top 3000 companies in the US by market cap. It shows stunning outperformance of the bench mark S&P 500 in both relative and absolute terms for a greatly reduced drawdown. Trouble is realism tends to lack on these forums and few are willing for the sort of returns which would please a pension fund. Most want to shoot the lights out and make incredible fortunes in record time. Sadly, fabulous returns usually don't last and if they do they are accompanied by huge drawdown. People endlessly say trend following is dead. So far they have been proved wrong. Ugh...terrible spelling.... Comes of typing messages on a mobile phone! Regarding futures, I wrote a series of articles on Tradersplace.net showing that trend efficiency has deteriorated over almost 40 years. Perhaps due to the huge influx of money onto the markets. I found no such decline in caah stocks. I have not traded futures since I got Corzined at MF Global and had to stop trading but I do not believe that TF is dead in the futures markets I have been paper trading a Bollinger band breakout for the last few years (I seem to recall publishing details on the now virtually defunct traders place) which has done surprisingly well over the past three years. Fine, JW Henry and Dunn were virtually put put of business along with many other much smaller CTAs but long term the Industry will survive. Or at least that is my belief. Also, to be honest I really think Michael is confusing the issue when he talks of asset allocation or timing systems perhaps continuing to work but NOT trend following. I am trading an asset allocation/ timing system at the moment. But tactical asset allocation and market timing is just trend following dressed up with a different name. Something I pointed out to Meb Faber on the Trading Blox forum many years ago. Simon, I'd wager that momentum in equities is a lost cause. Momentum in FX and futures however, may not be. I can't recall the book but it may have been something by Mandelbrot regarding the price movement of currencies as retaining more momentum than most other instruments. And if you examine many of the commodities you find that they also exhibit momentum much more strongly than stocks. Stocks are so fickle and seemingly manipulated. Futures and currencies have the entire world as a basis for their movements. http://www.followingthetrend.com/2014/04/trend-following-does-not-work-on-stocks/ This is similar, but maybe a little more hopeful. I was able to find something with a Sharpe around 0.4-0.5 doing long-only naive risk parity trend following on low cost asset class ETFs. I have started trading that one, since it's still better than how I invest with discretion (haha). I might try a long-only stock momentum strategy which uses a variety of other measures to try to avoid market downturns (breadth measures I expect), but it's still pretty bleak. I am glad you found results you like Anthony! Andreas Clenow - the author of the following the trend blog, has also discussed this view in his recent Stocks on the Move (self-pubished) book. I think he spends one chapter, with simulated examples supporting the view. The rest of the 275 page book is a step by step development of a "momentum" system applied to individual stocks in the SP 500. He shows significant outperformance of buy and hold. That is in large part because the system is in cash during the 2002/2003 and 2008 bear markets. Clearly Clenow sees a disitnction between "Trend Following", which buy definition includes the short side, and "momentum". A better title to his blog post would be "shorting stocks does not work". Simon, for my tests I nicked someone else's code and improved it: http://www.relativevalue.com.au/blog/momentum-take-2  I improved it as follows (taken from my website): Profit Taking A profit taking mechanism is employed to reduce volatility. On position entry I calculate a 10 ATR (average true range) profit target. I calculate the Average True Range over a 20 day period. I multiply the ATR by 10 and add it to the initial entry price: this is the first “target”. When reached, I sell 75% of the holding in that instrument and recalculate the profit target using the then latest closing price. I repeat until an exit signal is given by the normal “top 10” exit rule. True range for an instrument = (the maximum of the current high and the previous close) – (the minimum of the current low and the previous close). Average True Range = the average true range the look-back period (20 days in this case). Profit taking trades are permitted on any business day and are NOT restricted to reallocation days. Trade Filters Reject any trade where the momentum is negative. Reject any trade where efficiency is below the “Efficiency Limit”  I have used Trading Blox for years and have been a bit slow learning zipline/python etc. But I think eventually it will be a superb product and is worth the trouble to get to know. Ah, I see that Clenow has now wound up Tradersplace.net and re-directed it to his own website. Apologies. Its a pity he did not bother to consult me since we set up Tradersplace jointly and I put a great deal of hard work into it. There you go! Happily I happen to have saved a few of my "better" posts before he closed it down without bothering to consult me. I'll place a few of them at anthonyfjgarner.net over the coming weeks, especially the details of the Bollinger Band futures system which I improved with Kaufman's efficiency ratio and some unusual correlation filters. http://www.followingthetrend.com/2015/11/apparently-trend-following-just-died-again/ Clenow rebutting Mike Harris' post. Seems to be a hot topic! I'm sure I've submitted this primitive idea to the Q-Qroud before... however my Alzheimers is acting up. Markets are either ranging or running. And it is the timeframe context that tells you which behavior is in place. One of my favorite examples for this is step back and look at the DJIA over the last nearly 100 years. It's been on a pretty good run I'd say. So for the the 100 year timeframe we have a run. But now imagine (as hard as it might be) if for the next 100 years the DJIA headed back to nearly zero. Then for the 200 year time frame we would consider the DJIA to be in a ranging mode. In one periodicity the market is running and in another, it's ranging. So context for something like momentum is all based on which time frame you're looking at. A market might have momentum on the 5 minute chart, but it's just ranging on the hourly chart. How to use this information, as rudimentary as it is? Multiple time frames would seem a natural method. If a market is running at the weekly periodicity, running at the daily periodicity and has just now switched to running at the hourly periodicity -- all in the same direction -- then that three periodicity confirmation would seem to indicate it's time to get into that market. And so to complete this thought, using only the simple mindedness of which I'm capable, here's a momentum measurement trick: count the crossovers of a pair of moving averages. If you had say, a 5 and a 7 period set of moving averages, applied to weekly data, and over the a 52 week period that sinuous pair crossed over 20 times you say to yourself "ranging". Up and down went that market. Then, for the next 52 weeks, the same pair of moving averages crossover only 10 times... and the last time they crossed was 15 weeks ago, you'd say to yourself "running" -- it went directional. Use this technique then on three timeframes, measure the rolling count of moving average crosses, each timeframe window rolling independently, when all the counts were relatively low -- momentum. When all the counts were relatively high -- no momentum. The method is neolithic, but I've built systems that used it and seen success using it. And because I love dirt simple solutions, here's a way to interpret this technique. Image you're measuring this MACrossCount over 100 periods, we'll keep a rolling window looking back 100 periods. Now let's say our MA pair crossed over at period 20 (80 periods ago), period 30, period 50 and period 60 (40 periods ago) - four separate crossovers, no matter the direction: [80 + 70 + 50 + 40 / 4] = 60. 60 / 100 periods = 0.6 (the higher number the greater the probability of a run in place) That's a simple number to use to determine momentum. How about another set, from 70 periods ago to just 10 periods ago: [70 + 60 + 40 + 20 + 10] / 5 = 40 40 / 100 periods = 0.4 Maybe a simple interpretation would be a number greater than 0.5 is running and a number less than 0.5 is ranging? Do this for 3 time scales and you might have a pretty good, easy way to determine range vs run. I wasn't really able to find anything I liked using moving averages, to be honest. What I am trading now is a measure of momentum something like the number of period returns greater than 0, where period = 2-6 months. This is an indicator which ranges from 0 to 5, so you re-scale it or whatnot. Both of Andreas' books are great. The momentum one especially because it applies to stocks. I'd love to see his strategy coded up in Quantopian. It's relatively simple, but beyond my Python capabilities at this point, sadly. Graham @Graham, if you write the pseudo code then someone might pick it up and build it... So what's the answer? Is Simon now convinced that momentum exists by finding "incontrovertible evidence of the effect"? I'm still looking for stock momentum, I ordered Clenow's book. I did find something I am happy with for global asset class momentum, it's not great, but if the OOS sharpe stays in the 0.6 range I'll be happy. @Graham I did some work with Andreas over the summer, implementing the strategy from Stocks On the Move as best as possible on Q. I've been meaning to get a Pipeline version of it out the door, so stay tuned. The book is actually a pretty fun read, Andreas has a very blunt way of explaining things, and injects a fair bit of dry humor. One of my favorite lines from the book, and I'm paraphrasing, "There is a 20% chance Wednesday is the best day of the week to trade on...so let's trade on it." 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. I feel that momentum is not very pronounced in equities. Strong trends tend to be short lived and ready to reverse by the time I get in. Some solid trends do show up in commodities/FX still, but squeezes/reversals seem to have gotten nastier as everybody heads for the door at the same time. EUR/USD is great recent example, it has been in a strong down trend since mid October, but gave back a significant chunk of the gains in one day (Dec 3). Anybody who showed up late to that party probably had a bad week. Equities are cash flow instruments, so any momentum effect should be done on a dividend adjusted basis. Price trends don't mean much without knowing the expected cash flows from owning the stock. A stock with a large payout, but range-bound price may be more profitable/less risky than a trending stock with no payout. Some closed-end funds are good examples, Pimco's High Income Fund (PHK), has consistently paid its investors a 16%+ yield, but without much capital appreciation. A 16% yield is solid, so as long as the price base doesn't collapse and burn your equity this is an attractive investment. (Side note: PHK is trading at historically low premiums relative to its NAV due to rate hike mania). Maybe incorporating fundamentals and cash flows will help you find your momentum. The ideal momentum effect is in your own account, not necessarily what you're invested in. Here's a quick attempt at a 'volatility adjusted momentum' strategy loosely based on Andreas F. Clenow's book, Stocks On the Move. The definition of volatility adjusted momentum (M), as defined by Andreas, is simply the slope of the linear regression line from the log price multiplied by the correlation of determination between the log price and the linear regression line. The implemented strategy uses pipeline to trade 30 stocks with the highest M out of roughly 1200 stocks per month. Trade are entered when SPY close > SPY mavg(200), and exited when SPY close < SPY mavg(200). My backtest sort of shows the non-existence of momentum in equities, but then again, I did not 100% follow Andrea's strategy. Adding more fundamental filters or reverting back to hand selecting a pool of stocks will likely improve the strategy performance. The strategy will need to be optimized more, be prepared to run into some timeouts. 66 Loading... 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 from quantopian.algorithm import attach_pipeline, pipeline_output from quantopian.pipeline import Pipeline from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.factors import CustomFactor, SimpleMovingAverage from quantopian.pipeline.data import morningstar import pandas as pd import numpy as np from statsmodels import regression, stats import statsmodels.api as sm import scipy as sp # get slope and residuals from linear regression # http://stackoverflow.com/questions/14940948/ # using-pandas-ols-on-multiple-dependent-variables-at-once def _ols(y): x = pd.DataFrame(np.arange(0,y.shape[0])) x[1] = np.ones(x.shape[0]) tmpmat = np.dot(np.linalg.pinv(np.dot(x.T ,x)),x.T) betamatrix = np.dot(tmpmat,y) slope = betamatrix[0] resid = betamatrix[1] return slope,resid # get correlation coef # corrcoef = sqrt(1-ssres/sstot) where ssres=sum((y-f)**2) sstot=sum((y-m)**2) # https://en.wikipedia.org/wiki/Coefficient_of_determination def _corrcoef(y,s,r): l_arr = np.tile(range(y.shape[0]),[y.shape[1],1]).T s_arr = np.tile(s.T,[y.shape[0],1]) r_arr = np.tile(r.T,[y.shape[0],1]) f_arr = s_arr*l_arr+r_arr m_arr = np.tile(np.mean(y,axis=0),[y.shape[0],1]) ssres = np.sum((y-f_arr)**2,axis=0) sstot = np.sum((y-m_arr)**2,axis=0) rsqr = np.sqrt(1-ssres/sstot) return rsqr def volatility_adjusted_momentum(y): y = np.log(y) s, r = _ols(y) c = _corrcoef(y,s,r)**2 ann_ret = (1+s)**250 return c*ann_ret class VolatilityAdjustedMomentum(CustomFactor): inputs = [USEquityPricing.close] window_length = 200 def compute(self, today, assets, out, close): out[:] = volatility_adjusted_momentum(close) # dont get it... class AbsMaxPctChange(CustomFactor): inputs = [USEquityPricing.close] window_length = 90 def compute(self, today, assets, out, close): out[:] = np.abs(np.max(np.diff(np.log(close),axis=0),axis=0)) class ZScore(CustomFactor): inputs = [USEquityPricing.close] window_length = 200 def compute(self, today, assets, out, close): out[:] = (close[-1]-close.std(axis=0))/close.mean(axis=0) class AvgDailyDollarVolumeTraded(CustomFactor): inputs = [USEquityPricing.close, USEquityPricing.volume] window_length = 20 def compute(self, today, assets, out, close_price, volume): out[:] = np.mean(close_price * volume, axis=0) ########################## fname = 'zscore' long_num = 30 long_criteria = lambda x: np.logical_and(x['zscore'] > 0,x['momentum'] > 1) short_num = 0 short_criteria = lambda x: x['zscore'] < 0 ########################## # Put any initialization logic here. The context object will be passed to # the other methods in your algorithm. def initialize(context): set_commission(commission.PerShare(cost=0.005, min_trade_cost=1)) set_slippage(slippage.VolumeShareSlippage( volume_limit=0.25, price_impact=0.1)) pipe = Pipeline() pipe = attach_pipeline(pipe, name='factors') sma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200) dollar_volume = AvgDailyDollarVolumeTraded() # Screen out penny stocks and low liquidity securities. remove_penny_stocks = (sma_200 > 5) & (dollar_volume > 10**7) volatilityAdjustedMomentum = VolatilityAdjustedMomentum() zScore = ZScore() pipe.add(zScore.rank(mask=remove_penny_stocks), 'zscore') pipe.add(volatilityAdjustedMomentum.rank(mask=remove_penny_stocks), 'momentum') #ampc = AbsMaxPctChange() #pipe.add(ampc.rank(mask=remove_penny_stocks), 'ampc') context.spy = sid(8554) context.shorts = None context.longs = None context.safe = [sid(23921)] # TLT, treasury bond. schedule_function( rebalance, date_rules.month_start(days_offset=0), time_rules.market_open(minutes=1)) schedule_function( cancel_open_orders, date_rules.every_day(), time_rules.market_close()) # Compute final rank and assign long and short baskets. def before_trading_start(context, data): now = get_datetime('US/Eastern') # skip some days to speed up backtest. if now.date().day > 7: return results = pipeline_output('factors').dropna() ranks = results.rank().mean(axis=1).order() if ranks is not None: log.info('pool size: %r' % ranks.size) context.shorts = ranks[short_criteria(results)].head(short_num) context.shorts /= context.shorts.sum() context.longs = ranks[long_criteria(results)].tail(long_num) context.longs /= context.longs.sum() update_universe(context.longs.index | context.shorts.index) # Will be called on every trade event for the securities you specify. def handle_data(context, data): record(lever=context.account.leverage, exposure=context.account.net_leverage, num_pos=len(context.portfolio.positions), oo=len(get_open_orders())) def cancel_open_orders(context, data): for security in get_open_orders(): for order in get_open_orders(security): cancel_order(order) def rebalance(context, data): for security in context.shorts.index: if get_open_orders(security): continue if security in data: order_target_percent(security, -context.shorts[security]) if data[context.spy].close_price > data[context.spy].mavg(200): for security in context.longs.index: if get_open_orders(security): continue if security in data: print(security.symbol,context.longs[security]) order_target_percent(security, context.longs[security]) else: for sec in context.portfolio.positions: order_target_percent(sec,0.0) for safe in context.safe: if get_open_orders(safe): continue order_target_percent(safe,1.0/len(context.safe)) for security in context.portfolio.positions: if get_open_orders(security): continue if security in data: if security not in (context.longs.index | context.shorts.index): order_target_percent(security, 0) # https://www.quantopian.com/posts/pipeline-calculating-beta # https://www.quantopian.com/posts/long-short-pipeline-multi-factor # https://www.quantopian.com/posts/long-only-value-momentum-strategy-with-filter-first-algo There was a runtime error. I'll try to add my two cents to the discussion, but since I am a novice, please bear with me. :-) I think that it is fair to say that there is momentum present with the market as a whole and this is reflected in an index-based ETF, such as the SPY, simply because an index like the S&P 500 ultimately reflects the state of the entire economy and the economy has its ups and downs. Now, the SPY itself is a combination of individual stocks and therefore there must be some momentum in most of them. But the problem is that this momentum is very small compared to its uncertainty. Imagine a distribution of daily returns for a stock, accumulated over a certain period of time. The momentum, whichever way you define it, is linked to the average of this distribution (or perhaps its median). But the distribution also has its variance and the uncertainty of the average is just the standard deviation of the distribution divided by the square root of the number of days used for the construction of the distribution (the averaging time). Unfortunately, the variance of the distribution is huge compared to the average for stocks and the sampling period is necessarily limited. With an index you effectively do additional averaging and get a reduction in the uncertainty of the average (the momentum) by another factor of a square root of the number of stock that compose the index. This would imply that with the momentum strategy it is really difficult to "beat the market" -- except that one can simply stay long on an index most of the time and in addition by relatively simple means avoid the major downturns, at least to a certain extent, which can be significant. Hi all, I implemented Andreas' 50 day breakout strategy in a separate platform where I could access Forex and Futures data and integrated the returns with a simple Value/Momentum strategy I built in Q. Posted the results here. I thought it might be interesting to the folks following this discussion. In my opinion the most relevant point is that managed futures provide uncorrelated returns and when combined with other factor based strategies can smooth out overall returns. Also, the 50 day breakout strategy does quite well in the period after Clenow's book was published, does poorly in 2012, but has nice returns from 2013-2015. As far as I can tell Trend Following is alive and kicking. I thought this is relevant to this thread so I'll just post a link Nope hahaha I have actually come up with a couple momentum strategies which have killer returns (40%+ annualized from January 1st, 1999 until March 16th, 2016). However, there are a few caveats to that. First, the biggest returns happen with the smallest stocks, and thus work best for the smallest starting capital. Second, the commissions on the trades and the liquidity vs capital investment trade-off can ruin the returns entirely if you don't balance the dollar investments appropriately with both factors. Third, even these killer algorithms have their off-periods. The worst drawdown is around 36% in my backtesting. While I have working long and short versions of the strategy (which each individually post 40%+ annualized returns), combining them only increases the returns to 44% annualized and reduces drawdown to 32%. This "low" drawdown is assuming they are investing in uncorrelated assets with historically low beta. If I remove those constraints, drawdowns peak at 70% - 80%, and returns actually shrink. The other caveat with regard to Quantopian is that I use several factors which are not available on Quantopian, and I use a fairly sophisticated ranking system. I implemented a similar ranking system on Quantopian, along with most of the factors I need to implement the algorithm here, but I have not been able to match the performance I obtain with my original algorithms on the other system I use. And, the final caveat is that weekly drawdowns are often in the 5% - 12% range 1 - 3 times every two weeks. It is very hard to grit your teeth and hang on when you see your returns diminish so much so often. It's a crazy roller coaster ride. But, while it does bounce around a lot, it very often gets several week runs with 10% returns each week. The overall win rate on the trades is 73% on the short trader and 68% on the long trader. The long trader can only handle capital up to about$200k before it flatlines. The short trader can handle up to about $800k before it flatlines. Beyond that, you get much better performance from other strategies. The main thing these algorithms use is actually overzealous buying and selling. They trade the reversals. Basically, you take a stock which has been going up or down on momentum, and then they hit this "overzealous" period where the volume suddenly increases and the stock moves sharply in the same direction it has been going. Typically, the move is an overreaction, so I trade the correction. Thus, it doesn't really make money off momentum in the sense that you follow the momentum - you trade the opposite when you notice an overzealous movement. But it really only works on assets exhibiting momentum based movements. May be this piece from Clifford Asness of AQR would help to shed some light to an otherwise murky topic. He differentiates trend following from momentum. A very critical point at that. Trend following is essentially beta bet. After all, stocks rise and fall in different degree with the market as CAPM has taught us. Momentum as it is defined in this publication is ranked based, excuse my crude paraphrase, and dollar neutral if not exactly beta neutral. Sorry, I have not done enough home work to be able to tell whether it is beta neutral. It is basically the building block of a long-short hedged strategy. Fact, Fiction and Momentum Investing You might find this interesting...with ETF's you could probably get at most of the asset classes. Worlds longest backtest (and it's about momentum) Has anyone done Fabers GTAA 13 Agg 6? Where you invest evenly in the top 6 asset classes @Eliot did you check the default commission settings of Q? It defaults to max 25% of the minute bar volume which creates a huge slippage and might cause your algo to prematurely flatline. I recommend you change the volume limit to 2.5% (which is the new default in Quantopian 2 Test Drive). @mikko I also really liked the crisis alpha book: http://www.amazon.co.uk/Trend-Following-Managed-Futures-Trading/dp/1118890973 @anthony some have pointed out the cliff assness paper drives a lot of its return from the way it weights assets according to risk (ie diversified risk parity where risk = volatility). from my personal trading experience if you are looking for momentum you are really just following the tape and swing trading. Pay attention to Dojis and news of the moment. (my twitter feed is always open) RSI levels and MACD also really help along the 5 minute chart. again if you are looking at momentum then please ignore fundamentals, they can be used as catalysts however they are not a variable as much as a coefficient. It is simply shortening down the time frame and taking each day as a year in it of itself. Flip flopping thru momentum is great. If you wish to stretch out your time frame then it becomes INVESTING and thus 200-day moving averages are good guidlines. Simon, I think you must be doing something wrong in your code or the indicator you're using is not being used in a creative way. You must think like a portfolio manager, someone whose life depends on making this thing make money. You wouldn't just apply an indicator blithly. You take the idea and you twist the shit out of it until you're convinced that it is now unique; it's your creation, and there aren't 1000 other guys already doing that such that FatLeftInTheTrade=0. Though I trade futures I'd be astonished if stocks didn't have real momentum like I've found. Indeed, in my mind, momentum is the basic thesis of how markets operate. Anyway, good luck. Thanks for the advice. FWIW momentum is quite easy to find in futures, perhaps that it why it works for you. In stocks, the topic of this thread, I had a harder time finding anything I would trade. HI all, I'm new here, but came across this thread and wanted to share some results on the Q500 using the t12 to t2 type momentum (excluding most recent month) and share that in this most basic sense it just doesn't appear to exist over the equity and time sample. (Most of you have probably already done this, but anyhow I thought it was worth confirming and might be interesting to somebody starting like me...) Wes Gray did a post about this on alpha architect, that there are long periods of time where momentum has stopped working. Doesn't mean it's dead, but.. http://blog.alphaarchitect.com/2016/09/07/is-momentum-investing-dead-or-is-it-just-painful/#gs.LPGB1t8 Anyhow I ran some basic "long only" momentum on the Q500, from June 1 2004 to through April 28 2017 using equal weighted positions rebalanced monthly. I compared to Guggenheims RSP equal weighted SP500 index due to equal weighting of our buys. Start date of June 1 2004 selected because it looks like RSP didn't exist for much longer than a year before that. I'm pretty sure I turned off all commissions and slippage for test to remove that effect, but you can check my code as I modified one of tutorial files and am still learning. I think it's right, but I could've messed something up. The momentum calc used is not perfect, but should serve as proxy - calculated a 252 day return less the 20 day return. mo252 = Returns(inputs=[USEquityPricing.close],window_length = 252,mask=base_universe) mo20 = Returns(inputs=[USEquityPricing.close],window_length = 20,mask=base_universe) wtdmo = mo252 - mo20  Anyhow - for the full time period here are some summary stats RSP benchmark: up 207.2% Q500 up 185.4% Top 30% of t12 to t2 Q500 momentum up 153.2% (percentile 70 to 100) --- This is the backtest shown Bottom 30% of t12 to t2 Q500 momentum up 139.3% (percentile 0 to 30) Middle 40% of t12 to t2 Q500 momentum up 224.8% (percentile 30 to 70) So really, not much in the way of momentum showing up. I couldn't figure out how to post more than one backtest, but the attached is for the Top30% of momentum. 19 Loading... 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 #conclusion from quantopian.pipeline import Pipeline from quantopian.algorithm import attach_pipeline, pipeline_output from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.factors import SimpleMovingAverage, Returns from quantopian.pipeline.filters.morningstar import Q500US def initialize(context): #set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1)) #set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1)) set_benchmark(sid(24744)) #this is RSP set_commission(commission.PerShare(cost=0.0000, min_trade_cost=0)) set_slippage(slippage.VolumeShareSlippage(volume_limit=0.1, price_impact=0.00)) context.aapl = symbol('RSP') # Schedule our rebalance function to run at the start of each week. schedule_function(my_rebalance, date_rules.month_start(), time_rules.market_open(hours=0,minutes=5)) # Record variables at the end of each day. schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close()) # Create our pipeline and attach it to our algorithm. my_pipe = make_pipeline() #my_pipe #can't figure out how to print my_pipe in IDE attach_pipeline(my_pipe, 'my_pipeline') def make_pipeline(): """ Create our pipeline. """ # Base universe set to the Q1500US. base_universe = Q500US() # 10-day close price average. #mean_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10, mask=base_universe) # 30-day close price average. #mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30, mask=base_universe) #look at momentum #mo200 = Returns(inputs=[USEquityPricing.close],window_length = 200,mask=base_universe) mo252 = Returns(inputs=[USEquityPricing.close],window_length = 252,mask=base_universe) #mo250 = Returns(inputs=[USEquityPricing.close],window_length = 250,mask=base_universe) #mo158 = Returns(inputs=[USEquityPricing.close],window_length = 158,mask=base_universe) #mo100 = Returns(inputs=[USEquityPricing.close],window_length = 100,mask=base_universe) mo20 = Returns(inputs=[USEquityPricing.close],window_length = 20,mask=base_universe) #wtdmo= mo250/250.0+mo158/158.0+mo100/100.0 wtdmo = mo252 - mo20 #strongest_mo = wtdmo.top(100) #strong_pullbacks = strongest_mo.bottom(25) #should be recent weakest of the long term strongest - doesnt' work #weakest_mo = wtdmo.bottom(100) #weakest_surge = weakest_mo.top(25) #should be recent strongest of the long term weakest - doesn't work #percent_difference = (mean_10 - mean_30) / mean_30 # Filter to select securities to short. #shorts = percent_difference.top(25) #shorts = wtdmo.percentile_between(3,6) shorts = wtdmo.bottom(1) #shorts = wtdmo.percentile_between(0,49) #shorts = weakest_surge # Filter to select securities to long. #longs = percent_difference.bottom(25) longs = wtdmo.percentile_between(70,100) #longs = wtdmo.top(1) #longs = wtdmo.top(50) #longs = strong_pullbacks # Filter for all securities that we want to trade. #$securities_to_trade = (shorts | longs)
securities_to_trade = longs

return Pipeline(
columns={
'longs': longs,
'shorts': shorts
},
screen=(securities_to_trade),
)

def my_compute_weights(context):
"""
Compute ordering weights.
"""
# Compute even target weights for our long positions and short positions.
long_weight = 1.000 / len(context.longs)
#short_weight = -0.5 / len(context.shorts)
short_weight = 0

return long_weight, short_weight

def before_trading_start(context, data):
# Gets our pipeline output every day.
context.output = pipeline_output('my_pipeline')

# Go long in securities for which the 'longs' value is True.
context.longs = context.output[context.output['longs']].index.tolist()

# Go short in securities for which the 'shorts' value is True.
context.shorts = context.output[context.output['shorts']].index.tolist()

context.long_weight, context.short_weight = my_compute_weights(context)

def my_rebalance(context, data):
"""
Rebalance weekly.
"""
for security in context.portfolio.positions:
if security not in context.longs and security not in context.shorts and data.can_trade(security):
order_target_percent(security, 0)

for security in context.longs:
if data.can_trade(security):
order_target_percent(security, context.long_weight)

for security in context.shorts:
if data.can_trade(security):
order_target_percent(security, context.short_weight)

def my_record_vars(context, data):
"""
Record variables at the end of each day.
"""
longs = shorts = 0
for position in context.portfolio.positions.itervalues():
if position.amount > 0:
longs += 1
elif position.amount < 0:
shorts += 1

# Record our variables.
record(leverage=context.account.leverage, long_count=longs, short_count=shorts)

There was a runtime error.

Take this with a large grain of salt, as I haven't done any studies myself, and this is based off of what I've heard from other quants. Momentum is a purely price-based factor. Pricing is the single biggest over-mined data set in finance, as it's given out in nearly every platform and everybody knows about it. Momentum is also the single easiest conceptual strategy and many people trade on it without even being quants. The effect may remain in some cases, as it's a self-reinforcing effect. If others are trading momentum, then everybody will make money until the market goes down or some other exogenous shock occurs. Some typical quant momentum factors you can try are defined here: https://github.com/quantopian/algorithm-component-library/tree/master/factors_project

With any price-based factor, trading can be pretty unreliable. In general I think that these days if you're going for alpha, you need to be a bit more sophisticated. I would try using other data sets such as sentiment or such to first filter the universe into sets where momentum will be more or less prevalent and then try momentum on those sets. This is just an idea but I think it gets at the notion of what type of multi-factor interaction models are at the forefront of modern quant research. https://www.quantopian.com/data

The current drought in momentum (as typically defined in academics) is interesting to me because it's a component of my current methodology, and one thing I've noticed is some of my biggest investment mistakes have been when I ignored negative momentum and added to a losing position. At least for the subset of companies that I've historically screened and purchased, considering negative momentum is something that would've saved me money. But I have value investing tendencies that I have to control for - that when something gets cheaper it's not always a better deal.

Paul Tudor Jones' quote "Losers average losers" works for me (at least I think it helps). I've come to accept that for the universe of stocks I'm attracted to based on other fundamentals, if I try add to losing positions - more often than not it doesn't end well. I'm using e a combination of value, momentum, quality, and growth (real growth, not expensive) factors based on research I've been able to read - but I'm hoping to model some of these things in Quantopian to investigate better for myself.