PyInvesting

Helping investors beat the market.


Ivann Fok
9 months, 3 weeks ago · 7193 Views

WRITTEN BY

Ivann Fok

Ivan is the founder of PyInvesting.com. He is passionate about technology and finance and has worked as a software developer at a hedge fund where he was responsible for building the fund's trading system. He hopes that PyInvesting will help investors adopt a data driven approach to investing and support them in their journey towards financial freedom.


Ivann Fok · 5 months, 3 weeks ago
Investing in Top Growth Stocks with Huge Disruptive Potential
Growth investing has been extremely profitable with growth funds such as Cathie Wood’s ARK Innovation ETF (ARKK) surging over 200% over the last year. The performance of growth funds have been attributed to disruptive growth stocks that are able to take advantage of opportunities from record-breaking technological changes. These companies have the potential to change their industry’s landscape by creating simplicity and accessibility while driving down costs with their technologically enabled product or service. The current pull back we are seeing in the market presents an attractive buying opportunity for long term investors looking to gain exposure to these disruptive growth stocks. Today, we will explore the characteristics of growth stocks and discuss how we can identify top growth stocks that are revolutionizing their industry. What is a growth stock? Growth stocks are companies that increase both their revenue and earnings at a faster rate than most stocks in their industry. These companies are able to generate exponential growth by developing an innovative product or service that is able to gain market share from its competitors or creating entirely new industries. These high growth stocks are rewarded by the market, delivering huge returns to shareholders in the process. The faster their growth, the bigger their returns. In contrast with value stocks, high growth stocks are relatively more expensive with higher price to earnings ratio (P/E Ratio) and price to sales ratio (P/S Ratio). However, even though growth stocks are expensive relative to the current earnings, the best growth stocks can still provide huge returns to investors when they realise their growth potential. How do we find growth stocks? With thousands of stocks to choose from, how do we identify the best growth stocks to invest in 2021? We can use a screening tool, to scan thousands of stocks in the market and filter stocks with strong revenue growth. Using this list of fastest growing stocks today, we run a fundamentals backtest to further select the top growth stocks for our portfolio. Finally, qualitative investors may also further enhance the selection of growth stocks using fundamental analysis. Screening for our universe of growth stocks Head over to the screening tool where we will be screening for our investment universe of growth stocks. In our screen, we will be filtering for: Stocks in the US market Stocks that are mid cap sized and above Stocks with a revenue growth greater than 20% In the Region field, select US Stock. Under Market Cap, check the mega cap, large cap and mid cap check boxes. Click on Add another filter and select revenue growth. A new revenue growth field will appear where we will select stocks with a revenue growth greater than 20%. Finally, click on the blue button to find your stocks. This will generate a list of over 500 stocks that pass our screening criteria. In the list we can see stocks such as Apple that had a revenue growth of 21.4% in the last year. Click on the button to create a backtest with screen results. You will see a pop up with the option to create a backtest using your screen results. We are going to select the top 250 stocks from our screen results with the highest revenue growth to run a fundamentals backtest. Once you have selected these parameters in the dropdown menus, click on the blue button to create your fundamentals backtest. Backtesting our growth investing strategy You will be directed to the fundamentals backtest page, where the investment universe has been pre-populated with the 250 stocks from our screen with the highest revenue growth. Scroll down to the next section, where we will select the signals for our fundamentals backtest to build our portfolio of top growth stocks. We are going to select 3 signals to rank our stocks - revenue growth, profit growth and price to sales ratio (P/S ratio). Besides, using growth metrics such as revenue growth and profit growth to select the fastest growing companies, we also want to look at valuation to ensure that our stocks are not excessively overvalued relative to their sales. We use the price to sales ratio instead of the price to earnings ratio (P/E ratio) because a number of these growth companies are not profitable yet. They are spending a lot of money on areas such as marketing to increase their growth. Because their earnings are negative, their P/E ratio is not defined. Hence we use the price to sales ratio to gauge the company’s valuation relative to their sales. We want companies with the lowest price to sales ratio because they are cheap relative to their sales with strong upside potential. These signals are normalized such that they are comparable with each other and assigned a weight of 33% each where we equal weight each of these signals. These signals are combined together to form our overall signal used to rank all 250 stocks in our investment universe allowing us to select the best growth stocks for our portfolio. Next, select the number of stocks to include in your portfolio. We are going to select 30 stocks in our portfolio where each stock is equally weighted at 3.3%. This is to ensure that our portfolio is diversified with low concentration risk. We are not gambling on a single stock going up big. Instead, we are betting that growth stocks on average are able to outperform the market. Our rebalance frequency will be set to a monthly frequency to prevent excessive trading and reduce transaction cost. Every month, 250 stocks will be ranked using the signals we selected (profit growth, revenue growth and price to sales ratio) and the top 30 stocks will be selected to form our portfolio. Finally hit the run backtest button to run your growth investing strategy. The strategy has an annualized return of 32%, a volatility of 25% and a max drawdown of 39%. Comparing the strategy against Cathie Wood’s ARK Innovation ETF (ARKK), we can see that there is significant correlation in their performance. This is due to similar exposure to growth stocks between the 2 strategies. While ARKK has a higher annualized return of 34%, our strategy has a higher risk adjusted return reflected from its higher Sharpe ratio (1.08 vs 0.99). Scrolling down, you will see a list of stocks in the strategy’s current portfolio and the weight of each stock in the portfolio. These are the top growth stocks selected by the model based on the signals we chose for our growth investing strategy. For quantitative investors who prefer relying on a fully systematic strategy without any human intervention, you can choose to invest in all 30 stocks from your backtest portfolio. Fundamental analysis of growth stocks Qualitative investors who prefer looking at the business model and growth potential of a stock can do additional fundamental analysis to further narrow down this list of 30 stocks down to 15 to 20 stocks. One possible way to analyze these stocks is to find stocks that are best positioned to profit from strong market trends. Companies that are able to take advantage of these trends can exponentially grow their profits, generating huge returns for investors. For example, one of the stocks selected by our model was Fiverr. Fiverr is a global online marketplace for freelancers in creative industries. Freelancers provide a wide number of services such as developing a new website, creating a new logo, editing a video and writing for blogs. With the huge tailwinds due to the work from home trend and the gig economy expected to grow to $100b in the US market, Fiverr’s revenue growth has been accelerating to over 80% year over year. Another method of analyzing stocks would be to search for companies with strong economic moats that can maintain their competitive advantage and protect their profits and market share from their competitors. A great example of such a company selected by the model is CrowdStrike. CrowdStrike is a growth leader in cyber security with a disruptive business model in endpoint security. CrowdStrike uses artificial intelligence to learn from previous cyber attacks, allowing its platform to adapt and provide robust cybersecurity solutions. The company’s superior technology is a strong economic moat that creates an effective barrier against its competitors, preventing them from seizing their market share. Conclusion Investing in growth stocks can be extremely profitable for long term investors looking to participate in the exponential growth of disruptive companies. We discussed how to build a portfolio of top growth stocks using a screening tool and a fundamentals backtest. We also looked at how qualitative investors can further narrow the stock selection using fundamental analysis. We hope that you will be able to use this stock selection method to profit from growth investing. Happy investing, and may the odds be in your favor.
Ivann Fok · 6 months, 2 weeks ago
The World Beyond Investing
This article is contributed by Chengkok from Wealthdojo Face it, finance without investing would be boring. The ups and downs, the highs and lows that keep you hanging at the edge of your seat. In your journey through investing, you probably would have met fellow investors, gurus or even con-artist. Some of you who are here might be new, some of you might have invested for years. One question which I like to present to every one of you is this. What is the bigger picture? Sure. The objective of investing is to make money. However, looking at finance just concentrating on investing is like trying to defeat a high-level boss monster with a magician that only has high MP (Magic Points) and low HP (Health Points). Hi, I’m Chengkok from Wealthdojo. In my journey in financial planning, I have met people who are overly focused on their investing that they missed out the bigger picture. Like them, I have missed out on the bigger picture before and hope that many of you will not have to go through my mistake. To make it easier for you, I have summarized the big picture through the 6 Levels Wealth Karate Strategy. We will only be talking about 3 Levels today. #1 Abundant Surplus Creator Some of the investors I met live simply ridiculous lifestyles. I love their optimism but it would take less than a few years before they burn through everything they are building. Because of their optimism in the market, some of them whom I met are spending through their future income. What it means is that these are people with excessive debts on their spending. The fastest way to fail is to live a lavish lifestyle before you can even afford it. This might sound very basic and I thought it was uncommon until I met many graduates who were living from paycheck to paycheck. In my other blog post, I wrote about my experience with a lady who spend $800+ on a pair of slippers but she stopped wearing it because she’s afraid the slippers will be exposed to the rain. (insert link) Simply ridiculous. #2 Aegis Of War A strong investment portfolio is a strong offense in their finance portfolio. Just like a mage with low HP with high MP, they may be a paper hero who can be defeated in one hit. Some investors I have met have zero or outdated defense in their finance portfolio. Medical and insurance cost has risen over the years. Someone who had their defense planned 3 to 5 years ago might not have enough protection to tide over their crisis at that time. With the new changes in the IP riders, co-payment has become a new norm. That is just the start. With the sedentary lifestyle that we are living nowadays, it is also no secret that the rates of critical illness have been raising over the years. The next personal war that we will be fighting will be medical one. The medical war will be one that is going to cost significantly. This is one financial hedge that we cannot ignore. #3 The Superfund Income You guys are at the right place. I met many who do not have a gameplan in their investment journey. If you invest with a well thought out investment gameplan, this usually produce a much better result as you will be calmer and more composed as compared to those who are speculating the market. Here at PyInvesting, they specialize in using backtesting as their gameplan in their investing journey. Using a backtest is one way to find profitable strategies. I strongly encourage you guys to consider if this backtest method is suitable for you. Final Thoughts From Wealthdojo The world beyond investing is creating an all-rounder finance portfolio that can take care of you in every aspect. Some of which are habits you can adopt, some of them are mindsets and many others your decision to start today. Hope that I can be part of your journey as well. Wishing you all the best in your finance journey. To keep in touch, join my Telegram Channel for a tip a day! In Wealthdojo, we dedicate a small amount of time daily for learning new things. Continuous learning is one of the greatest secrets of success.
Ivann Fok · 7 months, 1 week ago
GameStop has surged over 1500% in 2021. Should you chase the stock going forward?
By now, you’ve probably heard of GameStop $GME, the hottest stock in the market right now. We know that many people are betting against $GME and shorting the stock. Don’t take it from us – Bloomberg reported that while Gamestop’s shares outstanding stands at 69.7 million, short interest is at 71.2 million shares. As part of preliminary fundamental analysis, let’s look into the business model of GameStop. And in terms of a Q3 2020 update, Gamestop’s net sales were $1,004.7 million, down 30.2% from the fiscal 2019 third quarter reflecting: The impact of operating during the last few months of the seven-year-long current generation console cycle and the subsequent limited availability of hardware and accessories; The unplanned shift of software titles later into the fourth fiscal quarter, and in some cases, into fiscal 2021; An 11% reduction in the store base, as part of the Company’s de-densification strategy, partially offset by recaptured sales through the transfer to neighboring locations and online However, did you know that this video game retailer hasn’t made a profit in two years? Considering Gamestop’s last annual report, Gamestop posted an operating loss of $399.6 million in FY ended 1st Feb 2020, and an operating loss of $702m in FY ended 1st Feb 2019. This is a stark shift compared to FY ended 1st Feb 2018, where they posted a net earnings of $439.2 million. As a physical retailer in a world where gamers download games online, the future of this business was not looking great. Gamestop’s CEO, George Sherman, addressed this point in their annual shareholder’s letter, stating the firm’s strategy as an omni-channel one with a ‘Buy Online Pick Up in Stores’ approach. However, considering the last two year’s financial performance, it remains to be seen if their shift from offline to online will pay off and turn the company’s finances around. Despite the gloomy outlook, the stock has surged over a whopping 1500% in January 2021 alone fueled by an army of rookie day traders from Reddit’s WallStreetBets forum. It first started with now famed Reddit User ‘Roaring Kitty’ (34 year old Keith Gill) who first posted a picture of his US$53,000 investment in Gamestop, reportedly an investment made in 2019 when Gamestop was at $5 a share. While that post alone did not attract much attention from the community aside from comments on lack of conviction in Gamestop’s share price rise, those comments spurred Keith Gill to continue to make more videos on popular social media channels such as Youtube and Tikok on Gamestop. This saw the start of the flood of retail money into Gamestop, with Keith Gill and Reddit user DeepF***ingValue being the first drivers spurring the community which collectively bought heavily shorted stocks such as GameStop. As we know, this eventually pushed share prices higher and squeezed out hedge funds like Melvin Capital and Citron, forcing them to close out their short positions in GameStop at a huge loss. The big question now is whether investors should continue chasing the stock or sit this one out on the sidelines. To answer this question, we looked at 3 technical indicators (Bollinger Band, MACD and RSI) to decide whether to participate in GameStop’s massive rally. #1 Bollinger Bands Bollinger Bands are the blue bands in the price chart below covering a standard deviation level above and below a simple moving average of the price. As the width of the bands reflect the standard deviation of the stock’s price, they become wider during periods when the stock is more volatile. At its current price of $325, GameStop is trading around 18% above its upper band implying that the stock is extremely overbought in the short term. As a result, the risk of a pull back in the short term is very high, making it a bad entry point for investors and traders. The middle band (yellow line) which is the simple moving average of the stock, is typically used as a support level. When the stock breaks below its support level, it indicates that the stock is no longer in an uptrend and would be a signal to sell the stock. If we assume a stop loss at this support level of $80 where traders will exit their positions, the risk of a GameStop trade is $80 / $325 - 1 = -75% which is extremely high. Given the high risk of this trade, investors would be better off finding other stocks with better trading setups and risk reward ratios. #2 MACD The MACD or Moving Average Convergence Divergence is a trend following momentum indicator that reflects the speed of a stock’s price. If it’s positive, the stock is trending upwards and if it’s negative, the stock is trending downwards. The larger the MACD’s value, the faster the speed. For those interested in the math behind the MACD, the indicator is calculated by subtracting the 26 day exponential moving average (EMA) from the 12 day EMA. GameStop’s MACD (blue line) has been taking off like a rocket since December last year. What this means from a technical standpoint is that the stock is accelerating where it is increasing its velocity over time. To the newbie investor, this could seem like a great opportunity. “Yes! Let’s get on this rocket as it takes off to the moon!”. But wait a second, let’s take a closer look at the MACD before the stock took off in December last year. Throughout the stock’s entire history since 2015, the MACD for GameStop has never come close to a value of 5. And in slightly over a month it shoots up to 57, implying the speed went up over 10X in a short period of time. This implies that the stock is extremely overheated in the short term and is unlikely to be able to sustain the same velocity going forward especially when WallStreetBets gets bored of GameStop and finds another stock to pump. #3 Relative Strength Index (RSI) The relative strength index (RSI) measures the magnitude of recent price changes to evaluate whether a stock is overbought or oversold. The RSI is displayed as an oscillator and can have a reading from 0 to 100. A stock is considered overbought when the RSI is above 70% and oversold when it is below 30%. GameStop’s RSI is currently at 83% implying that the stock is extremely overbought in the short term. As the stock is expensive based on the RSI indicator, investors would be better off waiting for the RSI to pull back to be able to get a better entry point. Conclusion Our 3 technical indicators show that GameStop is extremely overbought in the short term and buying the stock now is very risky with a potential downside of -75%. The prudent thing to do is to stay away from GameStop instead of chasing the stock at these insane price levels just because all the Redditors on WallStreetBets are talking about it. If you enjoyed this article and would like to create your own investment strategy on the cloud, I invite you to check out PyInvesting’s new beginners backtest where we will guide you through an example and help you understand how the website works. I hope that PyInvesting helps you in your journey towards financial freedom. Happy investing, and may the odds be in your favor. This joint post was done in collaboration with MissFITFI, a financial blogger who started her personal finance journey ten years ago, whilst building her career in the technology investments space.
Ivann Fok · 8 months, 2 weeks ago
3 Powerful ETF Investing Strategies for Conservative Investors
One of the key benefits of ETF investing is allowing investors to have exposure to multiple asset classes such as stocks, bonds, real estate and commodities. By placing uncorrelated bets across different asset classes, investors are able to reduce risk and increase the risk adjusted returns. Another advantage of ETF investing is that it is extremely simple to implement. We only need to manage between 2 to 5 ETFs as compared to pure equity investors that typically hold around 20 to 30 stocks. Because of the convenience of ETF investing, it can be implemented easily on your own using a discount broker such as Interactive Brokers which can save you almost 1% per year on advisory fees.  In this article, I’m going to discuss 3 powerful ETF investing strategies for conservative investors that can outperform the S&P 500.  Strategy 1: 60/40 Portfolio The 60/40 portfolio is a well known investing recommendation where the investor allocates 60% of their portfolio to large cap stocks and 40% to treasuries or investment grade bonds.  This investment strategy is often misunderstood by most people. The common impression is that since the portfolio has such a high percentage of bonds, which are considered low risk assets, the overall portfolio returns are going to be significantly worse than a buy and hold strategy on a 100% equity portfolio. Is that actually what happens?  To find out, I ran a strategic allocation backtest where I allocated 60% of the portfolio weight to SPY (S&P 500 ETF) and 40% of the portfolio weight to TLT (Treasuries ETF). I specified a 10% rebalance band where if the actual weights of the portfolio deviated from the 60/40 target allocation by more than 10% due to price movements, the algorithm would rebalance the portfolio back to its original target weights. The results are surprising. Despite having such a large percentage of bonds in the portfolio, the 60/40 portfolio’s total return is almost the same as a buy and hold strategy on the S&P 500!  Taking a look at the statistics, while the annualized returns between the 60/40 portfolio and the S&P 500 are very close at 9.3% vs 9.5%, the 60/40 portfolio has a much lower risk with a volatility of 10.4% and a max drawdown of 31.2%.  The key reason why the 60/40 portfolio performs well is due to rebalancing. Rebalancing is the process of realigning the weights of stocks and bonds in the portfolio back to their target weights of 60% stocks and 40% bonds. Rebalance needs to be done because over time, the prices of stocks and bonds change, causing their weights to drift away from the 60/40 target allocation.  For example, during the 2008 global financial crisis, the value of stocks fell while the value of bonds increased. This was because investors rotated from risky assets such as stocks into safe assets such as bonds to protect their portfolios. If you were holding a 60/40 portfolio previously, the portfolio’s stock weightage would fall below 60% while its bond weightage would increase above 40% due to the price movements. To rebalance your portfolio back to the 60/40 target allocation, you would need to sell some of your bonds which have gone up in value and buy more stocks which have fallen in value. This process of taking profit on your bonds to buy stocks when they are cheap tends to improve your portfolio’s performance in the long run.  For conservative investors, the 60/40 portfolio done with ETF investing is an attractive option because we can achieve similar expected returns as a buy and hold strategy on the S&P 500 with almost half the level of risk.  Strategy 2: Bogleheads Three-Fund Portfolio The Bogleheads three-fund portfolio is a simple and diversified portfolio consisting of 3 asset classes: Domestic Index Fund International Index Fund Bond Fund Also known as a lazy portfolio, the three-fund portfolio is designed to perform well in most market conditions. This portfolio can be implemented with 3 low-cost ETFs and can be rebalanced easily without the hassle of trading numerous instruments.  To implement the three-fund portfolio, I use the following ETFs: SPDR S&P 500 Index (SPY) as the domestic index fund iShares MSCI ACWI ETF (ACWI) as the international index fund iShares 20+ Year Treasury Bond ETF (TLT) as the bond fund I assigned equal weights to each of these ETFs at 33% each and ran a backtest to compare the strategy’s performance against the S&P 500.  At an initial glance, the three-fund portfolio seems to perform worse than a buy and hold strategy on the S&P 500. Looking at the statistics, the three-fund portfolio has a lower annualized return of  8.7% vs the S&P 500 which does 10%. However, the three-fund portfolio’s risk is significantly lower with a volatility of 12.3% vs 20.6% and a max drawdown of -35.7% vs -51.5% for the S&P 500. To compare the performance between these 2 strategies, we can look at the Sharpe ratio, which is a measure of risk adjusted returns. The three-fund portfolio has a Sharpe of 0.47 while the S&P 500 has a Sharpe of 0.41. This implies that adjusting both funds for the same level of risk, the three-fund portfolio has a stronger performance than the S&P 500.  As an example, we can use leverage which investors can access using a margin account to amplify both the risk and returns of the three-fund portfolio such that both the three-fund portfolio and the S&P 500 have the same volatility.  The backtest results show that when we leverage the three-fund portfolio 1.66X, the volatility of the three-fund portfolio matches the volatility of the S&P 500 at 20.6%. With a leverage of 1.66X, the annualized returns of the three-fund portfolio is 13.8%, outperforming the S&P 500 which has an annualized return of 10%. Strategy 3: Ray Dalio All Weather Portfolio The Ray Dalio All Weather Portfolio also uses asset class diversification to reduce portfolio volatility and drawdown which makes an excellent choice for conservative investors. Unlike the 60/40 portfolio and three-fund portfolio, this strategy provides exposure to 5 different asset classes including stocks, bonds and commodities through ETF investing. These are the 5 ETFs and their portfolio weights: 30% in Vanguard Total Stock Market (VTI) 40% in iShares 20+ Year Treasury Bond (TLT) 15% in iShares 3-7 Year Treasury Bond (IEI) 7.5% in SPDR Gold Trust (GLD) 7.5% in iShares S&P GSCI Commodity Indexed Trust (GSG) Using the power of rebalancing, during a recession when gold and bonds significantly outperform stocks, the strategy will sell gold and bonds and reinvest the profits into stocks which are cheap. Conversely during a bull market when stocks outperform gold and bonds, the strategy will sell stocks and reinvest profits into gold and bonds at lower prices. This allows the all weather portfolio to achieve high risk adjusted returns regardless of market conditions. The backtest results show that even though the all weather portfolio has a lower total return compared to the S&P 500, the strategy’s returns look a lot smoother than the S&P 500 with a significantly lower volatility and drawdown.  Examining the statistics, over the period from 2007 to 2020, while the all weather strategy has a lower annualized return (7.4% vs 9.1%), its volatility and drawdown is almost one third of the S&P 500. In exchange for having an annualized return that is 1.7% less than the S&P 500, we are able to reduce our risk to one third the risk of the S&P 500. Sounds like a pretty good deal! Consequently, the risk adjusted returns of the all weather portfolio is higher with a Sharpe of 0.56 vs 0.37 for the S&P 500.  One drawback of this strategy though is that since the annualized returns are relatively low at 7.4%, investors with a large risk appetite might not be able to achieve their expected returns even with leverage. Due to Reg T constraints on margin accounts, a retail investor is capped at 2X leverage due to initial margin requirements.  When I re-ran the all weather portfolio with 2X leverage, it achieves an annualized return of 14.4% and a volatility of 14.8%. While this performance is already significantly better than the S&P 500, for investors with a target volatility above 20%, they would need to consider the use of futures and options to gain additional leverage that ETFs do not provide.  Final Thoughts For conservative investors to sleep well at night, using ETF investing to gain exposure across multiple asset classes is a great way to reduce risk and increase risk adjusted returns. The 3 ETF investing strategies discussed in this article are able to outperform the S&P 500 benchmark with higher risk adjusted returns.  As a follow up exercise, I invite you to clone the Ray Dalio all weather portfolio and backtest your investment strategy using PyInvesting’s backtesting software. I've also attached a tutorial video below to guide you on how to create a strategic allocation backtest. Happy investing and may the odds be in your favour.  
Ivann Fok · 10 months, 3 weeks ago
Want to view trading signals from the magic formula? Check out our backtesting software.
Hi everyone, I am very excited to share a new feature which allows you to view the signals generated by your trading strategy in your backtest results. This feature would bring greater transparency to your backtests allowing you to understand why certain stocks were selected by your investment strategy based on your trading signals.  What are trading signals? A trading signal is an indicator used by an investor to determine whether to buy or sell a stock.  For example, a value investor could rely on the price to earnings ratio (PE ratio) to decide whether to buy or sell a stock. A low PE ratio would be a buy signal as the stock’s price is low relative to its earnings while a high PE ratio would be a sell signal.  There are many possible types of trading signals. Day traders and swing traders tend to look at technical indicators such as moving averages, volatility and other technical patterns in prices to form their trading signals. Investors with a long term view rely on fundamental data such as price to earnings ratio (PE ratio), return on equity (ROE) and profit growth as indicators to buy or sell a stock.  How do I combine trading signals? Investors usually have multiple preferences when it comes to trading signals. For example, the Magic Formula by Joel Greenblatt relies on both the earnings yield and return on capital.  However, combining these signals together is not as simple as adding them together. This is because the potential range of values for the earnings yield are very different from return on capital. To make the earnings yield signal comparable with return on capital signal, we need to normalize the signals. This normalization is done using the z-score where we adjust our signals using their mean and standard deviation. By normalizing both the earnings yield and return on capital, we can now add these 2 signals together to form an equally weighted overall signal.  This overall signal is used to rank our stocks so we can identify the best stocks to buy and the worst stocks to sell from our portfolio.  How do I view my trading signals? To view your trading signals click on the results button in the top navigation bar and select a backtest result. If you have not created a backtest before check out this tutorial on how to create a backtest. As an example, I chose a fundamentals backtest using the Magic Formula by Joel Greenblatt. The strategy selects the top 30 stocks every year with the lowest price to earnings ratio (PE ratio) and stocks with the highest return on equity (ROE) from a basket of 150 US stocks. This strategy does decently well against the S&P 500 with a higher annual return of 14.4% vs 9.0% and a lower volatility 19.3% vs 20.3%.   Scroll down to the signals section of the results page. Here, you will find a signals table with different trading signals in each column used by your backtest. The last column on the right shows the overall trading signal calculated from the z-scores of each individual trading signal. You may sort the table based on a specific column by clicking on the blue column heading. This helps you to understand how your stocks would rank for each trading signal.  Sorting based on the price to earnings ratio (PE ratio) trading signal, we can see that in our portfolio, General Motors, Biogen and Gilead Sciences have the lowest price to earnings ratio (PE ratio).  Sorting based on the return on equity (ROE) trading signal, Moody’s, Lockheed Martin and Clorox have the highest return on equity (ROE).  Conclusion Backtesting software tends to be a black box for most people. We input our backtest details, run the backtest, and view the stocks that were selected by the backtester.  However, I think it is useful to know the actual signals used by the backtester and how the overall trading signals were calculated based on the z-score. I hope this new signals table will help you understand why the backtester selected the respective stocks in your current portfolio and help you rank these stocks based on their trading signals.  If you would like to see this new feature in action, I invite you to create a fundamentals backtest using the magic formula. Happy investing and may the odds be in your favour.
Ivann Fok · 11 months, 1 week ago
The Ultimate Tool for Finding Top Breakout Stocks
Ed Seykota, one of the market wizards behind computerized systems trading, turned $5,000 into $15 million in 12 years. He is a strong believer in trend following and uses a breakout trading system to enter trades when momentum is in his favour. Whether you do day trading or swing trading, using a solid breakout trading system can significantly improve the risk reward ratio of your trades and increase your trading profits in the long run. In this article, I’m going to introduce a tool that I built to help you identify top breakout stocks with explosive momentum. What is a breakout in stocks? A breakout in stocks occurs when the price of a stock breaks above its resistance level or breaks below its support level. After a breakout happens, prices tend to continue moving undeterred with strong momentum. The example below shows Tesla breaking out from it’s 140 day high in November 2019 (highlighted in yellow) when it surged from $65 to almost $400 one year later.  You can think of the stock’s price normally acting as a ping pong ball bouncing between a glass floor (support level) and a glass ceiling (resistance level).  When the ball hits the floor, it rebounds off the floor which acts as a support. When the ball hits the ceiling it bounces off the ceiling which acts as a resistance.  However, what happens if this ping pong ball suddenly transformed into a bowling ball during mid flight?  If the bowling ball is falling towards the floor, it would smash right through the glass floor which offers little support against the bowling ball’s large momentum. Similar If the bowling ball is flying towards the ceiling, it will smash right through the glass ceiling which provides negligible resistance. In the case of stocks, when investors get excited due to a positive earnings release for example, this enthusiasm provides the momentum for the stock price to break through its resistance level and surge towards new highs.  Conversely when investors start panicking due to a public health crisis such as Covid-19, the widespread fear across the market causes stock prices to crash through their support levels. As a breakout swing trader or day trader, your goal is to identify such breakouts when they occur so that you can buy stocks that break above their resistance level and short stocks that break below their support level. How do you trade breakouts? The rules of a mechanical trend following trading systems are very simple. Go long when the price breaks above the high of the past n days. Go short when the price breaks below the low of the past m days. The highest price of the past n days acts as the resistance level. If the stock’s price is able to break above this high price, it reflects strong upward momentum. This is a strong indicator that confirms a breakout into an uptrend.  Conversely the lowest price of the past m days acts as the support level. If the stock’s price is able to break below its low price, it is a strong indicator that confirms a breakout into a downtrend. Let’s take a look at Apple. The chart below shows the price of Apple (blue line) sandwiched between 2 gray lines which act as the channel.  The gray line above the blue line is the resistance level based on the high of the past 20 days. The gray line below the blue line is the support level based on the low of the past 60 days.  The green arrow is an indicator to go long when the price hits the top gray line. The red arrow is a signal to short the stock when the price hits the bottom gray line. The big question is what look back periods should we use?  The turtle traders, under the mentorship of Richard Dennis, used both a short term and a longer term lookback period for systems trading.  System 1 was a short term system based on a 20 day breakout while System 2 was a longer term system based on a 55 day breakout.  While this set of rules for systems trading were highly profitable for the turtle traders, backtest results have shown that when the same set of rules were applied many years later, the strategy was not as successful as before.  There are two possible reasons why the strategy did not perform well years many years later.  The breakout parameters for the lookback period are fixed at 20 days and 55 days. This is a problem because different instruments have different trends. Some instruments have short term trends while other instruments have long term trends. These trends could also change over time as well so it does not make sense to use a static look back period over the entire history.   The breakup parameter of 20 days is the same as the breakdown parameter of 20 days. There is no reason to assume that these parameters should be the same because in one case we are looking to enter a long trade while in the other we are trying to short the market.  Why is it important to pick the right indicator to confirm a breakout? Picking the wrong stock breakout signal that fails to properly capture the trend can be detrimental to your strategy’s performance.  This is because if a stock is in a long term uptrend and we use a short look back period, there is a high chance that we might get whipsawed due to the volatility of the stock’s price.  For example, if we use a 120 day break up and 80 day break down window for Tesla, the plot below shows that a bad trade would be made in the part highlighted in yellow below. The system generated a sell signal in March 2020 anticipating that the stock will enter a down trend. However, the stock rebounded shortly after that, causing the trading system to miss out on the recovery after the Covid crash. If a longer term break down parameter was used, the sell signal would not have triggered because the gray line would have been lower, hence allowing more room for volatility. What traders typically do to account for the volatility of the stock’s price when deciding their breakout parameters is to use the average true range (ATR) which is a measure of the market volatility over a given period of time.  However, this approach is subjective as well. There are different multiples of ATR which you could choose to set your stop loss. For short term trends, setting your stop loss at 1 X ATR might be more appropriate while for longer term trends, setting your stop loss further away at 2 X ATR might be better to avoid being whipsawed due to volatility.  How do we remove this subjective approach towards trading and instead rely on data analysis to select the optimal breakout parameters? Finding the best stock breakout signals The best approach is to backtest your trading strategy using different breakout parameters. This allows us to figure out which breakout parameters are the most profitable and are able to generate trades with the highest risk reward ratio.  To help you out, I’ve created a tool that runs 100 backtests using different breakup and breakdown parameters. This is how you use it. First head over to https://pyinvesting.com/trading-breakouts/. Fill in the form below specifying the stock you are interested in. In this example we are going to look at Apple. Next select your start and end date for the optimization. The start date by default is chosen to be 5 years ago and the end date is set as today’s date.  Select the performance metric that you would like to use to determine which is the best breakout trading parameter. By default, the Sharpe Ratio is used which allows us to find out which breakout parameters lead to the highest risk adjusted returns of our trading strategy.  Finally hit the blue button to start trading breakouts. The results will show a heat map where each square represents the results of running a backtest with a specific breakout parameter. The greener the square, the better the performance would be based on our selected performance metric (Sharpe Ratio). The results show that the Sharpe Ratio generally improves as the breakup lookback period gets shorter. On the other hand, there is no clear pattern for the breakdown parameter in affecting the trading strategy’s performance. If you click on any of the squares, it will show you the backtest results using the respective parameters. For example, here are the results from the 20 day breakup and 60 day breakdown window. Based on these parameters, the latest signal generated by the trading system was a buy signal in April when the markets rebounded from the Covid crash and broke into an uptrend. Scrolling down we can see the profit and loss (P&L) of trading Apple using the 20 day breakup and 60 day breakdown parameters along with performance numbers such as total returns, Sharpe Ratio and max drawdown.  Conclusion Breakout trading can be highly profitable if we are able to catch onto a major trend. However, finding the best stock breakout signals is crucial as it prevents us from being whipsawed due to price volatility. We discussed how we can improve our risk reward ratio by running multiple backtests with different parameters to find the optimal parameters for our breakout trading strategy.  Now head over to https://pyinvesting.com/trading-breakouts/ and find out the best trading system for your favourite stocks today.  Happy investing and may the odds be in your favour.
Ivann Fok · 11 months, 2 weeks ago
I'm up 42% this year despite Covid. Here's how I did it.
Yes, this is a snapshot of my Interactive Brokers account. If you are an investor in the stock market, this year has been quite the ride for you. The market plunged 35% within a span of a single month from February to March this year. Shortly after, we saw a V shape recovery in the market straight back to its all time high. This was followed by increased volatility from September onwards as we head towards US elections. Despite the huge volatility in the stock market, my portfolio has done decently well this year with a return of 42.1% vs the S&P 500 which is up 9.4%. In addition, the portfolio had a significantly lower drawdown of 11%. Here’s how I did it.  Data Driven Investing As a DIY investor, I use a data driven approach when it comes to investing. No emotional trading out of fear or greed. No reaction to news headlines. And most certainly, no decisions to trade because I “felt” this stock was going to go up. All investment decisions to buy or sell a stock are made many months in advance based on my trading rules so I don’t need to scramble when markets get volatile. I hate scrambling. It’s much easier to execute a trading plan in a calm and emotionless manner using trading rules that have an edge in the market. How do I know my trading rules work? You guessed it. I backtest my investment strategy which gives me the confidence to bet my hard earned money in the stock market. Next I go live with my strategy on PyInvesting which implements my strategy by pulling live prices daily and generating orders for me to trade on my Interactive Brokers account. All I need to do is to open my email and execute the trades. Moving on, what investment strategy do I use? Trend Following I’m a simple guy. I buy stocks that have been going up and I sell stocks that have been going down. It’s called trend following. Trends exist everywhere. We have fashion trends, social trends, weather trends, heck in this age of technology we even have Google search trends. Similarly, trends exist in the stock market. Statistics show that when a stock has been going up for a period of 6 to 12 months, it tends to continue going up. There are many behavioral reasons for this effect such as herding where people tend to follow the crowd’s sentiment because the terrible feeling that comes with making a loss are muted by the fact that everyone suffered a loss in their investment as well. I identify trends using moving averages. A moving average is an average of prices within a window of time (black line). When a stock’s price is above its moving average, it means that the stock is trending upwards. Conversely when its price is below its moving average, the stock is trending downwards. Apple’s stock price with its 200 day moving average (200MA) We have fast moving averages (where the look back period is usually less than 50 days) to measure short term trends and slow moving averages (look back period longer than 100 days) to measure long term trends. Longer term trends are more stable and less noisy. Hence the 200 day moving average (200MA) is where I draw the line in the sand. Any stock that is above its 200 day moving average, I will consider to include in my portfolio. Any stock that is below its 200 day moving average, I will sell if the stock is in my portfolio. Fundamental Analysis After filtering for stocks in a long term uptrend, I rank the stocks using fundamental analysis. This is done by creating a signal for each stock based on their fundamental data. I use 3 factors to create my signal. The first factor is price to earnings (PE ratio) which is a measure of the company’s valuation. The lower the PE ratio, the cheaper the stock relative to its earnings which is great for investors. After all, who doesn’t like a nice discount? The second factor is the return on equity (ROE) which the company’s net income divided by its shareholder’s equity. ROE is a measure of how efficiently a company is able to use its resources. High quality companies tend to have high ROE. The third factor is profit growth which is a measure of how quickly a company is able to grow its profits. The value of your stock is highly correlated to the earnings of a company. Companies that are able to grow their earnings quickly tend to produce huge returns on their stock prices. By combining both technical and fundamental analysis, we are able to filter, rank and select the best stocks to include in our portfolio. Active Risk Management The next step is to apply an active risk management system based on market sentiment to protect our portfolio during a crisis. The main idea here is that we want to take on more risk and hold more stocks when market sentiment is bullish. This is because during a bullish regime, markets tend to reward investors for staying invested. In contrast, when market sentiment is bearish, we want to take less risk by raising our cash allocation and holding fewer stocks. This is to protect our portfolio from suffering huge drawdowns. For example, during March this year, my portfolio was almost completely in cash as market sentiment turned bearish. This allowed me to reduce my portfolio’s drawdown to 11% even though the market tanked 35%. Subsequently, PyInvesting gradually started buying stocks and reducing cash to participate in the V shape market recovery that followed. If you are interested in how I determine this cash allocation feel free to check out PyInvesting’s fear and greed index. Position Sizing The final piece of the puzzle is position sizing. I hold at least 30 stocks in my portfolio and equal weight each of them. Why do I do this? To avoid concentration risk. I don’t have a crystal ball and can’t predict when a stock will tank due to a surprisingly bad earnings release or for the case of Tesla, whether the CEO is going to Tweet. Because of that, I keep each position small so that my risk of being screwed by any single stock becomes very small. With 30 stocks, my portfolio sits at the yellow sweet spot in the plot below. I get to reap most of the benefits of diversification where the volatility of the portfolio approaches the volatility of the market. Holding more than 30 stocks has not much additional benefit of reducing my portfolio’s volatility.   Image source: Stockopedia In doing so, I’m not betting on any single stock carrying the entire portfolio. I’m betting on investment concepts that on average, a group of stocks with high momentum, low PE ratio, high ROE and high profit growth outperforms the S&P 500.  The naive argument against holding 30 stocks in your portfolio is that no one has enough time to research so many stocks and that people who hold more than 10 stocks in their portfolio do not know what they are doing.  My retort against people who make this argument is that we are not living in the age of the dinosaurs. With the help of technology, it’s not difficult to use a backtesting software like PyInvesting to comb hundreds of companies and select the top 30 stocks with the strongest fundamentals and best technical setups in a matter of seconds. Putting It All Together We covered multiple individual steps that contributed towards my overall portfolio strategy. We started with identifying stocks that were in a long term uptrend. Next we ranked these stocks using fundamental analysis. Following which we applied an active risk management system. Finally we did position sizing to reduce concentration risk.   Each step contributed towards the overall performance of my portfolio which outperformed the S&P 500 by over 30% so far this year.  Even though there were many steps involved. Implementing the strategy was a breeze using PyInvesting. I simply filled in a form to specify the details for my backtest and went live with my strategy on the cloud. After that all I did was to execute my trades on Interactive Brokers (IBKR) whenever I received an email from PyInvesting.  If you enjoyed this article and would like to go live with your investment strategy on the cloud, I invite you to check out PyInvesting’s moving average backtest which I used to create my personal investment strategy. I hope that it will be helpful to you in your journey towards financial freedom. Happy investing, and may the odds be in your favour.
Ivann Fok · 1 year ago
How to Backtest a Trading Strategy Even if You Can't Code
Have you ever tried an investment strategy that was highly recommended, yet decided to quit once you started losing money? I know I have. A buddy of mine who used to work at a hedge fund was preaching to me about his insane portfolio with super star stocks. For some reason I thought it would be cool to go along and invest in the same stocks as he did. And so I did. When I bought in, it happened to be a good entry point as the market was going up almost everyday. With stocks like Sea and Tesla, there were days when the portfolio surged 4% in a single day! However as markets became highly overbought, a huge red day soon followed. I panicked and cashed out shortly after that. Overall, I stuck with the portfolio for three short weeks. While it was an exciting experience, never again would I invest in a strategy that I had no confidence in.  How do I find a strategy that I can stick to, even when markets are volatile?  Backtest your portfolio Backtesting is the process of simulating an investment strategy using historical prices to test how well the strategy would have done in the past. You need to backtest your investment strategy because it allows you to confirm whether you have an edge in the market without risking any of your own money.  It’s kind of like how pilots have to train using a flight simulator before they are allowed to fly a plane. In the flight simulator, the pilot will be tested on whether he is able to safely navigate the plane through different situations. If a pilot crashes a plane during a flight simulation, there is no way he will be allowed to fly a real plane with hundreds of passenger lives at risk.  Similarly, if an investment strategy has performed poorly during a backtest, why should you risk your hard earned life savings on this strategy?  In addition, backtesting your trading strategy does not put any of your money at risk. It is a way to research your trading ideas and test whether they are profitable before your money is on the line.  Now that we have discussed the importance of backtesting, the next question is how do we backtest a trading strategy? Decide on your trading rules  Every backtest relies on a logical set of trading rules that gets applied consistently during each day’s simulation. This set of trading rules is also commonly referred to as your trading plan. As an example, we are going to backtest a moving average crossover strategy. Moving averages are used to estimate the momentum of a stock. Stocks trading above their moving average have upward trending prices (uptrend stocks) while stocks trading below their moving average have downward trending prices (downtrend stocks). We want stocks that are in a strong uptrend as they are likely to continue going up.  This strategy’s trading rules are as follows: Filter for stocks trading above their 200 day simple moving average (200SMA).  Rank the filtered stocks based on the following signals: Lowest price to earnings ratio (PE Ratio) Highest return on equity (ROE) Highest profit growth Select the top 20 stocks with the highest ranking to form an equally weighted portfolio. Our investment universe will be stocks from the S&P 500, we will be observing the portfolio weekly to check whether every stock in the portfolio is above its 200SMA. If a stock falls below its 200SMA it will be replaced with another stock above its 200SMA and with the highest ranking.  Backtesting software Backtesting a trading strategy is highly computationally intensive. Fortunately, we can rely on the power of technology to simplify this process.  Head over to PyInvesting’s moving average backtest where we will backtest our moving average crossover strategy. PyInvesting is a backtesting software that I built for users to go live with their investment strategies on the cloud.  Select stocks for your investment universe Click on the blue button to select your stocks and select S&P 500 under the template portfolio. This will select stocks from the S&P 500 that will form our investment universe.  Create your signals to rank your stocks Next we are going to select the smart beta factors used to rank our stocks. Based on our trading rules, we are going to select stocks with the lowest PE ratio, highest ROE and highest profit growth. These signals are equally weighted at 33% each and combined to form an overall signal.  Decide on your moving average parameters Following our trading plan, we are going to use the 200 day simple moving average (200SMA) to determine whether a stock is in a long term uptrend or downtrend. By default, the moving average parameters are set to the 200SMA so we do not need to make further changes. Number of stocks and portfolio rebalancing frequency Set the number of stocks to 20 and a weekly rebalancing frequency where our trading algorithm will be checking that each of the 20 stocks in our portfolio is above its 200 day moving average. Hit the run backtest button to simulate your trading strategy! Portfolio performance analysis The backtest results show that our strategy has an annualized return of 16.7% vs the S&P 500 which did 9.1% from March 2016 to October 2020. The volatility of our strategy is also lower at 17.2% vs the S&P 500’s volatility of 19.9%. Consequently, our strategy has a higher Sharpe ratio of 0.78 vs the benchmark’s Sharpe of 0.37. In addition, our strategy has a max drawdown of 39.9% during the 2008 global financial crisis while the S&P 500 was down 55.2%.  The annual returns plot also shows that our strategy beats the S&P 500 in 12 out of the last 14 years. It underperformed in 2016 and 2019. This means that there is a 85.7% (12/14) chance of beating the benchmark in any year going forward. Not too shabby.  Here is a training video I created with a live demo of me running a moving average backtest. Profiting from your investment strategy After analyzing our backtest results, we are happy with our strategy’s performance. So how do we turn our backtest into a live actionable trading strategy that we can profit from? Simply click on the “Go Live” button. Once your strategy is live, PyInvesting’s backtester will run your strategy daily with live prices and send you daily email updates with any buy or sell orders from your strategy. You can then make the trades on your own personal account to profit from your strategy. FYI Interactive Brokers IBKR is great as transaction costs are extremely low.  Happy investing, and may the odds be in your favour. If you want to develop an effective investment strategy, learning how to utilize the results of backtesting can be one of the best decisions you ever make since backtesting can help you identify an incorrect or correct investment before your money is on the line. PyInvesting is a backtesting software written in Python that helps investors go live with their investment strategies on the cloud without writing a single line of code.
Ivann Fok · 1 year ago
New feature! PyInvesting can backtest stocks with different currencies
A friend recently highlighted to me that when he ran a backtest on PyInvesting with both US and Hong Kong stocks, the backtester did not account for the currency differences. As a result, the simulated portfolio’s performance was incorrect because it did not handle the forex fluctuations between US and Hong Kong stocks. I’ve been putting off this fix for a while because it was not easy to implement with many details that needed to be handled. However, I decided to implement this feature this week because it was requested by a number of my users and it would be useful going forward as I introduce stocks from other countries into my database. Updating backtester price feeds Being able to handle the forex fluctuations between stocks of different currencies meant that I needed to convert the prices of every stock into a single currency before feeding the prices into the backtester. For example, if a backtest was done using stocks from the US and Hong Kong, I would convert the historical prices of all the Hong Kong stocks from HKD into USD using the HKD/USD historical FX times series. This would make the stocks from different countries comparable with each other and account for the currency differences.  The result of this change is that the net asset value (NAV) of the backtested portfolio will now be in USD and we can observe the performance of our investment strategy in terms of USD. However, what happens if a user is based in Singapore and would like to find out how his investment strategy performs in SGD terms? Introducing base currency The next step would be to convert the historical performance of the backtested strategy from USD into the preferred currency of the user, also known as the base currency. To do that, I have added a drop down menu on every backtest form page, where the user will have to select the base currency for the backtest. Next, PyInvesting will convert the performance numbers from USD to the user’s selected base currency.  Users can also change the base currency on the results page by clicking on the currency shown in the screenshot above. This would allow them to observe how the performance of their investment strategy changes when viewed from the perspective of a different currency. For example, as the Singapore dollar has appreciated against the US dollar over the last 15 years, the performance of an investment strategy in SGD terms will be worse than the performance of an investment strategy in USD terms. Currency of live portfolio value The final impact of this feature update is that the base currency that the user selects will also be applied to the portfolio value which the user inputs when going live with their investment strategy. When users click on “Go live with this strategy” as shown in the screenshot above, PyInvesting will run their strategy daily with live prices and send live orders to users so they can profit from their investment strategy. To calculate the quantity of lots that users need to buy and sell on their personal account, PyInvesting will prompt users to input the size of their portfolio. This portfolio value will be based on the currency selected by the user. If the user selects SGD for example, this portfolio value shown in the screenshot below will be $10k SGD which is used to determine the number of lots to buy or sell for each stock in the user’s personal portfolio.   Conclusion I’m glad that this feature has finally been rolled out. It was not an easy one to implement and I hope that it will be helpful for users that invest in stocks across different currencies by automatically handling the forex fluctuations for them. I would love to hear your thoughts on this new feature. Do check it out and let me know what you think on the PyInvesting forum (https://pyinvesting.com/forum/).  Happy investing, and may the odds be in your favour. If you want to develop an effective investment strategy, learning how to utilize the results of backtesting can be one of the best decisions you ever make since backtesting can help you identify an incorrect or correct investment before your money is on the line. PyInvesting is a backtesting platform that helps investors go live with their investment strategies on the cloud without writing a single line of code.
Ivann Fok · 1 year ago