SHASHANK KHANNA
  • Blog
  • Gallery
  • About
  • Contact

Stock Analyzer - Modeling, Analytics, and Plotting

 

Purpose

To develop an easy to use utility tool that downloads historical prices of an asset and then allows us to perform various statistical analysis along with charting. 

What does it do?

Before we get into the details, I would like to mention the functionalities provided by this tool. Its essence lies in the ease to use and a one-stop shop for all the basic tools data modeling, analytics, and plotting. 

Here is the list of functionalities our Stock Analyzer is capable of:
  1. Download historical data for a given publicly traded stock ticker
  2. Compute basic statistical points on this data -ex. Mean, Variance, Standard Deviation, Volatility, Returns, etc. 
  3. Plot daily close price
  4. Plot daily returns
  5. Plot daily returns against an Index return, ex. SNP 500
  6. Plot daily prices in a Candlestick chart along with Volume
  7. Calculate and Plot user-defined on-the-fly moving averages
  8. Compute Linear regression by applying ordinary least square (OLS) model against SNP 500
  9. Display and return linear regression values, such as R-Squared, F-Statistic, BIC, Standard Error, etc.  
  10. Plot Linear regression model

Let's Begin

For all the examples below, I will use Tesla stock (Nasdaq Ticker = TSLA). 

In order to initiate an object of this class, we need to pass a Stock-ticker. As soon as we pass a ticker to the constructor, appropriate calls are made to Quandl/Yahoo/Morningstar APIs to fetch historical prices & volume data for this ticker. By default, the calls are made to collect last 252 trading days data; but one can tweak that by also providing a number to optional hist_start_date parameter. Another optional parameter is refresh, which does not make calls to the web if previously downloaded historical data is already stored in local files. 

Further, along with downloading data for this ticker, additional calls are made to download data for SNP 500 Index. As we will see later, this is needed to perform linear regression and various charting options. 
Download historical Prices & Volume from Web

Output after downloading date

Basic Statistical Analysis

Now, we have the data, so we can perform the basic statistical data analysis by leveraging Pandas' useful functions for Mean, Standard Deviation, Daily Returns. 
Compute basic statistical properties

Output for basic statistical properties

Plot Daily Prices

plot function of this class provides a convenient utility to draw chart for daily close prices of the stock. My implementation is based on Bokeh library; but if we provide optional parameter useMatplot then the chart is plotted using the famous Matplotlib. I personally prefer Bokeh as it provides interactive charts -try it out! 
Generate plot for Daily prices

Picture

Plot Daily Returns

plot_returns function of this class provides a convenient utility to draw chart for daily returns of the stock. Just like plot function (above), it also provides ability to draw chart either using Bokeh or matplotlib. 
Generate plot for Daily Returns

Plot returns against SNP 500

plot_returns_against_snp500 function provides us the utility to visualize returns of the Stock against the returns of SNP 500 index. Similar to the above two functions, it provides plot in both matplotlib as well as the interactive web-based browser chart using Bokeh. 
 Generate plot for Daily Returns against that of SNP-500

Plot Candlestick chart with Volume

Candlestick plots are the most popular charts when it comes to visualizing stock prices grouped under fixed intervals. Stock Analyzer's plot_candlestick function provides this ability to visualize these historical prices in a candlestick chart. Like other plots show above, we will go through the code later in this blog. 
Generate Candlestick chart with Volume

Picture

Plotting dynamic Moving Averages

One of the most convenient use of my tool Stock Analyzer, is to dynamically generate moving averages and have them plotted for visualization. plot_moving_averages method takes in below three optional parameters:
  • Window1: An integer specifying number of days for which we need to generate Moving Average 1 - default value is 14 days
  • Window2: An integer specifying number of days for which we need to generate Moving Average 2 - default value is 42 days
  • useMatplot: Boolean flag suggesting whether to use matplotlib or Bokeh for charting - default is to use Bokeh.
Below is how easy these commands can be invoked and we get these plots.
Generate Moving Averages and Plot them along with daily Price

Code to calculate moving averages

Linear Regression against the Index

We will now apply Linear regression on these returns and see how strong is the relationship between SNP 500 returns with TSLA returns. 

Below is the source-code we use to apply Linear regression on these two set of values. 
Apply Ordinary Least Square model to perform Linear regression

Once the OLS model is applied, we can go ahead plot the regression values using the below function.
Plot OLS on Returns

Finally, one does not need to code above and just use the below functions to apply linear regression, plot it and retrieve Stock's Alpha and Beta along with model's R-Statistics, F-Statistic, etc - simple to use!
Apply Ordinary Least Square model to perform Linear regression

Picture
Output Stock's Alpha and Beta against the Index

Picture

Source Code

For complete source-code, please check this project at my GitHub repository @ https://github.com/shashank-khanna/Stock-Analyzer

    Author

    I am a passionate, driven polyglot programmer and architect with a knack of solving complex problems in quick and efficient way.  Along with programming, software development, financial products, and management expertise, I also bring skills in statistical modeling, empowering me to work on challenging projects that require combination of software development and quantitative analysis.

    Categories

    All
    American Option Prices
    Black-Scholes Method
    Blockchain
    Bokeh
    Brownian Motion
    Cryptography
    Derivative Pricing
    European Option Prices
    Gaussian Process
    Linear Regression
    Matplotlib
    Monte Carlo Simulations
    Monte-Carlo Simulations
    Numpy
    Ordinary Least Square (OLS)
    Pandas
    Put-Call Parity
    Python
    Sha-256 Hash
    Statistical Analysis
    Stochastic Process
    Stock Analyzer
    Time Series Models
    Wiener Process

    RSS Feed