PyInvesting

Helping investors beat the market.


Ivann Fok
2 months, 3 weeks ago · 551 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.


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 · 1 week, 1 day 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 · 3 weeks, 2 days 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 · 1 month 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 month, 2 weeks 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 month, 3 weeks 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 · 2 months ago
Ivann Fok · 2 months, 1 week ago
3 Ways to Evaluate the Performance of your Investment Strategy
Do you happen to know that one guy who only invests a single stock because it is the hottest stock in the market? This guy is usually the loudest person in the room and will always brag about how much money he made just dumping his entire net worth into a Tesla stock. Let’s call him, Mr Tesla.  Another guy that you might know, loves to invest in tech companies. He is the guy that queues up for hours just to get hold of the latest iPhone on the same day that it is released into the market. Because of his obsession with technology and IT gadgets, his favourite stocks to invest in are Facebook, Apple, Amazon, Netflix and Google also known as FAANG stocks. Let’s call him, Mr FAANG. Mr FAANG holds an equal weighted portfolio of FAANG stocks and rebalances his portfolio once a year using a strategic allocation backtest.  One day, Mr Tesla and Mr FAANG bumped into each other at a bar, got drunk, and started arguing with each other about who is the better investor.      Mr Tesla: “My returns are higher!”  Mr FAANG: “But your risk is higher too!”  They both have a point. Mr Tesla has a higher return of 44.6% vs Mr FAANG’s less impressive 34.5%. However, Mr FAANG’s portfolio has a lower volatility of 25.3% vs Mr Tesla’s portfolio of 53.5%.   So who is the better investor? Introducing risk adjusted returns While Mr Tesla does indeed have a significantly higher annualized return than Mr FAANG, he achieves this annualized return at more than double the volatility of Mr FAANG. To compare Mr Tesla’s performance against Mr FAANG, we need to use a performance metric that rewards investment strategies with high returns while penalizing strategies with high risks. This is known as the risk adjusted returns of a strategy. Investors generally prefer higher risk adjusted returns as compared to simply higher returns because it accounts for the difference in risk between strategies.  Sharpe ratio The Sharpe ratio is one of the most common measurements of risk adjusted returns. It is the excess return of your strategy divided by its volatility. The excess return can be obtained by subtracting the risk free rate from the annualized returns of your strategy. The risk free rate is the return from investing in a safe instrument such as the yield for US treasury bonds.  Sharpe ratio = (Annualized returns - Risk free rate) / Volatility  The higher the returns of a strategy, the larger the numerator, the higher the Sharpe ratio. The higher the volatility, the larger the denominator, the lower the Sharpe ratio. Doing the math for both strategies, Mr FAANG comes out ahead of Mr Tesla with a Sharpe of 1.25 vs 0.78.  Sortino ratio The next measure of risk adjusted returns is the Sortino ratio. This ratio is slightly different from the Sharpe ratio where instead of dividing the excess returns by the volatility, we divide the excess returns by the semi deviation. The semi deviation is calculated by measuring the volatility on days when the strategy has negative portfolio returns.  Sortino ratio = (Annualized returns - Risk free rate) / Semi deviation Using the semi deviation makes sense because any investor should welcome upside volatility as it translates to higher returns. By differentiating between harmful volatility from the overall volatility of a strategy, the Sortino ratio provides a better representation of risk adjusted returns than the Sharpe ratio.  Going back to Mr FAANG’s and Mr Tesla’s investment strategy, we can see that Mr FAANG still comes out ahead of Mr Tesla with a higher Sortino ratio of 1.60 vs 1.11 Calmar Ratio The Calmar ratio is another measure of risk adjusted returns. Unlike the Sharpe and Sortino ratios that depend on volatility, the Calmar ratio looks at the maximum drawdown of a strategy.  The maximum drawdown is the maximum loss from peak to trough of your portfolio’s value before a new peak is attained. For example, the maximum drawdown of the S&P 500 was 56% as it lost 56% from its peak in October 2007 to March 2009 before going on to recover from the global financial crisis. The Calmar ratio is calculated by dividing your strategy’s annualized returns by its max drawdown. Calmar ratio = Annualized returns / Max drawdown The Calmar ratio might appeal more to some investors because the max drawdown is a better indicator of your strategies risk. While volatility is commonly used as a proxy for risk, it does not give the investor an idea of how much he could lose during black swan events like what we saw during the recent Covid crisis.  Comparing Mr FAANG’s and Mr Tesla’s investment strategy, we can see that Mr FAANG wins with a higher Calmar ratio of 1.08 vs 0.74 How do you improve your risk adjusted returns? Overall, Mr FAANG’s investment strategy has higher risk adjusted returns as compared to Mr Tesla. All 3 performance metrics (Sharpe, Sortino and Calmar ratios) were higher for Mr FAANG’s strategy.  There are 3 key reasons why Mr FAANG’s strategy outperformed with higher risk adjusted returns.  Diversification. Everyone knows that the only free lunch on wall street is diversification and that we should never put all our eggs in one basket. By spreading his bets among 5 different stocks, Mr FAANG was able to reduce the risk of his portfolio as compared to Mr Tesla who was all in on a single stock. The logic behind this is that by investing in different stocks, the portfolio’s volatility is lower because of different stocks moving in different directions and at different pace where the correlation between different stocks is less than 1. Equal weighting. By equal weighting the portfolio among 5 different stocks, there is a much smaller concentration risk in the portfolio as compared to holding a single stock. By allocating the weights equally between different stocks, it ensures that even if one of the stocks does not do well, the impact on the overall portfolio will be limited. We are betting on the average performance of every stock in the portfolio rather than on a single stock hitting a home run for us.   Rebalancing. The purpose of rebalancing is to adjust the weight of each stock in the portfolio back to its target weight so that we can maintain our equal weighting over time. As the different stocks in the portfolio have different performance, over time this difference in returns gets larger causing the weights between each stock to differ from their target allocation of 20% per stock. Rebalancing involves taking profits on some stocks that have performed well and reinvesting these profits into stocks that have fallen in value. This allows us to keep the weights between different stocks equal over time and reduce concentration risk in our portfolio. 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. Check out the tutorial video below to see a live demo of how to analyze the performance of your backtest.  
Ivann Fok · 2 months, 1 week ago
Top 3 factors that determine which investment strategy is right for you
When it comes to investing, every investor has their own personal tastes and preferences. Investors approaching retirement tend to be more conservative and prefer strategies with lower risks while young working adults usually have a higher risk appetite and are willing to stomach some volatility in exchange for higher returns. Whichever strategy you choose, it is important that you are comfortable with the risk it entails so that you are able to stick to your strategy and avoid making emotional decisions.  There are three key factors that determine which investment strategy is right for you.  Risk tolerance Expected returns Effort required to implement the strategy Risk tolerance The first factor is your risk tolerance which is the amount of risk you are willing to take on in exchange for a return on your investment. Generally, investment strategies with higher risks should be rewarded with higher returns. You should choose an investment strategy with a target risk that you are comfortable with and will not cause you to lose sleep at night. Many investors are often attracted to the high returns from an investment strategy. However when markets get volatile, and they start seeing huge fluctuations in their portfolio’s value, they are unable to stick to the plan and get shaken out of their positions. They end up panic selling and crystalizing huge losses on their portfolio.  One way you can measure the risk of your strategy is to backtest your investment strategy and find out the maximum drawdown of your strategy. The maximum drawdown tells us what is the maximum amount of money you can lose on your portfolio during a crisis. For example, during the 2008 crisis, the S&P 500 lost 55% from it’s peak value in October 2007 to March 2009.  You need to ask yourself how much are you prepared to lose if markets were to crash and are you willing to stay the course. Retirees who need to gradually withdraw their funds for their daily expenses should only invest a small percentage of their wealth that they can afford to lose. Young working adults on the other hand should take on more risk because they have time on their side to ride out any market crashes.  For me personally at 30 years old, I’m comfortable with a 50% drawdown on my portfolio if a black swan event such as the 2008 global financial crisis were to happen again. When I’m 50 years old, I would be comfortable with a 30% drawdown on my portfolio.  Expected Returns The second factor that determines your investment strategy is expected returns. How quickly do you need your money to grow to achieve your financial goals?  The math shows that if you save $50 a day for 20 years at a 10% rate of return, you will end up with over a million dollars. However, if your investment strategy is expected to make 5% a year, it is extremely unlikely that you will hit a million dollars at the same saving rate. This could mean being able to free yourself from the corporate rat race a few years earlier and being able to provide a significantly higher standard of living for your loved ones.  You can measure the expected returns of your strategy by backtesting it using historical prices and calculating the annualized returns. Check out this tutorial video below to find out how you can analyze the performance of your investment strategy.   Once you get the annualized returns from your backtested investment strategy as shown below, you can plug that value into the CPF retirement calculator to find out whether you are able to hit your financial goals. Effort Required  The third factor is how much effort you are willing to spend on managing your investments. Some strategies require less work to maintain than others and would appeal to more hands off investors. It is important to choose a strategy that fits the amount of effort you are willing to commit to implement the strategy. This is because if you choose a strategy that requires more time to implement than you are willing to commit, you could end up finding it a chore to manage your portfolio and eventually give up on following your strategy. For investors who are not willing to spend a lot of time managing their portfolio, long term strategies such as the Ray Dalio all weather strategy, would be a great fit. This strategy involves allocating a fixed percentage of your portfolio in specific asset classes such as stocks, bonds, REITs and commodities and rebalancing the portfolio once a year to the portfolio’s target allocation. Investors that are able to spend more time managing their portfolios are able to adopt more active strategies such as a moving average strategy where they monitor their positions on a weekly basis. Note that actively monitoring your positions does not necessarily mean you are trading every week. The investor could simply be frequently checking each position more frequently but only opportunistically trading a small number of stocks in the portfolio if they change their buy or sell conviction.  Backtest your investment strategy When choosing our investment strategy, it is important to consider our risk tolerance, our expected return and the amount of effort we are willing to spend on managing our portfolio. Having the right investment strategy will allow us to stay invested even when markets are volatile and help us achieve our financial goals.  Backtesting your investment strategy will allow you to estimate the strategies expected risk and return, and understand the amount of effort required to manage your portfolio. While most portfolio backtesting methods involve expertise in programming and statistics, we can use platforms such as PyInvesting.com to simply fill in a form and create a backtest. The website will run your investment strategy using live prices and send you an email with the orders you need to trade on your personal account.  Stay the course, and may the odds be in your favor.
Ivann Fok · 2 months, 2 weeks ago
Here's Why Every Investor Should Backtest Their Investment Strategy
What is Backtesting? Backtesting is the process of simulating an investment strategy using historical prices to test how well the strategy would have done in the past. Running a simulation over a large number of stocks over the past decades is a computationally intensive process. Fortunately, with the help of technology, investors can rely on backtesting software to run these calculations in a matter of seconds. Some of the most popular backtesting frameworks used to backtest trading strategies are created using Python code.     Why is Backtesting Important? Investment backtesting allows investors to analyze the historical behaviour of an investment strategy and determine how profitable the strategy is. If the backtest results show that a strategy has high returns and low risk, investors will have greater confidence of going live with the strategy. The main idea is that any investment strategy that has performed well in the past is likely to perform well going forward. Conversely if a backtest on a particular investment strategy shows poor performance, the strategy should be rejected because if it performs poorly in the past, it is unlikely to perform well in the future.  Backtesting investment strategies also helps investors understand their strategy’s behaviour during different key periods in history such as the global financial crisis and the Covid-19 public health crisis. They will know how much money they can expect to lose during these black swan events. For older investors, taking on too much risk could mean significantly delaying your retirement. For younger investors who are investing on margin (borrowed money), a large drawdown could mean receiving the dreaded margin call from your stock broker. By backtesting our investment strategy, we are able to know exactly how much money we will lose during these difficult periods so we are able to determine how much risk we can afford to take before we actually start investing. What kind of investment strategies can be backtested? Any strategy that can be expressed as a set of rules can be backtested. For example, a value investor might be interested in a strategy that selects 10 stocks with the lowest price to earnings ratio every year. Similarly an investor that relies on technical analysis might look at buying a stock when its fast moving average crosses above its slow moving average.These strategies all follow a consistent set of rules that can be simulated using historical data. The advantage of rules based investing is that it removes emotions from the picture. Every decision to buy or sell a stock is driven completely based on logic. This prevents investors from making behavioural mistakes such as panic selling or buying due to the fear of missing out. How do we create a realistic backtest? As the purpose of investment strategy backtesting is to find out how effective an investment strategy is, it is important to ensure that our backtest is as realistic as possible. This prevents us from creating backtests that look very attractive on paper but yet perform poorly during live trading. There are a few ways to achieve a more realistic backtest. 1. Choose a large investment universe of at least 100 stocks  A large universe will allow your strategy to select from a wide variety of stocks. This is important because it allows us to test whether the strategy is able to pick winning stocks from a large basket of stocks. A great strategy will be able to differentiate between winners and losers. However, if we restrict our investment universe to a small number of stocks, there are not many stocks for the strategy to select from. This makes it difficult for us to confirm whether a strategy works because both a great and a poor strategy are likely to pick the same stocks when there are so few to choose from. 2. Include at least 20 stocks in your portfolio Having 20 stocks equally weighted in your portfolio will reduce your portfolio’s concentration risk. This means that no single stock will have a huge impact on your portfolio’s performance which allows us to reduce the chance that your strategy just happened to be lucky and picked a winning stock. For example, if our strategy only picked Tesla and was 100% invested, it would have made huge returns over the last few months. However I would not be convinced that the strategy works because it could have picked another stock out of sheer randomness. It is much harder for a strategy to pick 20 winning stocks than a single winning stock. By ensuring that our strategy holds a diversified portfolio, we can confirm that the strategy is able to consistently pick multiple winning stocks and include them in a high sharpe ratio basket of stocks. 3. Choose a sufficiently long backtest period Ideally, your backtest period should be at least 15 years. This allows us to observe how the strategy performs over multiple economic regimes. For example, by including the 2008 financial crisis which happened 12 years ago, we can understand how much money our strategy would lose during a crisis. This allows us to manage the risk of our portfolio. For older investors that are retiring soon, this means deciding how much money they should invest in the market such that even if a crisis were to happen, they would have enough cash savings to retire as planned. For younger investors investing with leverage, it could mean understanding how much money they can afford to lose during a crisis without being hit by a margin call.  4. Include transaction cost The backtest should include your broker’s transaction cost. Whenever an investor buys or sells stocks, they would incur transaction cost that is paid to the broker. Over time as the number of transactions increase, your transaction cost will increase which would have a significant impact on your strategy’s returns. Moreover, strategies that have high turnovers and make a lot of trades will incur higher transaction costs than strategies that have low turnovers. Hence it is important to include transaction cost so we get a realistic idea of how much money our strategy will make during live trading.  How do we create a backtest? While backtesting requires a great deal of calculations, there are multiple websites we can use to create a backtest easily without writing a single line of code. These platforms include https://www.portfoliovisualizer.com/, https://www.etfreplay.com/, https://www.tradingview.com/ and https://pyinvesting.com/. In the table below, I compare the different backtesting platforms and weigh the pros and cons. To be able to backtest a portfolio of different stocks, all platforms except TradingView provide this functionality. TradingView is used more for backtesting a single stock and does not allow users to analyze the performance of a portfolio with multiple stocks. In terms of allowing users to backtest different kinds of strategies, Portfolio Visualizer is the only platform that lacks options. They only allow users to run an allocation backtest where the user has to specify the weights of each stock in the portfolio. All other platforms allow users to choose from multiple types of backtests such as relative strength and moving average backtests.  Regarding stock coverage, all platforms have extensive coverage across multiple exchanges except ETF Replay which is limited to ETFs and a handful of US stocks. If you invest in the Singapore market, unfortunately this platform will not be very helpful as it does not include Singapore stocks.  Among the different platforms, only PyInvesting provides fundamental data such as price to earnings ratio, free cash flow, return on equity, profit growth and more. These fundamental data are obtained from the company’s financial statements going as far back as 15 years. For investors that rely on fundamental data, this is currently the only platform that allows you to create a backtest using fundamental data without writing a single line of code. All other backtesting platforms above only provide technical indicators based on price or volume data which is not suitable for most long term investors. Finally, only PyInvesting allows users to go live with their investment strategy on the cloud. The website will send users an email to update them on their live positions and orders which they can trade on their personal account.  Here is a tutorial on how you can use PyInvesting to create a moving average backtest where the algorithm would select stocks trading above their moving average and sell stocks that are trading below their moving average.   Final Thoughts Every investor should backtest their investment strategy because it allows them to analyze the historical behaviour of their investment strategy and determine how effective it is. Backtesting also helps investors understand their strategy’s behaviour during different key periods in history which allows them to manage their risk. Finally backtesting allows investors to follow a logical set of rules which removes emotion from the picture and helps them make data driven decisions.
Ivann Fok · 3 months, 1 week ago