PyInvesting

Helping investors beat the market.


Blog

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.
Admin · 3 years, 8 months ago
External Mentions of PyInvesting
We are thankful for the following websites that have helped to spread the word about PyInvesting as a backtesting software for stock market investors. SG Stock Market Investor https://sgstockmarketinvestor.com/pyinvesting-quantitative-investing/ Datascience Investor https://www.datascienceinvestor.com/post/interview-with-ivan-founder-of-pyinvesting Dr Wealth https://www.drwealth.com/top-3-metrics-to-use-when-picking-hk-tech-stocks/ https://www.drwealth.com/how-to-beat-the-straits-times-index-by-an-average-of-7-2-per-year-using-a-smart-beta-strategy/ https://www.drwealth.com/backtest-shows-reit-investors-can-pocket-more-profits-by-using-discount-brokers/ Tree of Prosperity http://treeofprosperity.blogspot.com/2020/07/glimpse-of-investment-training-program.html The Finance.SG https://thefinance.sg/2020/08/11/using-fundamental-data-to-invest-with-the-supplementary-retirement-scheme-srs-to-complement-your-cpf-savings/ SG Invest Bloggers http://www.sginvestbloggers.com/ Lady, you can be FREE https://ladyyoucanbefree.com/2020/08/23/my-stock-report-card-for-jan-aug-2020-2-mil-profit-countdown/ Feedspot Top 75 Singapore Investment Blogs https://blog.feedspot.com/singapore_investment_blogs/ Singaporean Talks Money https://sginvestment-lady.blogspot.com/2020/08/august-2020-portfolio-dividends-and.html StocksCafe https://stockscafe.academy/380/learn-how-to-create-your-own-robo-advisor-and-track-it-too/ A Path to Forever Financial Freedom (3Fs) https://www.3foreverfinancialfreedom.com/2020/09/the-singapore-market-still-provides.html My Sweet Retirement https://mysweetretirement.com/ QuantPedia https://quantpedia.com/ Money Maverick https://www.moneymaverickofficial.com/ The Babylonians https://www.theancientbabylonians.com/ Financial Horse https://financialhorse.com/ Re-ThinkWealth https://www.re-thinkwealth.com/ Jayron Ong https://www.jayronong.com/ Investment Cache https://investmentcache.com/ Financially Independent Pharmacist https://thefipharmacist.com/backtesting-without-coding-pyinvesting-review/ Scrappy Finance https://www.scrappyfinance.com/ Investment Moats https://investmentmoats.com/ Risk N Returns https://www.risknreturns.com/ Best In Singapore https://bestinsingapore.com/financial-blog-singapore/ SG Budget Babe https://www.sgbudgetbabe.com/ REIT-TIREMENT https://www.reit-tirement.com/ The Kiam Siap Life https://thekiamsiaplife.com/ Wealthdojo http://yourwealthdojo.com/ Daniel Consulting https://www.danconsultancy.com/
Admin · 3 years, 8 months ago
Beating the S&P 500 by selecting US stocks with strong fundamentals
Most long term investors rely on fundamental data to decide which stocks they should include in their portfolios. Fundamental data can be obtained from financial statements such as the company’s balance sheet, income statement and cash flow statement. These reports provide valuable insights into the company’s financial health, profitability and growth. These are key fundamental factors that investors should look out for as they are highly correlated to the stocks performance.  However, measuring these fundamental factors is a tedious process. Investors need to comb through hundreds of financial reports to search for these factors and then combine these different factors together to rank the available stocks. Fortunately with the help of technology, this whole process has been simplified for us. Here is how you can go live and profit from a fundamental strategy for US stocks.  investing.com Introducing PyInvesting.com PyInvesting is a website that provides financial data and backtesting tools to help you go live with your own investment strategies. Our backtesting software helps you comb through hundreds of financial reports and tells you which stocks you should trade based on your personal investment strategy. We are going to use PyInvesting to create our fundamental strategy for US stocks. Let’s go! First go to https://pyinvesting.com/backtest/fundamentals/ where we will be creating a fundamental backtest. A backtest is a simulation of our investment strategy using historical data. If the simulation results are poor where the strategy significantly underperformed its benchmark, it confirms that the strategy does not work. In contrast, if the strategy significantly outperforms its benchmark, it gives us confidence that it’s likely to perform well going forward. The backtest also tells us what stocks we should be holding in our portfolio so we know which stocks to buy or sell when we go live with our strategy.  Click on the “Select your stocks” button which opens a window to select stocks for your fundamentals backtest. Under template portfolios, click on “S&P 500” to select s&p 500 stocks from the index. The default benchmark is the SPDR S&P 500 Index (which passive investors can use to invest in the s&p 500) where we will compare the historical performance of our fundamentals investment strategy against the s&p 500 historical prices. Financial Health We want to select companies with a healthy balance sheet and a low debt to equity ratio because these companies have strong abilities to repay their creditors. Because these companies have relatively low leverage, these companies are usually quite resilient and are able to survive through tough periods without going bankrupt. As a result, investors holding these stocks tend to lose less money during a crisis because these stocks are well positioned to weather a storm.  Profitability Next, we want to select companies that are highly profitable, and have a high return on equity. A high return on equity implies that the company’s management is efficient in using investment financing to grow their business and is hence able to provide better returns to investors. A low return on equity implies that the company could be mismanaged where the management is investing in unproductive assets. Return on equity is also a measure of how efficient the company is using its resources. A high return on equity could mean that the company is increasing its profits with a relatively low amount of capital.  Growth Finally, we want to select growth companies whose earnings increase at a much faster rate than the overall economy. These companies have high profit growth and tend to reinvest their earnings into profitable areas of their business. They usually do not pay dividends and choose to reinvest profits to further grow their business. Most growth companies such as Tesla, Google, and Amazon are in the technology sector where they are constantly investing in innovative ideas and expanding into new businesses. Growth companies are able to provide huge returns to investors by focusing on revenue growth and maintaining leadership in their industry. Constructing our portfolio strategy To select stocks with strong financial health, profitability and growth, we are going to select 3 factors shown below. Stocks with the highest return on equity, highest profit growth and lowest debt to equity. These 3 factors are equally weighted at 33% each. All other factors in the table are allocated a weight of 0%. The website will automatically combine these 3 factors for you using a z-scoring approach where the factors are normalized using the mean and volatility. Subsequently, we need to decide how many stocks to hold in the portfolio. I decided to hold 20 equally weighted stocks in my portfolio to avoid concentration risks. Every month, the stocks from the S&P 500 are ranked based on these 3 fundamental factors and the top 20 stocks are selected to form an equal weighted portfolio.  Performance The results show that our fundamental strategy for US stocks significantly outperforms the S&P 500 benchmark with an annualized return of 17.8% vs 9.0% since 2006. The strategy also has a higher Sharpe Ratio of 0.73 vs the S&P 500 which has a Sharpe Ratio of 0.37 implying that the strategy has higher risk adjusted returns. While the strategy has a higher volatility than the S&P 500, it has a lower semi deviation than the S&P 500. This means that the strategy has lower downside volatility and higher upside volatility. The max drawdown of the strategy is also significantly lower than the S&P 500 where it lost 46% during the 2008 crisis vs the S&P 500 which lost 55.2%.  Overall, this backtest confirms that the fundamental strategy for US stocks works where if we select stocks with the highest return on equity, highest profit growth and lowest debt to equity ratio, we can expect to outperform the S&P 500 by 8.8% every year. This strategy is suitable for long term fundamental investors who can afford to take on some market risk in exchange for significantly higher returns.   The website also shows the current positions in the portfolio which users can trade on their own personal account. Subscribers have the option of “going live” with their portfolios where they will receive daily email updates to notify them if their strategy decides to make a trade. I’ve added a link below for users to check out the backtest results from this strategy.  https://pyinvesting.com/invest/results/ab3d20df353143a7a41cdb5ab05e83c2 If you want a full video demonstration of how to create a fundamentals backtest, check out this tutorial video below. Do consider signing up for a free account with PyInvesting to receive future updates. In my next article, I will be explaining how to use the relative strength backtest. Stay tuned and I’ll see you guys next time!
Admin · 3 years, 8 months ago
Outperforming the market with high dividend yield stocks
One of the key factors most investors look out for when purchasing stocks is how much dividend the stock pays. A dividend is a reward that the company pays to its investors which usually stems from its net profit. When a company pays high dividends, it usually indicates that a company is doing well and is able to distribute part of its earnings to its investors. These companies tend to be large, established companies with strong and predictable cash flow. However, not all companies that pay high dividends make good investments. Some companies continue making dividend payments even when they are not profitable. This is to maintain their track record of making regular dividend payments. An example would include Exxon Mobil, a huge oil and gas company. Exxon Mobil has a consistent tracking record of paying dividends every quarter since 2013. However, an investor that bought the company since 2013 would have lost 14% vs the S&P 500 which made 101% during that period.   Do high dividend yield stocks outperform? To find out whether the dividend yield factor is able to select stocks that outperform the market, I run a backtest using Python code to simulate the performance of the strategy using historical data.  From an investment universe of 500 stocks, I select 50 stocks with the highest trailing dividend yield. The trailing dividend yield is the dividends per share over the trailing 12 months divided by the stock price. It is a measure of how much cash flow you are receiving for every dollar you invest in the stock. To select the stocks, I rank each stock in the universe based on their trailing dividend yield. I equal weight each of the 50 stocks in the portfolio to reduce the concentration risk of the portfolio. This will prevent my portfolio from taking a big hit if any single stock crashes. In addition, stocks with the strongest signal within each sector are selected such that no single sector has a weight larger than 20% of the portfolio. This reduces sector risk and allows us to isolate the source of out performance due to the high dividend yield signal.   Performance The backtest results show that the high dividend yield strategy has an annualized return of 10% and volatility of 20.7%. The strategy has cumulative return of 255%, outperforming the S&P 500 benchmark by almost 55% since 2006. We can also analyse the performance of the high dividend yield strategy over different periods. The plots above show that during the great financial crisis, the strategy’s performance was almost in line with the S&P 500 benchmark. During the crisis recovery period from 2009 to 2012, the strategy significantly outperformed the benchmark by 80%. However from 2013 to 2019, the strategy has been giving up some of those gains, under performing the benchmark by 60%.   Conclusion By selecting a portfolio of stocks with the highest dividend yield in each sector, we were able to develop a strategy which outperforms the market. The simulation also showed that the strategy performed well during the crisis recovery period but gave up a significant chunk of its gains during the new normal period from 2013 to 2019. In the next article, I will be discussing how we can improve the performance of the high dividend yield strategy by combining it with the quality factor.
Admin · 3 years, 8 months ago
Choosing high quality value stocks that outperform
When it comes to investing, everyone loves to talk about glamorous stocks such as the FAANG stocks (Facebook, Apple, Amazon, Netflix, Google). These are the stocks that get a lot of attention from investors and make good conversation topics at parties. However, is now the best time to be holding these stocks? Probably not, if you are a believer in value investing as these highly popular stocks are pretty expensive relative to their earnings. In my previous article, I wrote about how the value investment theme of selecting cheap stocks outperforms expensive stocks. While I was explaining the question of why value stocks outperform over time, we also discussed how value investing is subjected to risks such as the value trap, where cheap stocks continue to remain cheap because the company fails to improve and innovate. This implies that value investing doesn't work all the time and there is certainly room for improving the strategy. Can we do better in selecting value stocks that outperform stocks in general? In this article, I investigate how we can improve our value investing strategy by filtering for high quality stocks. By selecting stocks that are both cheap and are highly profitable, it is possible to increase the performance of our strategy. The best part about this strategy is that it is completely rules based so there is no room for opinions and speculation. Everything is straight forward based on the valuation and profitability numbers. By using a systematic value investing strategy, we are able to remove emotions and completely rely on logic to make our investment decisions. How do we select quality value stocks? From an investment universe of 500 stocks, I select 50 stocks with the lowest price to earnings ratio (PE ratio) and the highest return on equity (ROE). The PE ratio is a stock’s adjusted close price divided by its earnings per share (EPS). A low PE ratio implies that the stock is trading at a low price relative to its earnings. A cheap stock has a low PE ratio. The company’s ROE is its net income divided by its average total common equity. It is a measure of how much profit a company can generate with every dollar of capital. A high ROE implies that a company is highly efficient because it is able to generate profit with relatively little capital. A quality stock has a high ROE. To select the stocks, I rank each stock in the universe based on their inverse PE ratio (since we want stocks with a low PE ratio to have a high ranking) and ROE. Next, I take the average of each stock’s PE ratio ranking and ROE ranking. This gives me an overall signal which combines both value and quality factors and allows me to select low price high quality stocks.  Risk management I equal weight each of the 50 stocks in the portfolio to reduce the concentration risk of the portfolio. This will prevent my portfolio from taking a big hit if any single stock crashes. In addition, stocks with the strongest signal within each sector are selected such that no single sector has a weight larger than 20% of the portfolio. This reduces sector risk and allows us to isolate the source of outperformance due to the value and quality signal. I do not want the strategy to outperform or underperform because it was overly exposed to a single sector but rather because the strategy was invested in cheap and high quality stocks across all sectors. Performance I used Quantopian to backtest this python value investing strategy. The backtest results show that the quality value strategy has a cumulative return of 238%, outperforming the S&P 500 benchmark by almost 50% since 2006. More importantly, by including the quality factor to our pure value investing signal, the performance of our strategy has improved! The quality value strategy makes an annual return of 9.6% vs the pure value strategy which makes 8.9%. Besides increasing the returns of the strategy, the quality value strategy has a lower volatility of 19.4% vs the pure value strategy’s volatility of 19.7%. This means that the risk of the strategy has decreased. As a result, by combining the quality factor to our value factor, the risk adjusted returns of the strategy has increased. Hence for the same level of risk, the quality value strategy makes a higher return. This is reflected by the higher Sharpe ratio of the quality value strategy 0.57 vs 0.53 of the pure value strategy. Conclusion By combining the quality factor with our initial value investing strategy, our backtest has shown that we are able to achieve higher risk adjusted returns. This is because the stocks from our quality value strategy are both cheap and highly profitable. This strategy appeals to value fundamental investors that have a long investment horizon. While Warren Buffet once said that it’s better to buy a wonderful company at a fair price than a fair company at a wonderful price, I would argue that it’s even better to buy a wonderful company at a wonderful price.
Admin · 4 years, 10 months ago
Will value investing make you rich?
Warren Buffet, the 3rd richest person in the world with a net wealth of 86.3 billion, made his fortunes through value investing. Can we replicate his strategy to get similar results? I ran a historical simulation of a value investing strategy and will be answering the following questions: What are the rules used to select value stocks? How profitable is the value investment strategy if we used it from 2006 until today? What is value investing? Value investing is an investment strategy that selects stocks which are cheap relative to their earnings. These stocks are undervalued relative to other stocks due to the market’s overreaction to bad news. This gives value investors the opportunity to take advantage of the low prices to make huge profits when the prices revert back to their fair value. However, a value investment strategy is not without risks. A cheap stock can become cheaper if the company fails to improve, manage its cost and innovate. This is known as a value trap, which is every value investor’s nightmare. Hence, value investors take on this risk for the chance to be rewarded with huge profits in the long run. Their investment horizons are usually at least 3 years and they will close their positions once the price is no longer attractive relative to its fair value. How do we select value stocks? From an investment universe of 500 stocks in the S&P 500, I select 50 stocks (top 10%) within the universe with the lowest price to earnings ratio (PE ratio). A low PE ratio implies that the stock is trading at a low price relative to its earnings which is an ideal candidate for value investors looking for cheap deals. I equal weight each of the 50 stocks in the portfolio to reduce the concentration risk of the portfolio i.e. each stock in the portfolio has a target weight of 2%. The weights will deviate from 2% as the prices of stocks within the portfolio go up or down. If the weights deviate too far, the stock is re-balanced back to it’s target weight. I’m not interested in how a single stock or a few stocks perform, but how the value investment theme performs. This means looking at a group of stocks (10% of the universe) with a low PE ratio and finding out if it outperforms the market as a whole. Another key aspect of the portfolio construction is sector neutrality. A stock that is cheap in the tech sector may be considered expensive to a stock in the utilities sector based on PE ratios. It does not make sense to compare the PE ratio of stocks between sectors because each sector has its own unique characteristics. Hence we select the stocks with the lowest PE ratios within each sector to ensure that we do not end up with a bias towards sector that tend to have lower valuations. The plot below shows that the portfolio does not tilt towards any specific sector with every sector having a weight of under 20%. Simulation Results The simulation results show that the value investment strategy has an annual return of 8.9%. The strategy outperformed the S&P, making a cumulative return of 210%. While the strategy’s total returns are high, it’s comes with higher risk. It’s annual volatility is 19.7% vs the market’s historical volatility of 17%. In addition, there are certain periods where the strategy performs worse than the market. If we compare the performance since 2013, the simulation shows that while the S&P makes 130%, the strategy only makes 80%. That’s a whopping 50% difference in performance. An investor that bought value stocks since 2013 will not be too happy! Conclusion Value investing has shown promising results overall, providing exceptional returns during certain periods in the past. Cheap stocks do have the tendency to outperform expensive stocks. However, there are still risks involved where the investor might not be rewarded for taking on the value risk premium, such as the period from 2013 onward. This goes to show why most successful value investors have a long investment horizon from 3 years onward. This gives them ample time to ride out periods of under-performance for the chance of making huge profits in the long run. Find out what Datascience Investor has to say about value investing: https://www.datascienceinvestor.com/post/is-value-investing-still-relevant-or-is-it-dead
Admin · 4 years, 10 months ago
How Do You Trade Trends in the Market?
The turtle strategy was used by one of the most successful trend followers in history, Richard Dennis, who borrowed $1,600 and reportedly made $200 million in about ten years. The strategy states that when the price of instruments hits a 3 month high, we buy. And when the price of an instrument hits a 3 month low, we sell. The strategy provides an effective form of capital protection for investors yet allows investors to participate in the upswings of the market.   Backtesting the turtle strategy To test the effectiveness of the turtle strategy, I simulated the strategy using a backtesting framework built with Python. The simulation works by: Pulling historical prices of the S&P 500 ETF (SPY) into my database. Building the trading signals by using the rolling maximum/minimum of a 3 month window period. Submitting orders whenever a buy or sell signal was generated. Generating plots to show the results of the backtest. The plots below show the results of my simulation. The top plot shows the price of the S&P 500 (dark blue line) sandwiched between it’s rolling maximum (light blue line) and rolling minimum (purple line). Following the rules of the turtle strategy, when the price of the index crosses above it’s rolling maximum, we go long on the index. When the price of the index crosses below its rolling minimum, we close our long position. The profit and loss (PNL) value of the portfolio is shown in the lower graph. $1 million dollars invested in 2002 would result in slightly over $2.5 million today. While the returns may look unimpressive, traders typically use highly leveraged financial instruments such as futures contracts to magnify gains. This is possible because of the lower risk of the strategy which provides downside protection. For example, during the 2008 recession, the portfolio only lost 18% vs the market (down 56%). To most investors, however, this strategy would not be appealing because of its high turnover. We can see that to employ this strategy, investors would need to frequently buy and sell the index. This is highly inconvenient and would result in high trading cost.   Can we do better? The original turtle strategy used a 3-month signal horizon to trade the market (i.e. they bought the index when it’s price hit a 3 month high and sold the index when it’s price hit a 3 month low). With a computer, we can easily run the strategy using different parameters for the signal horizon and figure out the set of parameters that results in the best performance. Here are the results. The metric I used to gauge the performance of the strategy is the Sharpe ratio, which measures the return to risk ratio. The higher the Sharpe ratio, the higher the return of the strategy for a given level of risk. The results show that the strategy using 80 days for the maximum rolling window and 110 days for the minimum rolling window has the highest Sharpe ratio of 0.26. Now let’s re-run our simulation using these parameters. The results show that $1 million dollars invested in 2002 would result in slightly over $3.5 million today. That is a whooping 170% higher than the original turtle strategy. The frequency of trades is also much lower, making it easier to implement and incurring lower transaction cost. When it comes to investing, everyone has their own styles and strategies. I rely on systematic strategies because I can simulate their performance and convince myself that they can outperform the market.
Admin · 4 years, 10 months ago
Navigating the Trade War Between US and China
Thanks to Trump's indomitable will, the markets have been thrown into chaos for the past year with no breakthrough in sight. How can a fundamental investor navigate the waters and position ourselves to make money? In the next few weeks, I seek to answer 3 key questions that every investor should be thinking about right now: Do we remain invested? Which sector is best? Who is the winner? Do we remain invested? People often quote Warren Buffett but never truly understand how to apply his principles in investing. The first thing we have to understand as investors is that the market is dynamic, and every cycle is unique; what's important is your ability to analyse the facts and weigh the risks before you proceed. So, when Warren Buffett said "Be fearful when others are greedy and greedy when others are fearful", what does he really mean? In a greedy bull market, at what point do you say enough is enough and get out? When Buffett says to be fearful, does he mean we should have the fear of missing out? Some funds prefer to drown out the noise and follow a rational, quantitative strategy - you can't go wrong if you just follow the trend, right? But as a fundamental investor, we should seek to predict the trend, and the only way to do so is to have a view, a conviction. So here's my view on the US-China trade war (I'll operate under the assumption that our readers here are already up to date with the specifics): For the longest time, it has been the DNA of US tech companies is to be in creme de le creme of the value chain. Apple is a classic example - they have not manufactured a single thing in the entirety of the company's history, all the components and final assembly of the iPhone is built in South Korea, Taiwan, and of course China. The simple reason is creating software and designing hardware gives you the highest margins, it is completely asset-light (high recurring FCF generation), and by diversifying your supply chain, you actively reduce your R&D burden and increases your bargaining power with suppliers. We often see Apple's suppliers make razor thin margins, spend millions on R&D only to fail to make the cut as the next supplier, and deal with inventory problems as they expand too fast on production capacity only to be disappointed with low purchase orders. Yet, these companies are only able to do that because 1. labour is cheap in China (workers are literally begging to work over-time to get extra pay), 2. the logistics network has been perfected over the last decade and manufacturers have found a way to increase cost-efficiency in any way possible, and well, 3. the US doesn't want to deal with all the environmental pollution that comes with manufacturing so let's have someone else do the dirty work. The proof is in the pudding - Apple has sustained a ~40% gross margin since the dawn of day, while other smartphone companies are still making a meager 5-10%. Apple is only one of many examples, we can look no further from America's iron grip on the Semiconductors industry (US owns 100% of the global CPU market with Intel & AMD).  Yet, Trump's tariffs is a regressive policy that will destroy the benefits of such globalization - any production relocation will take time (just setting up a factory could take 6-12 months) and all the cost-benefits for US companies discussed above will pretty much be moot. Some components manufacturers I've talked to in my time admittedly would rather take on a 25% tariff than move their production base out of China. So what is Trump thinking by imposing tariffs? What good comes out of relocating manufacturing to the US, and does it really create more jobs? Is toiling away in a factory the American dream? Furthermore, other players like Samsung assemble their smartphones in Vietnam/India, while Huawei hardly has any market share in the US so the tariffs will only serve to graze their ego. Way to go at leveling the playing field for everybody else, Trump. However, when the tariffs on China were announced - the US conveniently put Apple in the tariff-free category. On the surface, Trump may be threatening to throw all of us back into the stone age, but it is clear he knows what he's doing. Protectionism is well and alive. So that tariffs are clearly not an effective way to shut down China - China could simply slap retaliatory tariffs, costs will increase for consumers globally, demand slows down and so does the economy. Furthermore, while tariffs can fuel the US budget for fiscal spending or tax cuts to cushion the impact, they ultimately follow the law of diminishing marginal returns - as the trade deficit between US-China closes, so does the tariffs collected, and now you need the Fed to cut interest rates to prevent a recession. What a complete waste of everybody's time. What do you do when your Plan A doesn't work? Go to Plan B. The US announced in May that Huawei (China's crown jewel) will be blacklisted on the basis of undermining US national security. This really puts Huawei in a bind because the blacklist covers everything under the sun that has at least 25% US origin in their production/formulation. This means that 1. all US products/services are basically cut off from Huawei, 2. any product/service around the world that have some form of raw material / IP sourced from the US are also in play - violation of the blacklist could lead to similar sanctions imposed. So Huawei can't produce any network equipment or smartphones anymore, because 1. US controls pretty much all the key components (Intel, Qualcomm, Broadcom, Xilinx) that cannot be readily replaced by their Chinese counterparts. 2. US controls a lot of IP, so China can only dream about producing their own chips - EDA tools used for chip design supplied by Synopsys/Cadence are now cut off from Huawei, and ARM being unable to license their IP for Huawei's Application Processors limit them in the same capacity. 3. US is light years ahead in software, and Google's compliance means their Android OS which runs 80% of the world's smartphones is no longer available to Huawei in the form of key updates and apps like Gmail, Maps, YouTube etc. Make no mistake, Huawei's 1,000-strong team of software engineers has worked singularly and tirelessly to create their own OS (now dubbed HongMeng) even before the tariffs were in sight, to no avail. When ZTE first got banned, many investors balked at the idea that it would implicate Huawei. Afterall, Huawei is a completely different beast than ZTE, controlling ~25% of the global networking equipment market, and also 13% of the global smartphone market share (and recently overtook Apple as #2) - choking Huawei would be the same as choking the growth drivers of US companies which have seen a steady increase in % revenue mix from China. No single company could snap up Huawei's market share that quickly, and China isn't going to just sit quietly while being roasted. Sure enough, China has announced their own blacklist, targeting any firms that fall under China's definition of engaging in "unilateralism and trade protectionism". Not to mention, China has a history making life difficult for any firms that don't abide by their law, such as imposing tough bureaucracy, compliance checks, outright export control / shutdown of operations. Winter is coming, and I wouldn't like to be Apple, Starbucks or FedEx, just to name a few. Oh, and has everybody forgotten that China controls 70% of the global supply of rare earths? Rare earths are essential to the production of key components such as Semiconductors and Batteries (no wonder China controls >50% of the global EV-battery supply chain, and is the world's No.1 producer of Electric Vehicles). China could very well go down the path of Mutually Assured Destruction (in short, MAD-ness) - if Huawei can't produce, so can't you, World.  However, let's cover all bases. If Trump's aim is to truly decouple the world from China, then someone must fill the void. If we look through our history books, the US has plenty of capacity to be self-sufficient, but they chose not to be. Case in point, the US has been a net importer of crude oil for 75 years until recently, and when they decided to become a net exporter, down came the oil price. If you think about crude oil as a precious and depleting natural resource, you'd want to keep as much of it for yourself as possible. The US soil has enough oil reserves saved up over the years for them to be the last man standing. We could apply the same logic with rare earths - the US was the leading global producer of rare earths from the 1960s to 80s before they shifted out, and current domestic production is only 1% of what the US is capable of. Talk about planning ahead. This current model will work in the favour of the US indefinitely, why risk it now?  Again, we keep in mind that Trump has shown willingness to make tactical adjustments to his game - Huawei has been given a 90-day reprieve on the ban, and with that China has been holding back on opening Pandora's box. So Plan B isn't the best idea, how about Plan C? The Trump administration has stepped up efforts on restricting academic visas and increasing scrutiny on Chinese researchers working in the US. China fires back and issues travel restrictions to citizens travelling to the US, and we are already seeing a decline in revenues for US consumer companies such as PVH Corp. or Tiffany & Co. What's next? Does Trump have a Plan D? By now you should be seeing a pattern. Trump isn't fumbling in the dark, he's throwing more chips into this big game of chicken. These are negotiating tools to begin with, and his goal was never to close the trade deficit, or support the farmers (well 51% of his votes needed to come from somewhere, right?). The true aim is to cripple China, who has been growing at blinding speeds and spearheading innovation beyond the likes of US companies (Huawei in 5G, Alibaba in e-commerce, AI from start-ups like Megvii/SenseTime etc.), all on the back of "stealing" US IP, and having unfair trade practices such as giving domestic companies free subsidies, interest-free loans, tax rebates etc. Reading back-and-forth on the trade deal debate, it seems the Trump administration had wanted China to put in writing to block IP transfer of any sort, and ban outright government support to domestic companies - something China claims to infringe on their sovereignty (and let's be honest, Chinese firms would go out of business in a matter of days without the lifelines given by the government at the rate that they are burning cash). Then we take a step back, and we see Trump isn't just picking a fight with China, he's been slapping tariffs on everybody else - the EU, Mexico etc. In EU's case, to cripple Airbus which has been winning the duopoly with US Boeing with what Trump claims to be the help of subsidies from the EU (how about asking Boeing to stop driving their planes into the ground?). In Mexico's case, illegal immigrants and crime. So it is clear that the tariffs are just Trump's method of getting countries to give him what he wants. It's a terrible idea, but it's also the only one he's got.    Let's recap  Trump doesn't want to plunge the world into recession. All is well if countries get bullied into a trade deal, America wins again. If Trump's big gamble doesn't pay off, he's quite likely willing to take a step back. Then the issue here is that China isn't any other nation, and it sure isn't like the country it was 10 years ago. Since Xi's consolidation of power, he's given himself a lifetime on the iron throne. While Trump has limited time, even on the assumption that he gets re-elected in 2020, Xi can outlast him thanks to a convenient constitutional revision. Furthermore, the Chinese economy has never been stronger on the back of Xi's anti-corruption campaign and nationwide book-cleaning / deleveraging. Fun fact: China is the largest creditor of US treasuries (17.3% of total foreign-owned debt), and the Chinese poured in US$46bn/29bn of FDI into the US during 2017/18 compared to the ~US$13bn the US invests into China each year. China has become a proud nation and its people have a strong sense of nationalism with an unrivaled control over money flows. In the long-run, China is on track to overtake the US in technology - the US graduates 50,000 engineers a year, while China is churning out 260,000. Why should China take a knee in a race they are poised to win? As Xi's latest visit to Jiangxi Province would imply, China's new 15-year "long march" has just begun, and it seems like Russia's coming along. Ultimately, the likely scenario is that a trade deal will happen. Trump will concede on some points in the trade deal, and China would have given up a big chunk of their growth at the end of it. However, until then, there's no way of telling when it will happen - my best guess would be by end-3Q19, just as Trump prepares for his 2020 campaign. What does this means for us fundamentalists? If you haven't gotten out of stocks, take some pain and get out. By "get out", I mean everything - stocks, bonds, alternatives, nothing is safe until it is. If we just look back over our shoulder, we have another 15% downside to the recent low of Dec-2018, and that was before additional tariffs came into the picture. The silver lining, however, is that the storm should soon be over and you'll have plenty of time and upside to play catch up. For those who got out early, sit back, relax and enjoy the show. It's time to think about where you want to invest when the time is ripe.  Disclaimer: This post is the culmination of public information and progressive news reports, meant to reflect my personal course of action. Readers should take the time to fact check and review my arguments for themselves before following my recommendation.
MG · 5 years, 3 months ago