US examples
Technical indicator selection
On this page4
RSI (Relative Strength Index) measures the size of recent price changes to flag overbought or oversold stocks. This strategy buys the 20 US stocks with the highest RSI each week, so it chases momentum: it suits investors who expect strong stocks to keep rising.
Strategy logic
- Compute the 20-day RSI of every stock with
data.indicator('RSI', timeperiod=20). - Hold the 20 stocks with the highest RSI (
is_largest(20)). - Rebalance once a week.
Code
strategy.py
from finlab import data
from finlab.backtest import sim
from finlab.markets.us import USMarket
data.set_market('us')
close = data.get('price:adj_close')
close = close[close.index.dayofweek < 5] # remove weekends
# Select top 20 stocks by RSI
rsi = data.indicator('RSI', timeperiod=20)
position = rsi.is_largest(20)
# Backtest with weekly (W) rebalancing
report = sim(position, resample='W', market=USMarket(), fee_ratio=0.001, tax_ratio=0)
report.display()How to adjust it
timeperiod=20: the RSI lookback window. A 20-day RSI smooths out short-term noise compared with the more common 14-day RSI, while still capturing recent momentum.is_largest(20): how many stocks to hold. High-RSI stocks are the ones showing strong upward momentum.resample='W': rebalances once a week, balancing how quickly the portfolio follows momentum shifts against trading costs. Weekly rebalancing captures medium-term momentum while limiting turnover.fee_ratio=0.001: a 0.1% commission, a reasonable estimate for US brokerage fees.tax_ratio=0: US stock trades carry no transaction tax. Capital gains tax is handled separately and is not modeled in the backtest.
To rank by a different indicator, swap the data.indicator() call; the technical indicators page lists what is available.
Related pages
- Technical indicators Compute TA-Lib and pandas_ta indicators for every stock in one line.
- 52-week high momentum Another momentum strategy, built on new price highs.
- AAPL Bollinger rebound The contrarian opposite: buy when a stock looks oversold.
- Backtesting An S&P 500 version of the high-RSI strategy, with an interactive report.
Was this page helpful?