Backtesting Stock Strategies using Shiny

Ansel Andro Santos
Posted on Feb 4, 2018

Introduction

The two main schools of thought in investing are fundamental and technical analysis. Fundamental analysis inspects a company's financial statements and business model to make an assessment of a stock's fair value. On the other hand, technical analysis looks at the price action and volume of a stock to predict its next move.

Technicians use a combination of graphing methods and technical indicators to decide whether to buy or sell a stock. This takes time and experience to learn and master, with most people giving up after experiencing huge losses.

For the shiny application that I made, users can backtest strategies on three commonly used indicators, namely, Simple Moving Average (SMA), Relative Strength Index (RSI) and Slow Stochastic Oscillator. People who are new to technical trading can use my app to experiment strategies which use the indicators mentioned.

UI and Server Build

I built a simple User Interface (UI) for the app as a full suite of options might overwhelm someone who is just starting his journey into becoming a seasoned technical analyst.

I created a UI with three main panels. The first is where you select the dates and the stock you want to test. The second and third panels are for inputting the entry and exit indicator with its respective parameter. The selection of stocks is limited to the top 100 members of the S&P 500 and a few Exchange Traded Funds (ETFs). The app will buy the stock when the indicator is above the value set on the entry slider bar, and will sell the stock when the value of the indicator is below the value set on the exit slider bar. It is important to note that the formulas were set such that the strategy will never short the selected stock. Lastly, choosing yes for 'Long at day one' will start the simulation with a position on the selected stock.

Once you have set the options for your backtest, you can press the Run Strategy button to commence the calculations!

After you click the button, three graphs will show up. The first graph shows the stock price with the indicators selected; the other two graphs display the strategy being compared to the stock itself and the SPY ETF.

The chart above is an overview of how the backend of the application works. When the user clicks the run strategy button, the server pulls stock data using the quantmod package. After getting the price data, the TTR package is used for computing the indicators. Dplyr and tidyr are then utilized for arranging, cleaning and analyzing the price and indicator data. Lastly, the graphs are assembled using rbokeh.

Interesting Results using the App

Before I end my blog post, here are some things I found useful in trading using technical indicators:

It is very hard to beat an upward trending market using most backtest strategies; you’re better off just holding on to your stock or ETF.

On a sideways market (2004 to 2005), it was easier to find a strategy which outperformed the S&P 500. Technical indicators work well on these scenarios because you have less risk of getting left behind by a bull rally.

For an expensive market like the one we have today, the 100 day SMA exit strategy will substantially reduce your losses in case of a huge decline in stocks. The 100 day SMA is a psychological support for most people and a breakdown of the 100 day SMA is usually a sign of an overall change in sentiment. The euphoria of having positive gains for people who bought over the past 100 days reverse at this point and when they see their retirement accounts turn from green to red, a sudden rush to the exit happens. This will then add to the selling pressure, bringing stock prices even lower.

About Author

Ansel Andro Santos

Ansel Andro Santos

Ansel has a Master in Applied Mathematics from Ateneo de Manila University. He worked in the investments industry before deciding to become a data scientist. His interest in data science started while making the factor based investment strategy...
View all posts by Ansel Andro Santos >

Related Articles

Leave a Comment

Avatar
proxy server list September 9, 2018
Hi,I log on to your blog named "Backtesting Stock Strategies using Shiny | NYC Data Science Academy Blog" regularly.Your writing style is witty, keep it up! And you can look our website about proxy server list.

View Posts by Categories


Our Recent Popular Posts


View Posts by Tags

2019 airbnb alumni Alumni Interview Alumni Spotlight alumni story Alumnus API Application artist aws beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Big Data Book Launch Book-Signing bootcamp Bootcamp Prep Bundles California Cancer Research capstone Career Career Day citibike clustering Coding Course Demo Course Report D3.js data Data Analyst data science Data Science Academy Data Science Bootcamp Data Scientist Data Scientist Jobs data visualization Deep Learning Demo Day Discount dplyr employer networking feature engineering Finance Financial Data Science Flask gbm Get Hired ggplot2 googleVis Hadoop higgs boson Hiring hiring partner events Industry Experts Job Jon Krohn JP Morgan Chase Kaggle Kickstarter lasso regression Lead Data Scienctist Lead Data Scientist leaflet linear regression Logistic Regression machine learning Maps matplotlib Medical Research meetup Networking neural network Neural networks New Courses nlp NYC NYC Data Science nyc data science academy NYC Open Data NYCDSA NYCDSA Alumni Open Data painter pandas Part-time Portfolio Development prediction Prework Programming PwC python python machine learning python scrapy python web scraping python webscraping Python Workshop R R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest recommendation recommendation system regression Scrapy scrapy visualization seaborn Selenium sentiment analysis Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Tableau TensorFlow Testimonial tf-idf Top Data Science Bootcamp twitter visualization web scraping Weekend Course What to expect word cloud word2vec XGBoost yelp