Backtesting Stock Strategies using Shiny

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 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

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

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI