---
title: "Brain ML Stock Ranking"
description: "Brain ML Stock Ranking dataset from Brain."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/brain/brain-ml-stock-ranking
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/brain/brain-ml-stock-ranking.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/14%20Datasets/08%20Brain/02%20Brain%20ML%20Stock%20Ranking
modified: 2026-10-30
index: https://www.quantconnect.com/llms.txt
---

# Brain ML Stock Ranking

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Datasets > [Brain](https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/brain.md) > Brain ML Stock Ranking

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## Introduction

The Brain ML Stock Ranking dataset by Brain generates a daily ranking for US Equities based on their predicted ranking of future returns relative to the universe median across four-time horizons: next 2, 3, 5, 10, and 21 days (one trading month). The data covers 1,000 US Equities (universe updated yearly by including the largest 1,000 US companies of the previous year), starts in January 2010, and is delivered on a daily frequency. This dataset is created by a voting scheme of machine learning classifiers that non-linearly combine a variety of features with a series of techniques aimed at mitigating the well-known overfitting problem for financial data with a low signal-to-noise ratio. Examples of features are time-varying stock-specific features like price and volume-related metrics or fundamentals; time-fixed stock-specific features like the sector and other database information; market regime features such as volatility and other financial stress indicators; calendar features representing possible anomalies, for example, the month of the year.

More precisely the ML Stock Ranking score is related to the confidence of a Machine Learning classifier in predicting top or bottom quintile returns for the next N trading days (e.g. next 21 trading days) for a stock with the respect to the median of the universe and ranges from -1 to +1.

A negative score means that the system is more confident that the stock belongs to the lower returns quintile, a positive score means that the system is more confident that the stock belongs to the higher returns quintile. It is important to note that the score has a meaning only if used to compare different stocks to perform a ranking.

Typical use is to download the score for a large stock universe for a given day, e.g. 500 stocks or the full universe of 1000 stocks, order the stocks by mlAlpha score and go long the top K stocks, or build a long-short strategy going long the top K and short the bottom K stocks.

For more information, refer to Brain's [summary paper](https://braincompany.co/assets/files/BSR_summary.pdf).

