Python
How to Identify Trending Stocks Using Python?

FabTrader
Article overview
If you’re a trader or investor, identifying trending stocks can give you an edge in the market. Stocks in a strong uptrend often continue their momentum, while stocks in a downtrend may keep falling. In this guide, we'll show you how to find the top trending stocks using Python by calculating their trend slopes.
If you’re a trader or investor, identifying trending stocks can give you an edge in the market. Stocks in a strong uptrend often continue their momentum, while stocks in a downtrend may keep falling. In this guide, we'll show you how to find the top trending stocks using Python by calculating their trend slopes.
Understanding Stock Trends
A stock trend is determined by the direction in which its price is moving over a period of time. A positive slope indicates an uptrend (bullish momentum), while a negative slope signals a downtrend (bearish momentum). By using Linear Regression, we can calculate the trend slope for each stock and identify the top 10 uptrending and downtrending stocks.
Steps to Find Trending Stocks
- Fetch stock data using the
yfinancelibrary. - Use linear regression to calculate the slope of closing prices over the last 30 days.
- Sort stocks based on their slope values.
- Filter out non-trending stocks (only consider positive slopes for uptrends and negative slopes for downtrends).
- Extract the top 10 uptrending and downtrending stocks.
Python Code to Find Top Trending Stocks
Here’s the Python script to accomplish this task:
import yfinance as yf
import pandas as pd
from sklearn.linear_model import LinearRegression
import numpy as np
# Define the list of stocks
stocks = ["AAPL", "MSFT", "GOOGL", "TSLA", "AMZN", "NVDA", "META", "NFLX", "AMD", "INTC",
"BABA", "UBER", "DIS", "V", "PYPL", "SQ", "JPM", "BA", "SPOT", "SHOP"]
# Define the time window for trend calculation
window = 30
# Function to calculate the slope of the closing price trend
def calculate_slope(stock):
try:
# Fetch historical stock data
df = yf.download(stock, period="6mo", interval="1d", progress=False)
# Ensure there are enough data points
if len(df) < window:
return None # Skip stocks with insufficient data
# Prepare data for linear regression (last `window` days)
X = np.arange(window).reshape(-1, 1) # Days as independent variable
y = df['Close'].iloc[-window:].values.reshape(-1, 1) # Closing prices
# Fit linear regression model
model = LinearRegression().fit(X, y)
slope = model.coef_[0][0] # Extract slope
return slope
except Exception as e:
print(f"Error processing {stock}: {e}")
return None
# Store results in a DataFrame
stock_slopes = [(stock, calculate_slope(stock)) for stock in stocks]
df = pd.DataFrame(stock_slopes, columns=["Stock", "Slope"]).dropna() # Remove None values
# Filter and sort stocks
df_up = df[df["Slope"] > 0].sort_values(by="Slope", ascending=False) # Only positive slopes
df_down = df[df["Slope"] < 0].sort_values(by="Slope", ascending=True) # Only negative slopes
# Get top 10 uptrend stocks
top_10_stocks = df_up.head(10)["Stock"].tolist()
# Get bottom 10 downtrend stocks
bottom_10_stocks = df_down.head(10)["Stock"].tolist()
# Display results
print("Top 10 Trending Stocks (Uptrend):", top_10_stocks)
print("Bottom 10 Trending Stocks (Downtrend):", bottom_10_stocks)
How This Works
- The script fetches 6 months of historical stock data.
- It calculates the trend slope for the past 30 days using Linear Regression.
- Stocks with a positive slope are considered uptrending, and those with a negative slope are considered downtrending.
- Finally, it sorts and extracts the top 10 stocks in each category.
Example Output
Top 10 Trending Stocks (Uptrend): ['NVDA', 'AAPL', 'MSFT', 'GOOGL', 'TSLA', 'META', 'AMZN', 'NFLX', 'V', 'DIS']
Bottom 10 Trending Stocks (Downtrend): ['BABA', 'UBER', 'PYPL', 'SQ', 'JPM', 'BA', 'SPOT', 'SHOP', 'INTC', 'AMD']
Why Use This Method?
✅ Easy to implement using Python and free data sources.
✅ Objective trend detection using Linear Regression.
✅ Helps in stock selection by identifying momentum.
This method can be integrated into an algorithmic trading system or used as a stock filtering tool for further analysis. Let us know if you find this useful! 🚀
Want to automate your trading strategy?
Check out more tools and insights on FabTrader to enhance your trading journey! 🚀
Support this community : FabTrader.in is a one-person initiative dedicated to helping individuals on their F.I.R.E. journey. Running and maintaining this community takes time, effort, and resources. If you’ve found value in the content, consider making a donation to support this mission.
More from Python
Finding the Most Liquid Equity ETFs in each Category using Python
Not all ETFs are created equal — especially when it comes to liquidity. While NSE provides a full ETF list, identifying the...
The Market’s Coiled Spring — Building the Momentum Squeeze Indicator in Python
Volatility doesn’t expand randomly — it contracts first. The Momentum Squeeze Indicator, popularized by LazyBear, is built on this simple but powerful...
Price Consolidation Boxes: Ranges, Breakouts, and Retests Using Python
Markets don’t trend most of the time — they pause, compress, and consolidate. Before every meaningful move up or down, price typically...
