Stockstats — a handy, stocks-oriented pandas DataFrame wrapper | by Eryk Lewinson | Towards Data Science

In this post, I wanted to briefly describe another interesting library I recently came across — stockstats. It is a wrapper library on top of a pandas DataFrame and its main goal is to provide instantaneous access to a variety of measures and technical indicators related to stock prices. Let’s jump right into it!
Before being able to see what stockstats has to offer, we need to import the libraries and download the data.
Using yfinance, we download Apple’s OHLC prices (+ volume) from 2020. For more details on the library, please refer to my other article.
This volume of data will be more than enough to showcase the features of stockstats. The main class of the library is StockDataFrame, which is a wrapper on top of the pandas DataFrame. We can easily convert the latter to the former using the following snippet.
stock_df = StockDataFrame.retype(df)stock_df
So far, nothing really changed and the new DataFrame contains the very same columns it had, just the names are in lowercase now.
stockstats offers quite an interesting approach to calculating different metrics— we just need to select the columns we would like to see, and the library will use underlying methods to calculate the requested values.
Let’s start with some basic information we could use for the analysis — stock returns.
stock_df[["change", "rate", "close_-1_d", "log-ret"]]
Using normal pandas way of selecting columns, we obtained the requested values, which is quite handy. Very briefly, a short description of the columns:
change / rate — these are the simple returns, that is the daily percentage change between the stock prices. Values are expressed in percentages.
close_-1_d — this is the price difference between time t and t-1. We will get back later to this special way of requesting values is stockstats.
log-ret — the log returns.
It is also worth mentioning that when we request those columns as we did above, we obtain only the requested output. However, the very same columns were appended to the source object stock_df.
In the subtitle I promised technical indicators, so let’s create a very simple one — a 10-day simple moving average (SMA).
stock_df[["close_10_sma"]]
We once again used the special way of requesting custom metrics. To fully understand it, we can look at the requested column name using the following schema {columnName_window_statistics}, where:
columnName — the name of the column on which we want to calculate the metric. In the example above, we used the close price.
window — how many observations to take into account. We used a 10-day window above.
statistics — which measure we want to calculate. In the example above, we used the simple moving average (sma). For a list of all available metrics and their corresponding column names, you need to check the GitHub repo of stockstats.
We will now combine a few elements we have already seen to create a simple plot of the close price and two moving averages.
On a side note, the StockDataFrame still retains the functionalities of the pandas DataFrame. So using a single square bracket to request a column would result in a pandas Series. And we can use pandas indexing to slice the DataFrame, for example:
This plot would be very similar to the first one, but it would only contain the data from 2020–06–01 onward.
Another TI we can easily calculate and plot are the Bollinger Bands.
There are many more technical indicators available, such as the Relative Strength Index (RSI), the Moving Average Convergence Divergence (MACD), the Stochastic Oscillator, William’s Overbought/Oversold index, the Average True Range (ATR), and many more.
All of those indicators use some hard-coded values for the windows, which are based on the industry standards. For example, the Bollinger Bands are calculated using 20-day moving average (BOLL_PERIOD) and the bands are at 2 standard deviations (BOLL_STD_TIMES). We can overwrite those by accessing the corresponding elements of the StockDataFrame.
Lastly, often when playing around with Technical Indicators we want to create signals — an indicator whether this is a buying/selling moment. Some of the simple and popular strategies involve checking whether one value crosses above/below another one. stockstats also offers such functionality.
stock_df["close_xu_close_20_sma"]
We obtain a Boolean Series indicating whether the close price crossed above the 20-day SMA of the same close price. We can also request more complex crossovers, such as a crossover of two SMAs.
stock_df["close_10_sma_xd_close_50_sma"]
In this case, we get a signal when the 10-day SMA crosses below the 50-day SMA, both calculated using the close price.
stockstats is definitely an interesting library, which can come in handy while doing some quick analyses of stock prices. It also offers a unique way of calculating the requested metrics by selecting the appropriate column names. It might take a while to get acquainted with the schema used for accessing combined metrics.
However, the library is rather poorly documented. Most of the information can be derived from the README file in the repo, or just by inspecting the code directly. But this also offers a possibility to have a peek at how the technical indicators are calculated, which is a good learning experience.
stockstats is a wrapper on top of a pandas DataFrame and offers easy access to a variety of stock-related metrics.
the library offers a wide range of popular technical indicators, such as SMA, EMA, RSI, MACD, etc.
you can calculate the metrics just by calling the desired column name and all will be handled under the hood.
You can find the code used for this article on my GitHub. Also, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.
If you are interested in learning about how to use Python for quantitative finance, you might want to check out Quantra (disclaimer: an affiliate link), which offers a variety of different courses on the topic.
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
If you liked this article, you might also be interested in one of the following: