Stock Picking With Trending Value Strategy using Python

In partnership with

`

Own shares in early lung cancer detection.

Cizzle Biotech's groundbreaking blood test detects early-stage lung cancer with over 95% accuracy. Partnerships like Bio-Techne and Moffitt Cancer Center back our patented science. Our early detection could save lives and lower healthcare costs. Be a part of this vital medical breakthrough that could impact millions.

Read the Offering information carefully before investing. It contains details of the issuer’s business, risks, charges, expenses, and other information, which should be considered before investing. Obtain a Form C and Offering Memorandum at invest.cizzlebio.com

Exciting News: Paid Subscriptions Have Launched! 🚀

On September 1, we officially rolled out our new paid subscription plans at GuruFinance Insights, offering you the chance to take your investing journey to the next level! Whether you're just starting or are a seasoned trader, these plans are packed with exclusive trading strategies, in-depth research paper analysis, ad-free content, monthly AMAsessions, coding tutorials for automating trading strategies, and much more.

Our three tailored plans—Starter Investor, Pro Trader, and Elite Investor—provide a range of valuable tools and personalized support to suit different needs and goals. Don’t miss this opportunity to get real-time trade alerts, access to masterclasses, one-on-one strategy consultations, and be part of our private community group. Click here to explore the plans and see how becoming a premium member can elevate your investment strategy!

A strategy that combines value metrics and momentum for stock picking

In the ever-evolving world of investing, many have sought to unlock the secrets of success in the stock market. Amid the noise and chaos, a handful of thinkers have managed to stand out, crafting unique approaches that capture the market’s essence. One of these trailblazers is James O’Shaughnessy, an investor, author, and fund manager who pioneered the Trending Value Strategy — a concept that blends value investing with momentum, offering a fresh perspective to market participants.

But like any great story, the origins of the Trending Value Strategy trace back to a broader journey — one filled with curiosity, research, and a little bit of defiance against conventional wisdom.

The Early Days: A Search for Patterns

James O’Shaughnessy has always been a man who believed in numbers. In the early 1990s, when most investors relied on intuition, O’Shaughnessy turned to data. He embarked on an extensive study, diving into the history of stock performance with a single mission: to find patterns. What made certain stocks outperform while others fizzled out? Could there be a reliable way to predict future stock returns?

His quest was methodical. Using data that spanned decades, O’Shaughnessy scoured through hundreds of factors, testing their impact on stock performance. His findings formed the foundation of his seminal book, What Works on Wall Street â€” a text that revolutionised investing by quantifying historical stock returns and identifying the factors that consistently outperformed over time.

This Smart Home Company is Growing 200% Month-Over-Month

Ever thought the smartest part of your home could be your window shades?

Meet RYSE, the company transforming ordinary blinds into cutting-edge smart home devices. With 10 granted patents, a major win against copycat sellers on Amazon, and products already featured in 127 Best Buy locations, RYSE is scaling rapidly in a market growing 23% annually.

And they’re just getting started. With 200% month-over-month revenue growth, international expansion on the horizon, and partnerships with retail giants like Home Depot and Lowe’s, RYSE is poised to redefine home automation.

Now, for just $1.75 per share, you can invest in this fast-growing company and be part of the smart home revolution.

The Birth of the Trending Value Strategy

Through his research, O’Shaughnessy identified two dominant forces in stock market performance: value and momentum. These forces, while seemingly contradictory, turned out to be a powerful combination.

  • Value investing, championed by legends like Benjamin Graham and Warren Buffett, involves buying stocks that are considered undervalued by the market — those trading at a discount to their intrinsic value.

  • Momentum investing, on the other hand, focuses on stocks that have shown recent upward price trends. The idea is that stocks performing well are likely to continue doing so, as they gain positive investor sentiment.

O’Shaughnessy’s genius lay in recognising that value stocks, often ignored or out of favour with investors, could achieve remarkable returns if they also exhibited positive momentum. Thus, the Trending Value Strategy was born.

Instead of solely relying on value stocks — many of which could stay undervalued for long periods — O’Shaughnessy’s strategy added a filter for momentum. By selecting value stocks that were already trending upward, the strategy sought to capture stocks at the intersection of being fundamentally undervalued and technically strong.

How Does the Trending Value Strategy Work?

At its core, the strategy is based on quantitative rules. It systematically ranks stocks based on two key dimensions:

  1. Value Metrics: These include traditional measures like the price-to-earnings (P/E) ratio, price-to-book (P/B) ratio, price-to-sales (P/S) ratio, price-to-operating cash flow (P/OCF) and enterprise value-to- earnings before interest depreciation tax and amortisation (EV/EBIDTA) ratio. The lower the ratios, the more undervalued a stock is considered. There is also one other factor, Dividend Yield which can be included. This value should be higher for a stock to get higher rank.

  2. Momentum Factors: Stocks are further filtered based on their recent performance — typically measured by price appreciation over the past 6 to 12 months. The strategy favours stocks that have recently experienced upward momentum.

Once the universe of stocks is filtered by value and momentum, the portfolio is constructed by selecting the highest-ranking stocks. This blending of two distinct investment factors — value and momentum — enables the strategy to outperform many traditional approaches over time, as it seeks to avoid value traps (stocks that remain cheap for a reason) while capturing stocks that are poised for growth.

Python Implementation

Now that we know how this strategy works, lets implement the code to filter out stocks which meets the criteria for this strategy. I have used stocks listed on NSE exchange in India for this code implementation.

Step 1

Download the fundamental metrics for all the stocks from a site like screener.in. Ensure that you include the value factors like Price to Earnings ratio, Price to Book ratio, Price to Sales, Price to Operation Cash Flow, Enterprise value to EBITDA ratio and Dividend Yield. Along with this also include columns like 6 months returns and 1 yr returns for applying momentum criteria. I did this exercise and saved the data in a CSV file “FullUniverseOfStocks.csv”. In order to avoid micro cap stocks, I applied the filter on market-cap and selected only companies which are having market-cap greater than 500 crore rupees. Below image shows the extract of this file.

Step 2

Do some data cleaning. I removed all stocks which have PE ratio or PS ratio as negative. Also, some companies have no data for Dividend Yield, I have assumed that they don’t pay any dividend and have replaced NA value with 0 value. Also, for some companies the price to cashflow from operations is not available, I have replaced higher value (say 1000) for those stocks so that they get lower ranking.

import numpy as np
import pandas as pd
import yfinance as yf
import math

# Load the data from the file
df = pd.read_csv('FullUniverseOfStocks.csv')

# Filter out stocks with negative PE ratio and PS ratio
# Some stocks dont have any Dividend Yield, replace NA with 0
# For some companies cash flow from operation is not available, 
# for those stocks, I have used a higher value of Price to CFO so that they get lower rank

df = df[df['PE Ratio'] > 0]
df = df[df['PS Ratio'] > 0]
df.fillna({'Dividend Yield': 0}, inplace=True)
df.fillna({'Price / CFO': 100000}, inplace=True)

Step 3

Rank the stocks based on each of the value factors. For all ratios other than Dividend Yield, a lower value means higher rank. For Dividend Yield, however an higher value will fetch a higher rank.

# Rank all the stocks based on each of the value factors.
# For the ratios other than Dividend Yield, the rank is higher if the value is lower
# For Dividend Yield, the rank is higher if the value is higher
df['PE Rank'] =  df['PE Ratio'].rank(ascending=True)
df['PB Rank'] =  df['PB Ratio'].rank(ascending=True)
df['PS Rank'] =  df['PS Ratio'].rank(ascending=True)
df['Price / CFO'] =  df['Price / CFO'].rank(ascending=True)
df['EV/EBITDA Ratio']  = df['EV/EBITDA Ratio'].rank(ascending=True)
df['Dividend Yield']  = df['Dividend Yield'].rank(ascending=False)

Step 4

Apply decile rank to each stocks. This means that any stock whose rank falls in the top 10 % of the rank from step 3 will get a decile rank of 1. For stocks falling between 11 % to 20 % rank will get a decile rank of 2 and so on.

Calculate combined rank, by adding individual ranks.

# Calculate the Decile rank for each company

noOfShares = len(df)/10

df['PE Rank'] =  round(df['PE Rank']/noOfShares) + 1
df['PB Rank'] =  round(df['PB Rank']/noOfShares) + 1
df['PS Rank'] =  round(df['PS Rank']/noOfShares) + 1
df['Price / CFO Rank'] =  round(df['Price / CFO Rank']/noOfShares) + 1
df['EV/EBITDA Ratio Rank']  = round(df['EV/EBITDA Ratio Rank']/noOfShares) + 1
df['Dividend Yield Rank']  = round(df['Dividend Yield Rank']/noOfShares) + 1

# Calculate combined score by adding individual scores
df['Combined Rank'] = df['PE Rank'] + df['PB Rank'] + df['PS Rank'] + df['EV/EBITDA Ratio Rank'] + df['Dividend Yield Rank'] + df['Price / CFO Rank']

Step 5

Pick the top 10% stocks based on combined rank and apply momentum criteria on these stocks to pick top 25 stocks. For momentum rank, just sort the companies by their 6 months return and pick the top 25 stocks.

# Sort the companies by combined rank and pick the top 10 % of the stocks for apply momentum critier
df = df[df['Combined Rank'] < noOfShares/10].sort_values(by=['Combined Rank'])

# Sort the companies by their 6 months return and pick the top 25 stocks
df.sort_values(by='6M Stock Price Return', ascending=False)[0:25][['Company Name', 'Combined Rank', 'ROCE', 'ROE']]

Running the above steps will output the below result. I included the ROCE and ROE of the companies just to check if these selected stocks are having good quality as well and to my surprise the numbers for these quality metrices are also good.

Result as of 11th October, 2024

The Results: Proven Through Time

O’Shaughnessy’s work was not just theoretical. When backtested over long periods, the Trending Value Strategy demonstrated significant outperformance compared to broader market indices. For instance, in What Works on Wall Street, O’Shaughnessy showcases decades of data that highlight how value combined with momentum beats standard value strategies on their own.

Why does it work so well? O’Shaughnessy found that human psychology plays a crucial role in this success. Value investors tend to focus too much on price discounts, overlooking companies with improving fundamentals. Meanwhile, momentum investors often chase stocks that are overvalued. The Trending Value Strategy finds a middle ground, benefiting from the psychological biases of both groups.

The real-world application of this strategy has also been tested. Through O’Shaughnessy’s firm, O’Shaughnessy Asset Management, the strategy has been incorporated into investment products and portfolios, proving its mettle across different market conditions.

Why It Still Matters Today

In today’s market, where technology and innovation dominate headlines, and value stocks often seem overlooked, the Trending Value Strategy remains as relevant as ever. Investors are constantly searching for ways to identify undervalued stocks while avoiding value traps, and O’Shaughnessy’s approach offers a clear framework for doing just that.

It’s also a reminder that investing isn’t just about chasing the hottest trend or betting on the next big thing. True investing, as O’Shaughnessy’s work demonstrates, is about understanding the underlying principles that drive market behavior and patiently applying those principles over time.

Conclusion: A Lasting Legacy

The story of the Trending Value Strategy is one of innovation, research, and a deep understanding of both human psychology and market behavior. James O’Shaughnessy’s work continues to inspire investors, not just because it offers a path to potentially higher returns, but because it represents a disciplined, data-driven approach to navigating the complexities of the stock market.

As we look to the future, with markets constantly evolving and new technologies reshaping industries, O’Shaughnessy’s principles stand as a testament to the enduring power of blending timeless investment wisdom with modern analysis. The Trending Value Strategy, much like its creator, is here to stay.