9 months ago • 2 mins
There’s a reason hedge funds hire analysts who can write code: they can build profitable trading strategies that run on autopilot. As it turns out, ChatGPT can write code too. So I tried to get it to build me a profitable strategy in TradingView.
I asked ChatGPT to write the Pine Script code for a bunch of strategies based on technical analysis – for example, the one in the chart. This strategy buys the S&P 500 when it finishes a week above its 21-week exponential moving average (EMA, yellow line), and moves back into US dollars when it finishes a week below it. It’s a simple trend-following strategy – the EMA is just a “rolling”, or continually updating, average of the past 21 weeks of price movement, with more weight on the more recent weeks. In other words, it’s more responsive to changes in buyer momentum than a simple moving average would be.
After ChatGPT gave me the code, I pasted it into the Pine Editor section on a fresh TradingView S&P 500 chart. I then clicked “add to chart”, and TradingView gave me… an error. I then copied and pasted that error back into ChatGPT so it could fix it. This back and forth went on for some time, until eventually, I got the code to work. So here it is:
I backtested the strategy in TradingView since the year 1883 – which is as far as the index’s data goes back. I also added in a trading fee of 0.1% of the position size per trade to make it seem more like real-world trading (this would depend on your broker). A $1,000 investment in the strategy would’ve earned over $500,000 in profit over the past 140 years, or grown by about 4.6% per year.
Of course, I tried to improve the strategy by making it more complicated – and that’s when ChatGPT didn’t code so well. But here’s the good news: you’d have earned 4.95% a year by simply buying and holding the S&P 500 over the same period.
Disclaimer: These articles are provided for information purposes only. Occasionally, an opinion about whether to buy or sell a specific investment may be provided. The content is not intended to be a personal recommendation to buy or sell any financial instrument or product, or to adopt any investment strategy as it is not provided based on an assessment of your investing knowledge and experience, your financial situation or your investment objectives. The value of your investments, and the income derived from them, may go down as well as up. You may not get back all the money that you invest. The investments referred to in this article may not be suitable for all investors, and if in doubt, an investor should seek advice from a qualified investment advisor.
/3 • Your free quarterly content is about to expire. Uncover the biggest trends and opportunities. Subscribe now for 50%. Cancel anytime.