# Trading Index (TRIN): Formula, Calculation & Strategy in Python – Part III Articles From: QuantInsti
Website: QuantInsti

See Part I for a definition of TRIN and Part II for instructions on how to calculate TRIN in Python.

Next, we will find out the number of advancing stocks (ones which ended in green) and the number of declining stocks (ones which ended in red) from the previous day.

# Add the number of stocks that ended in green from previous day
# and number of stocks that ended in red from previous day
direction_cols = [col + ‘_direction’ for col in stocks]

# Print the “pos_direction” and “neg_direction” columns from dataframe

Output:

Now, we will generate the sum of the volume of the stocks ended in positive and negative from the previous day since this is required to calculate AD volume.

# Rename volume dataframe columns by adding ‘_volume’ , to help merge prices and volume dataframes
volume_cols = [col + ‘_volume’ for col in stocks]
volume.rename(columns=dict(zip(stocks, volume_cols)), inplace=True)

# Print the first two rows of the volume dataframe

Output:

Further, we will find out advancing and declining stocks and advancing and declining volume of stocks. Then, finally, we will calculate the TRIN value.

# Merge both prices, volume data-frames
mergedDf = prices.merge(volume, left_index=True, right_on=’Date’)

# Create vol_direction column for every stock, to sum positive ended and negative ended stocks volume
for col in stocks:
volume_col = col + ‘_volume’
direction_col = col + ‘_direction’
vol_direction = col + ‘_vol_direction’
mergedDf[vol_direction] = mergedDf[volume_col] * mergedDf[direction_col]

# Add the volume of all positive ended stocks to ‘total_pos_volume’
# And sum of the volume of negative ended stocks to ‘total_neg_volume’
vol_direction_cols = [col + ‘_vol_direction’ for col in stocks]
mergedDf[‘total_volume’] = mergedDf[volume_cols].sum(axis=1)
mergedDf[‘declining_volume’] = mergedDf[‘total_volume’] – \

# Print ‘pos_direction’,’neg_direction’, ‘total_pos_volume’ and ‘total_neg_volume’ columns from dataframe

Output:

# Calculate TRIN ratio

Output:

Date

01-04-2020         NaN

02-04-2020    1.289376

03-04-2020    0.686072

06-04-2020    3.285942

07-04-2020    0.693863

Name: TRIN, dtype: float64

Stay tuned for the next installment in which the author will plot a graph to find out the TRIN value for S&P500. 