This dataset depends on the [US Equity Security Master](https://www.quantconnect.com/datasets/quantconnect-us-equity-security-master) dataset because the US Equity Security Master dataset contains information on splits, dividends, and symbol changes.

For more information about the Brain ML Stock Ranking dataset, including CLI commands and pricing, see the [dataset listing](https://www.quantconnect.com/datasets/brain-ml-stock-ranking).

## About the Provider

[Brain](https://braincompany.co/bsr.html) is a Research Company that creates proprietary datasets and algorithms for investment strategies, combining experience in financial markets with strong competencies in Statistics, Machine Learning, and Natural Language Processing. The founders share a common academic background of research in Physics as well as extensive experience in Financial markets.

## Getting Started

The following snippet demonstrates how to request data from the Brain ML Stock Ranking dataset:

```python
self.aapl = self.add_equity("AAPL", Resolution.DAILY).symbol
self.dataset_symbol = self.add_data(BrainStockRanking2Day, self.aapl).symbol

self._universe = self.add_universe(BrainStockRankingUniverse, self.universe_selection)
```

## Data Summary

The following table describes the dataset properties:

| Property | Value |
| --- | --- |
| Start Date | January 2010 |
| Asset Coverage* | 1,000 US Equities |
| Data Density | Sparse |
| Resolution | Daily |
| Timezone | UTC |

The coverage includes all assets since the start date. It increases over time.

## Requesting Data

To add Brain ML Stock Ranking data to your algorithm, call the `add_data` method. Save a reference to the dataset `Symbol` so you can access the data later in your algorithm.

```python
class BrainMLRankingDataAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2021, 1, 1)
        self.set_end_date(2021, 7, 8)
        self.set_cash(100000)

        self.aapl = self.add_equity("AAPL", Resolution.DAILY).symbol
        self.two_day_symbol = self.add_data(BrainStockRanking2Day, self.aapl).symbol
        self.three_day_symbol = self.add_data(BrainStockRanking3Day, self.aapl).symbol
        self.five_day_symbol = self.add_data(BrainStockRanking5Day, self.aapl).symbol
        self.ten_day_symbol = self.add_data(BrainStockRanking10Day, self.aapl).symbol
        self.month_symbol = self.add_data(BrainStockRanking21Day, self.aapl).symbol
```

## Accessing Data

To get the current Brain ML Stock Ranking data, index the current [`Slice`](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/time-modeling/timeslices.md) with the dataset `Symbol`. Slice objects deliver unique events to your algorithm as they happen, but the `Slice` may not contain data for your dataset at every time step. To avoid issues, check if the `Slice` contains the data you want before you index it.

```python
def on_data(self, slice: Slice) -> None:
    if slice.contains_key(self.two_day_symbol):
        data_point = slice[self.two_day_symbol]
        self.log(f"{self.two_day_symbol} rank at {slice.time}: {data_point.rank}")

    if slice.contains_key(self.three_day_symbol):
        data_point = slice[self.three_day_symbol]
        self.log(f"{self.three_day_symbol} rank at {slice.time}: {data_point.rank}")

    if slice.contains_key(self.five_day_symbol):
        data_point = slice[self.five_day_symbol]
        self.log(f"{self.five_day_symbol} rank at {slice.time}: {data_point.rank}")

    if slice.contains_key(self.ten_day_symbol):
        data_point = slice[self.ten_day_symbol]
        self.log(f"{self.ten_day_symbol} rank at {slice.time}: {data_point.rank}")

    if slice.contains_key(self.month_symbol):
        data_point = slice[self.month_symbol]
        self.log(f"{self.month_symbol} rank at {slice.time}: {data_point.rank}")
```

To iterate through all of the dataset objects in the current `Slice`, call the `get` method.

```python
def on_data(self, slice: Slice) -> None:
    for dataset_symbol, data_point in slice.get(BrainStockRanking2Day).items():
        self.log(f"{dataset_symbol} rank at {slice.time}: {data_point.rank}")

    for dataset_symbol, data_point in slice.get(BrainStockRanking3Day).items():
        self.log(f"{dataset_symbol} rank at {slice.time}: {data_point.rank}")

    for dataset_symbol, data_point in slice.get(BrainStockRanking5Day).items():
        self.log(f"{dataset_symbol} rank at {slice.time}: {data_point.rank}")

    for dataset_symbol, data_point in slice.get(BrainStockRanking10Day).items():
        self.log(f"{dataset_symbol} rank at {slice.time}: {data_point.rank}")

    for dataset_symbol, data_point in slice.get(BrainStockRanking21Day).items():
        self.log(f"{dataset_symbol} rank at {slice.time}: {data_point.rank}")
```

## Historical Data

To get historical Brain ML Stock Ranking data, call the `history` method with the dataset `Symbol`. If there is no data in the period you request, the history result is empty.

```python
# DataFrames
two_day_history_df = self.history(self.two_day_symbol, 100, Resolution.DAILY)
three_day_history_df = self.history(self.three_day_symbol, 100, Resolution.DAILY)
five_day_history_df = self.history(self.five_day_symbol, 100, Resolution.DAILY)
ten_day_history_df = self.history(self.ten_day_symbol, 100, Resolution.DAILY)
thirty_day_history_df = self.history(self.month_symbol, 100, Resolution.DAILY)
history_df = self.history([self.two_day_symbol,
                           self.three_day_symbol,
                           self.five_day_symbol,
                           self.ten_day_symbol,
                           self.month_symbol], 100, Resolution.DAILY)

# Dataset objects
two_day_history_bars = self.history[BrainStockRanking2Day](self.two_day_symbol, 100, Resolution.DAILY)
three_day_history_bars = self.history[BrainStockRanking3Day](self.three_day_symbol, 100, Resolution.DAILY)
five_day_history_bars = self.history[BrainStockRanking5Day](self.five_day_symbol, 100, Resolution.DAILY)
ten_day_history_bars = self.history[BrainStockRanking10Day](self.ten_day_symbol, 100, Resolution.DAILY)
month_history_bars = self.history[BrainStockRanking21Day](self.month_symbol, 100, Resolution.DAILY)
```

For more information about historical data, see [History Requests](https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/history-requests.md).

## Universe Selection

To select a dynamic universe of US Equities based on Brain ML Stock Ranking data, call the `add_universe` method with the `BrainStockRankingUniverse` class and a selection function.

```python
def initialize(self) -> None:
    self._universe = self.add_universe(BrainStockRankingUniverse, self.universe_selection)

def universe_selection(self, alt_coarse: List[BrainStockRankingUniverse]) -> List[Symbol]:
    return [d.symbol for d in alt_coarse \
                if d.rank2_days > 0 \
                and d.rank3_days > 0 \
                and d.rank5_days > 0]
```

For more information about dynamic universes, see [Universes](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/key-concepts.md).

## Universe History

You can get historical universe data in an algorithm and in the Research Environment.

### Historical Universe Data in Algorithms

To get historical universe data in an algorithm, call the `history` method with the `Universe` object and the lookback period. If there is no data in the period you request, the history result is empty.

```python
# DataFrame example where the columns are the BrainStockRankingUniverse attributes:
history_df = self.history(self._universe, 30, Resolution.DAILY, flatten=True)

# Series example where the values are lists of BrainStockRankingUniverse objects:
universe_history = self.history(self._universe, 30, Resolution.DAILY)
for (_, time), ranks in universe_history.items():
    for rank in ranks:
        self.log(f"{rank.symbol} 2-day rank at {rank.end_time}: {rank.rank2_days}")
```

### Historical Universe Data in Research

To get historical universe data in research, call the `universe_history` method with the `Universe` object, a start date, and an end date. This method returns the filtered universe. If there is no data in the period you request, the history result is empty.

```python
# DataFrame example where the columns are the BrainStockRankingUniverse attributes:
history_df = qb.universe_history(universe, qb.time-timedelta(30), qb.time, flatten=True)

# Series example where the values are lists of BrainStockRankingUniverse objects:
universe_history = qb.universe_history(universe, qb.time-timedelta(30), qb.time)
for (_, time), ranks in universe_history.items():
    for rank in ranks:
        print(f"{rank.symbol} 2-day rank at {rank.end_time}: {rank.rank2_days}")
```

You can call the `history` method in Research.

## Remove Subscriptions

To remove a subscription, call the `remove_security` method.

```python
self.remove_security(self.two_day_symbol)
self.remove_security(self.three_day_symbol)
self.remove_security(self.five_day_symbol)
self.remove_security(self.ten_day_symbol)
self.remove_security(self.month_symbol)
```

If you subscribe to Brain ML Stock Ranking data for assets in a dynamic universe, remove the dataset subscription when the asset leaves your universe. To view a common design pattern, see [Track Security Changes](https://www.quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/alpha/key-concepts.md#05-Track-Security-Changes).

## Example Applications

The Brain ML Stock Ranking dataset enables you to test strategies using the machine learning ranking provided by Brain. Examples include the following strategies:

- Constructing a portfolio of securities with each security's weight in the portfolio reflecting its Brain ML Stock Ranking
- Buying stocks with the largest Brain ML Stock Ranking
- Building a market-neutral strategy based on the top N and bottom N stocks in the Brain ML Stock Ranking

### Classic Algorithm Example

The following example algorithm constructs a portfolio where the weight of each security in the portfolio is scaled based on its Brain ML Ranking. It gives a larger allocation to securities that have a higher Brain ML Ranking.

```python
from AlgorithmImports import *

class BrainMLRankingDataAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(100000)
        # Seed initial prices to avoid trading errors before fresh market data arrives.
        self.settings.seed_initial_prices = True
        # Select liquid large-cap equities to support credible ranking comparisons.
        tickers = ["AAPL", "TSLA", "MSFT", "F", "KO"]
        self.equity_by_dataset_symbol = {}
        for ticker in tickers:
            # Subscribe to each equity and its two-day estimated relative ranking data.
            equity = self.add_equity(ticker, Resolution.DAILY)
            dataset_symbol = self.add_data(BrainStockRanking2Day, equity).symbol
            self.equity_by_dataset_symbol[dataset_symbol] = equity
            # Request historical ranking data to inspect subscription coverage.
            history = self.history(dataset_symbol, 252, Resolution.DAILY)
            self.debug(f"We got {len(history)} items from our history request for {equity}")

    def on_data(self, data: Slice) -> None:
        # Collect ranking points for all selected equities before assigning weights.
        points = data.get(BrainStockRanking2Day)
        if not points:
            return
        rank_by_equity = {}
        for dataset_symbol, point in points.items():
            rank_by_equity[self.equity_by_dataset_symbol[dataset_symbol]] = point.rank
        if not rank_by_equity:
            return
        # Convert raw ranking values into comparable position sizes.
        sorted_ranks = sorted(rank_by_equity.values())
        ranked = {equity: sorted_ranks.index(rank) + 1 for equity, rank in rank_by_equity.items()}
        # Allocate more capital to equities with stronger estimated return rankings.
        total = sum(ranked.values())
        for equity, rank in ranked.items():
            self.set_holdings(equity.symbol, rank / total)
```

### Framework Algorithm Example

The following example algorithm constructs a portfolio where the weight of each security in the portfolio is scaled based on its Brain ML Ranking. It gives a larger allocation to securities that have a higher Brain ML Ranking.

```python
from AlgorithmImports import *

class BrainMLRankingDataAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(100000)
        self.settings.seed_initial_prices = True
        self.universe_settings.resolution = Resolution.DAILY
        # Select securities based on ML ranking data.
        self.add_universe(BrainStockRankingUniverse, self.universe_selection)
        self.add_alpha(BrainMLRankingAlphaModel())
        self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel())
        self.add_risk_management(NullRiskManagementModel())
        self.set_execution(ImmediateExecutionModel())

    def universe_selection(self, alt_coarse: List[BrainStockRankingUniverse]) -> List[Symbol]:
        # Select the securities expected to outperform the median market return in two to three days.
        filtered = [d for d in alt_coarse if d.rank_2_days > 0 and d.rank_3_days > 0]
        filtered = sorted(filtered, key=lambda d: d.rank_2_days)[-2:]
        return [d.symbol for d in filtered]

class BrainMLRankingAlphaModel(AlphaModel):
    _securities = []

    def update(self, algorithm: QCAlgorithm, slice: Slice) -> List[Insight]:
        # Collect rankings for all selected securities.
        points = slice.get(BrainStockRanking2Day)
        if not points:
            return []
        rank_by_security = {}
        for dataset_symbol, point in points.items():
            security = algorithm.securities[dataset_symbol.underlying]
            if not security.price:
                continue
            rank_by_security[security] = point.rank
        total_rank = sum(rank_by_security.values())
        return [
            Insight.price(security, timedelta(1), InsightDirection.UP, weight=rank / total_rank)
            for security, rank in rank_by_security.items()
        ]

    def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
        for security in changes.added_securities:
            self._securities.append(security)
            # Request data for the two-day estimated relative ranking.
            security.brain_stock_ranking_2_day = algorithm.add_data(BrainStockRanking2Day, security, Resolution.DAILY)
            # Historical data.
            history = algorithm.history(security.brain_stock_ranking_2_day, 252, Resolution.DAILY)
            algorithm.debug(f"We got {len(history)} items from our history request for {security.brain_stock_ranking_2_day.symbol}")
        for security in changes.removed_securities:
            # Unsubscribe from the Brain ML Ranking feed for this security to release resources.
            if security in self._securities:
                algorithm.remove_security(security.brain_stock_ranking_2_day)
                self._securities.remove(security)
```

### Research Example

The following example lists US Equities having the highest 2-day rank.

```python
qb = QuantBook()

# Requesting Data
aapl = qb.add_equity("AAPL", Resolution.DAILY).symbol
symbol = qb.add_data(BrainStockRanking2Day, aapl).symbol

# Historical data
history = qb.history(BrainStockRanking2Day, symbol, 30, Resolution.DAILY)
for (symbol, time), row in history.iterrows():
    print(f"{symbol} rank at {time}: {row['rank']}")

# Add Universe Selection
def universe_selection(alt_coarse: List[BrainStockRankingUniverse]) -> List[Symbol]:
    return [d.symbol for d in sorted(alt_coarse, key=lambda x: x.rank_2_days, reverse=True)[:10]]

universe = qb.add_universe(BrainStockRankingUniverse, universe_selection)

# Historical Universe data
universe_history = qb.universe_history(universe, qb.time-timedelta(5), qb.time)
for (_, time), ranks in universe_history.items():
    for rank in ranks:
        print(f"{rank.symbol} 2-day rank at {rank.end_time}: {rank.rank_2_days}")
```

## Data Point Attributes

The Brain ML Stock Ranking dataset provides `BrainStockRankingBase` and `BrainStockRankingUniverse` objects.

### BrainStockRankingBase Attributes

`BrainStockRankingBase` objects have the following attributes:

*Members of `QuantConnect.DataSource.BrainStockRankingBase` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.DataSource.BrainStockRankingBase&language=python*

### BrainStockRankingUniverse Attributes

`BrainStockRankingUniverse` objects have the following attributes:

*Members of `QuantConnect.DataSource.BrainStockRankingUniverse` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.DataSource.BrainStockRankingUniverse&language=python*
