Sector momentum scanner for swing traders

python dev.to

Swing trading has always been a fascinating approach for those looking to capitalize on short- to medium-term price movements. One of the more reliable strategies involves scanning for sector momentum. The concept is straightforward: sectors that are outperforming the market generally continue to do so for a period, providing a ripe opportunity for swing traders. In this post, I’ll walk you through the process of building a sector momentum scanner using Python.

Gathering Sector Data

The first step in building a sector momentum scanner is to gather reliable data. For this purpose, I typically use APIs that provide sector-specific data. While there are several paid options, you can also find free APIs with limited usage.

Here's a quick example of how you might start pulling sector data using the yfinance library, which is a wrapper around Yahoo Finance:

import yfinance as yf

# Define the sector tickers (example: SPY sector ETFs)
sector_tickers = ['XLF', 'XLK', 'XLE', 'XLY', 'XLI', 'XLC', 'XLV', 'XLB', 'XLRE', 'XLU']

# Fetch historical data
def get_sector_data(ticker):
    data = yf.download(ticker, period='1mo', interval='1d')
    return data['Close']

sector_data = {ticker: get_sector_data(ticker) for ticker in sector_tickers}
print(sector_data)
Enter fullscreen mode Exit fullscreen mode

This script fetches the closing prices for each sector ETF over the last month. With this data in hand, we can start calculating momentum metrics.

Calculating Momentum

Momentum is typically measured by the rate of change in price over a specific period. For simplicity, we'll calculate the percentage change over the last 20 days for each sector:

import pandas as pd

def calculate_momentum(data):
    return data.pct_change(periods=20).iloc[-1]

sector_momentum = {ticker: calculate_momentum(data) for ticker, data in sector_data.items()}
momentum_df = pd.DataFrame.from_dict(sector_momentum, orient='index', columns=['Momentum'])
momentum_df.sort_values(by='Momentum', ascending=False, inplace=True)
print(momentum_df)
Enter fullscreen mode Exit fullscreen mode

This code snippet calculates the 20-day momentum for each sector and sorts them in descending order. The result is a quick visualization of which sectors are currently leading in momentum.

Analyzing the Results

The sorted DataFrame of sector momentum provides immediate insight into which sectors are potentially profitable for swing trades. However, this is just the starting point. A robust strategy might also incorporate other factors, such as relative strength, volume, or even fundamental data.

One pitfall I've encountered is relying solely on momentum without considering other market conditions. Sectors can show strong momentum due to temporary news events, only to reverse quickly. Therefore, it’s crucial to use this scanner as a part of a broader strategy, not in isolation.

By the way, if you're interested in a more comprehensive solution, I’ve packaged this idea into a tool called Stock Market Screener. It allows you to scan the entire market with over 50 technical indicators and fundamental filters, including pre-built screens for momentum and breakout setups. Real-time data can be a game-changer, especially when you're trying to catch these sector moves as they happen.

Automating the Process

Manually running these scripts every day can be a chore. Automating the process with a scheduler like cron or a cloud-based solution can save a lot of time. Moreover, setting up alerts when a sector's momentum exceeds a certain threshold can help you act quickly on potential opportunities.

Building a sector momentum scanner has been an enlightening project, marrying data science with practical trading strategies. Whether you're using this as a standalone tool or integrating it into a larger trading system, the ability to quickly identify leading sectors can be a valuable edge in the fast-paced world of swing trading.

Also available on Payhip with instant PayPal checkout.


If you need a server to run your bots 24/7, I use DigitalOcean — $200 free credit for new accounts.

Source: dev.to

arrow_back Back to Tutorials