Basic Interactive Stock Analysis Template
Tags: Visualization, Finance, Stock Market, Personal Finance, Data Science

Notebook replicate of “Why Python is huge in finance? by Daniel Roos”

Source: Unsplash @Markus Spiske

Background

After listening to the talk from Daniel Roos on Why Python is huge in finance?[1], I’m intrigued how he used Jupyter Notebook to build interactive charts that back-test portfolio and perform historical simulation. Hence, I tried to replicate his notebook and try to build into my stock analysis template.

The analysis breaks into 3 parts.

Stock Scraping using yfinance Portfolio return Backtesting using Interactive Chart Correlation Plot & Risk-Reward Chart Monti-Carlo Simulation of Portfolio Return

The code can be found in my GitHub repository here:

https://github.com/Chiu-Huang/Simple_stock_analysis/blob/master/Basic_Interactive_Stock_Analysis_Template.ipynb

Let’s get started!

Step 1: Stock Scraping

It’s pretty straight forward. We basically plug in the ticker as parameters and we can get the whole history of the particular stock.

Roos uses cached_data to avoid repeatedly downloading the stock information again. All stock info would be stored in cached_data in a dictionary format, so that we could save it/reuse them later.

Step 1A. Data Preprocessing

It’s probably a good practice to backfill any missing values inbetween the dates, and chop off data so that selected stocks have the same length.

Backfill is usually used in time-series as it doesn’t spoil the data from the future to the past.

Step 1B. Visualizing the data

Let’s plot the data to see if there’s any obvious mistakes that we made in previous steps.

Stock prices over time

It seems fine with me with no obvious breaks and gaps between data. Also, all stock data is available at t= 0 which is good.

Step 2: Portfolio return Backtesting using Interactive Chart

For simplicity, Roos uses 1/N equal-weighted portfolio, meaning that each stock has 1/N weight. Feel free to build your own portfolio by replacing returns[‘PORTFOLIO’].

Portfolio Return is in Pink, basically Square.inc mainly drives the performance of the portfolio. Gold is lagging compared to all other Tech since 2016

To examine whether our portfolio strategy works, we need to test our portfolio across different time-periods/ holding-time-horizon, and the interactive plot below helps us visualize the process easily by changing the sliders of start_period and time-horizon of the portfolio.

Backtest from 2014–04–03 to 2015–04–03, None represents our portfolio

In one year period, portfolio roughly gained 7%, which was in par with the S&P 500 (SPY).

None represents our portfolio, back-test for 2–year-period

For 2 year-period from 2014 to 2016, we could see that stocks were more volatile, especially during election time, there was a big surprise that president Trump won the election and stocks plummeted and strongly recovered after it. The portfolio outperformed the market by ~6% over 2 year-time-horizon. Let’s see the impact if we drop IBM, FB, and SPY out of our portfolio.

3 tickers are removed from the portfolio.

We can see that our portfolio fluctuated more due to higher concentration on tickers, and portfolio performance dropped significantly after removal of the tickers.

Maybe more periods should be tested, but you get the idea, using the chart can quickly tell when your portfolio works and when doesn’t with some market context. The main benefit of this chart is that we could easily add/subtract stocks from our existing portfolios, and test-out their stand-alone impact. It seems useful in entry/exit decision making process.

Step 3: Correlation Plot & Risk-Reward Chart

We should examine the correlation between stocks as well. We want diversification, but if all stocks goes in same direction, it loses the point of mitigating risk while maintaining the same expected return.

Correlation plot of the stocks in portfolio

It turns out the stocks are highly correlated(above 0.5). It makes sense because they are all tech-stocks, and they are large in size, meaning that they have massive influence on S&P 500 (SPY) performance. Probably I have to rethink about the portfolio composition. Let’s switch gears to risk-reward plot of the stocks.

risk-reward plot of the stocks

IBM seems to be a inferior from this plot. IBM yields average return of ~1% while fluctuating with the standard deviation of 23% every year. SPY is the least risky (low volatility) asset, and the recent rally (2018–2020) really drives the SPY average return up from historically 7% to roughly 15% in this 7-year time period. Tesla is super risky but may yield high expected return.

Step 4: Monti-Carlo Simulation of Portfolio Return

From step 1– 3, we basically find that we need to consider more stocks (increasing n to lower volatility) and select stocks from different industry (lower non-systematic risk) to avoid such a highly correlated composition of stocks.

However, there’s nothing really concrete. Hence, we need simulation to see how our portfolio actually performed in numerical terms if history repeats in similar favour (similar return distribution).

Basically, we randomly select the return from past and form synthetic returns for all the stocks over time-horizon (k = 60 days in this case), and we calculated our portfolio based on those synthetic returns. In this example, we simulate for 1,000 times, and get the confidence interval of our portfolio value after 60 days.

Simulation result on top Panel; Quantile Return on bottom Panel

Our portfolio is likely to have 1.5% on average over 60–day-period, and the return could lie between -12% and 22 % in a 90% confidence interval.

The simulation definitely provides some useful information that if bad things happen to my portfolio, similar to historical bad events (down-case), then I could face a -10% cut on my portfolio, while if good events (up-case) happen, then I could happily accept 22% return.

Conclusions

The talk from Daniels Roos provides a great starting point for quick, dirty stock analysis in our portfolio. I particularly like the interactive plotting function that I have never seen before. In the following posts, I would probably dig deeper into how this interactive plotting can help us in stock analysis, as well as the simulations.

If you like the content, please hit the clap button so the articles can circulate around the community! Thanks.

Reference

[1]: “Why Python is huge in finance? by Daniel Roos” at https://www.youtube.com/watch?v=kBwOy-6CtAQ