This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.

# Trading Index (TRIN): Formula, Calculation & Strategy in Python – Part II

Contributor:
QuantInsti
Visit: QuantInsti

Learn the definition of TRIN with Part I in this series.

## Example of TRIN

Source: CFI

According to the example above, a rising TRIN indicates a bearish market, whereas a falling TRIN indicates a bullish market. The example above shows that the traders who bought in the market when the TRIN value was above 3.00 fared well because it was an oversold situation. The traders in the oversold situation must have got the benefit from a rise in the supply of stocks when they bought. Also, the traders who sold in the market based on values below 0.50 in which there was an overbought condition, must not have had a profitable time.

The SMA or moving average smooths the data series and makes it come into a range that is needed to generate an overbought or oversold signal or value in the market.

We will now find out the calculation of TRIN value with the help of Python codes.

## Calculation of TRIN in Python

Let us see how to calculate the TRIN value with Python to analyse the condition of the market. Although if you wish, you can learn more with our blog article on building technical indicators in Python.

Coming to this calculation for TRIN value, we will first fetch the data of price and volume for the stocks. We have taken S&P500 stocks for our calculation with python code.

# Import libraries
import pandas as pd
import numpy as np

# Fetch data
data = data.dropna()
return data

# Print the first two rows of the prices dataframe

# Print the first two rows of the volume dataframe

# List the stock names
stocks = prices.columns

Now, we will find out if today’s close price is higher than yesterday’s close price or not. If today’s close price is higher than the previous close price, the output will show “1” and if otherwise, then the output will be “o” for the particular day. We will print this direction for one stock, that is, Amazon (AMZN) so as to see our output.

# Generate direction column for every stock with conditions if today’s close price > previous close price,
# if today’s close price < previous close price
for col in stocks:
direction_col = col + ‘_direction’
prices[direction_col] = np.where(prices[col] > prices[col].shift(1), 1, 0)
prices[direction_col] = np.where(
prices[col] == prices[col].shift(1), -1, prices[direction_col])

# Print the direction column for one stock

Output:

Stay tuned for the next installment in which the author will find out the number of advancing stocks.