What is Boot Camp?
Boot Camp is a great way to improve your skills and learn the QuantConnect API in easily digestible portions.
Don't have an account? Join QuantConnect Today
We are dedicated to providing investors with a cutting-edge platform for rapidly creating quant investment strategies. Founded in 2012, we've empowered more than 250,000 quants and engineers to create and trade their ideas.
Quickly and easily started with our API to build your strategy. The learning center lessons are interactive, step-by-step guides to make you productive as fast as possible.
Focus your efforts on driving alpha, not parsing CSV files. Our cloud offers hundreds of terabytes of traditional and alternative data preformatted, cleaned, and instantly accessible by our API.
Coordinate teamwork, control access permissions, and your shared cloud resources. Grow your trading organization safely and efficiently on top of our cloud architecture.
A selection of streaming live-trading strategies written by QuantConnect, and top highlights from the community available to follow and clone. Peer into detailed real-time positions to gain insight for your own trading.
What is Boot Camp?
Boot Camp is a great way to improve your skills and learn the QuantConnect API in easily digestible portions.
A collection of courses from independent educators to improve your quant skill base and create better strategies.
Solidify and expand your quant skill base with courses at QuantConnect
Learn algorithmic trading with python for US Equities. Guided strategy development in easily digestible portions.
Author: QuantConnect
Free | 96,013 People Enrolled
Learn algorithmic trading with python for FX. Guided strategy development in easily digestible portions.
Author: QuantConnect
Free | 20,591 People Enrolled
Learn algorithmic trading with python for Futures. Guided strategy development in easily digestible portions.
Author: QuantConnect
Free | 7,425 People Enrolled
In this algorithmic trading tutorial series you will learn everything you need to know to start writing your own trading bots using Python and the QuantConnect quantitative trading platform.
Author: Louis
Free | 28,796 People Enrolled
Master algorithmic trading on QuantConnect; backtest and live trade Stocks, Options, Futures, Forex, and Crypto.
Author: Cheng Li
Paid | Enroll on Udemy
Learn to use Python, Pandas, Matplotlib, and the QuantConnect Lean Engine to perform financial analysis and trading.
Author: Jose Portilla, Pierian Training
Paid | Enroll on Udemy
Learn to write programs that algorithmically trade cryptocurrencies using QuantConnect (C#).
Author: Eric Summers
Paid | Enroll on Udemy
Organization Notes
Get Started with Algorithm Lab
New Research
Optimizing a Gold-SPY Portfolio Using Hidden Markov Models for Market Downtime
Gold-SPY portfolio optimization using Hidden Markov Models for minimizing market downturn risk....
ReadAlgorithm Lab is your playground for developing and refining trading algorithms with QuantConnect. Utilize advanced tools, historical data, and robust backtesting to enhance your trading strategies. Transform your ideas into actionable insights and optimize your trading approach with ease.
Sign Up for FreeAlready have an account Log In.
This account is protected by two-factor authentication.
Request Token Information Reset My TokenCreated | Last Time Used | Agent | |
---|---|---|---|
No entries found |
To continue please enter your email:
(No google account required)
To verify that everything goes well please enter the 6 digit verification code generated by the authenticator application
Algorithm Lab is your playground for developing and refining trading algorithms with QuantConnect. Utilize advanced tools, historical data, and robust backtesting to enhance your trading strategies. Transform your ideas into actionable insights and optimize your trading approach with ease.
Sign Up for FreeAlready have an account Log In.
Please stop one of the following coding sessions, or upgrade your account.
NAME | ORGANIZATION |
---|
QuantConnect Datasets
Explore free and paid datasets available on QuantConnect covering fundamentals, pricing, and alternative options.
Datasets >
Dashboard
A transparent, community reporting system. Report suspected issues with our cloud data to be investigated by the QuantConnect Team.
Issue List
Loading...
Data Explorer Issues are a way to report and track data problems. They give the QuantConnect community a way to discuss potential solutions and be notified when they are resolved. If you think you have found a data problem please check the existing open and closed issues first; often another user may have already reported your problem.
Does your issue match any of the already listed issues?
Thank you for your contribution! Our team is currently working on resolving these issues, please subscribe to them to receive updates.
Datasets >
Brain ML Stock Ranking
Dataset by Brain
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.
This dataset depends on the US Equity Security Master dataset because the US Equity Security Master dataset contains information on splits, dividends, and symbol changes.
Brain 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.
The following snippet demonstrates how to request data from the Brain ML Stock Ranking dataset:
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)
_symbol = AddEquity("AAPL", Resolution.Daily).Symbol;
_datasetSymbol = AddData<BrainStockRanking2Day>(_symbol).Symbol;
_universe = AddUniverse<BrainStockRankingUniverse>(UniverseSelection);
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 Brain ML Stock Ranking dataset enables you to test strategies using the machine learning ranking provided by Brain. Examples include the following strategies:
Disclaimer: The dataset is provided by the data provider for informational purposes only and do not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor do they constitute an offer to provide investment advisory or other services by the data provider.
For more example algorithms, see Examples.
The Brain ML Stock Ranking dataset provides BrainStockRankingBase and BrainStockRankingUniverse objects.
BrainStockRankingBase objects have the following attributes:
BrainStockRankingUniverse objects have the following attributes:
To add Brain ML Stock Ranking data to your algorithm, call the AddDataadd_data method. Save a reference to the dataset Symbol so you can access the data later in your algorithm.
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
namespace QuantConnect
{
public class BrainMLRankingDataAlgorithm : QCAlgorithm
{
private Symbol _symbol, _2DaySymbol, _3DaySymbol, _5DaySymbol, _10DaySymbol, _monthSymbol;
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 7, 8);
SetCash(100000);
_symbol = AddEquity("AAPL", Resolution.Daily).Symbol;
_2DaySymbol = AddData<BrainStockRanking2Day>(_symbol).Symbol;
_3DaySymbol = AddData<BrainStockRanking3Day>(_symbol).Symbol;
_5DaySymbol = AddData<BrainStockRanking5Day>(_symbol).Symbol;
_10DaySymbol = AddData<BrainStockRanking10Day>(_symbol).Symbol;
_monthSymbol = AddData<BrainStockRanking21Day>(_symbol).Symbol;
}
}
}
To get the current Brain ML Stock Ranking data, index the current Slice 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.
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}")
public override void OnData(Slice slice)
{
if (slice.ContainsKey(_2DaySymbol))
{
var dataPoint = slice[_2DaySymbol];
Log($"{_2DaySymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
if (slice.ContainsKey(_3DaySymbol))
{
var dataPoint = slice[_3DaySymbol];
Log($"{_3DaySymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
if (slice.ContainsKey(_5DaySymbol))
{
var dataPoint = slice[_5DaySymbol];
Log($"{_5DaySymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
if (slice.ContainsKey(_10DaySymbol))
{
var dataPoint = slice[_10DaySymbol];
Log($"{_10DaySymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
if (slice.ContainsKey(_monthSymbol))
{
var dataPoint = slice[_monthSymbol];
Log($"{_monthSymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
}
To iterate through all of the dataset objects in the current Slice, call the Getget method.
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}")
public override void OnData(Slice slice)
{
foreach (var kvp in slice.Get<BrainStockRanking2Day>())
{
var datasetSymbol = kvp.Key;
var dataPoint = kvp.Value;
Log($"{datasetSymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
foreach (var kvp in slice.Get<BrainStockRanking3Day>())
{
var datasetSymbol = kvp.Key;
var dataPoint = kvp.Value;
Log($"{datasetSymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
foreach (var kvp in slice.Get<BrainStockRanking5Day>())
{
var datasetSymbol = kvp.Key;
var dataPoint = kvp.Value;
Log($"{datasetSymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
foreach (var kvp in slice.Get<BrainStockRanking10Day>())
{
var datasetSymbol = kvp.Key;
var dataPoint = kvp.Value;
Log($"{datasetSymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
foreach (var kvp in slice.Get<BrainStockRanking21Day>())
{
var datasetSymbol = kvp.Key;
var dataPoint = kvp.Value;
Log($"{datasetSymbol} rank at {slice.Time}: {dataPoint.Rank}");
}
}
To get historical Brain ML Stock Ranking data, call the Historyhistory method with the dataset Symbol. If there is no data in the period you request, the history result is empty.
# 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)
// Dataset objects
var twoDayHistory = History<BrainStockRanking2Day>(_2DaySymbol, 100, Resolution.Daily);
var threeDayHistory = History<BrainStockRanking3Day>(_3DaySymbol, 100, Resolution.Daily);
var fiveDayHistory = History<BrainStockRanking5Day>(_5DaySymbol, 100, Resolution.Daily);
var tenDayHistory = History<BrainStockRanking10Day>(_10DaySymbol, 100, Resolution.Daily);
var monthHistory = History<BrainStockRanking21Day>(_monthSymbol, 100, Resolution.Daily);
// Slice objects
var history = History(new[] {_2DaySymbol, _3DaySymbol, _5DaySymbol,
_10DaySymbol, _monthSymbol}, 100, Resolution.Daily);
For more information about historical data, see History Requests.
To select a dynamic universe of US Equities based on Brain ML Stock Ranking data, call the AddUniverseadd_universe method with the BrainStockRankingUniverse class and a selection function.
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]
private Universe _universe;
public override void Initialize()
{
_universe = AddUniverse<BrainStockRankingUniverse>(altCoarse =>
{
return from d in altCoarse.OfType<BrainStockRankingUniverse>()
where d.Rank2Days > 0m && d.Rank3Days > 0m && d.Rank5Days > 0m
select d.Symbol;
})
};
For more information about dynamic universes, see Universes.
You can get historical universe data in an algorithm and in the Research Environment.
To get historical universe data in an algorithm, call the Historyhistory method with the Universe object and the lookback period. If there is no data in the period you request, the history result is empty.
var universeHistory = History(_universe, 30, Resolution.Daily);
foreach (var ranks in universeHistory)
{
foreach (BrainStockRankingUniverse rank in ranks)
{
Log($"{rank.Symbol} 2-day rank at {rank.EndTime}: {rank.Rank2Days}");
}
}
# 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}")
To get historical universe data in research, call the UniverseHistoryuniverse_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.
var universeHistory = qb.UniverseHistory(universe, qb.Time.AddDays(-30), qb.Time);
foreach (var ranks in universeHistory)
{
foreach (BrainStockRankingUniverse rank in ranks)
{
Console.WriteLine($"{rank.Symbol} 2-day rank at {rank.EndTime}: {rank.Rank2Days}");
}
}
# 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 Historyhistory method in Research.
To remove a subscription, call the RemoveSecurityremove_security method.
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)
RemoveSecurity(_2DaySymbol);
RemoveSecurity(_3DaySymbol);
RemoveSecurity(_5DaySymbol);
RemoveSecurity(_10DaySymbol);
RemoveSecurity(_monthSymbol);
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.
The Brain ML Stock Ranking dataset provides BrainStockRankingBase and BrainStockRankingUniverse objects.
BrainStockRankingBase objects have the following attributes:
BrainStockRankingUniverse objects have the following attributes:
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.
from AlgorithmImports import *
from QuantConnect.DataSource import *
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)
# We cherry picked 5 largest stocks, high trading volume provides better information and credibility for ML ranking
tickers = ["AAPL", "TSLA", "MSFT", "F", "KO"]
self.symbol_by_dataset_symbol = {}
for ticker in tickers:
# Requesting data to get 2 days estimated relative ranking
symbol = self.add_equity(ticker, Resolution.DAILY).symbol
dataset_symbol = self.add_data(BrainStockRanking2Day, symbol).symbol
self.symbol_by_dataset_symbol[dataset_symbol] = symbol
# Historical data
history = self.history(dataset_symbol, 365, Resolution.DAILY)
self.debug(f"We got {len(history)} items from our history request for {symbol}")
def on_data(self, slice: Slice) -> None:
# Collect rankings for all selected symbols for ranking them
points = slice.Get(BrainStockRanking2Day)
if points is None:
return
symbols = []
ranks = []
for point in points.Values:
symbols.append(self.symbol_by_dataset_symbol[point.symbol])
ranks.append(point.rank)
# Rank each symbol's Brain ML ranking relative to each other for positional sizing
if len(ranks) == 0:
return
ranks = [sorted(ranks).index(rank) + 1 for rank in ranks]
# Place orders according to the ML ranking, the better the rank, the higher the estimated return and hence weight
for i, rank in enumerate(ranks):
weight = rank / sum(ranks)
self.set_holdings(symbols[i], weight)
using QuantConnect.DataSource;
namespace QuantConnect
{
public class BrainMLRankingDataAlgorithm : QCAlgorithm
{
private Dictionary<Symbol, Symbol> _symbolByDatasetSymbol = new Dictionary<Symbol, Symbol>();
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 7, 8);
SetCash(100000);
// We cherry picked 5 largest stocks, high trading volume provides better information and credibility for ML ranking
var tickers = new List<string>() {"AAPL", "TSLA", "MSFT", "F", "KO"};
foreach (var ticker in tickers)
{
// Requesting data to get 2 days estimated relative ranking
var symbol = AddEquity(ticker, Resolution.Daily).Symbol;
var datasetSymbol = AddData<BrainStockRanking2Day>(symbol).Symbol;
_symbolByDatasetSymbol.Add(datasetSymbol, symbol);
// Historical data
var history = History<BrainStockRanking2Day>(datasetSymbol, 365, Resolution.Daily);
Debug($"We got {history.Count()} items from our history request for {symbol}");
}
}
public override void OnData(Slice slice)
{
// Collect rankings for all symbols for ranking them
var points = slice.Get<BrainStockRanking2Day>();
if (points == null)
{
return;
}
var symbols = new List<Symbol>();
var ranks = new List<decimal>();
foreach (var point in points.Values)
{
symbols.Add(_symbolByDatasetSymbol[point.Symbol]);
ranks.Add(point.Rank);
}
// Rank each symbol's Brain ML ranking relative to the other symbols for positional sizing
if (ranks.Count() == 0) return;
var sortedRanksTemp = new List<decimal>(ranks);
sortedRanksTemp.Sort();
var sortedRanks = new List<decimal>();
for (var i = 0; i < symbols.Count(); i++)
{
sortedRanks.Add(sortedRanksTemp.IndexOf(ranks[i]) + 1);
}
// Place orders, the better the rank, the higher the estimated return and hence weight
for (var i = 0; i < symbols.Count(); i++)
{
var rank = sortedRanks[i];
var weight = rank / sortedRanks.Sum();
SetHoldings(symbols[i], weight);
}
}
}
}
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.
from AlgorithmImports import *
from QuantConnect.DataSource import *
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.universe_settings.resolution = Resolution.DAILY
# Select 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 ones that expected to out-perform the median of the whole market in 2-3 days
return [d.symbol for d in alt_coarse \
if d.Rank2Days > 0.2 \
and d.Rank3Days > 0.2]
class BrainMLRankingAlphaModel(AlphaModel):
symbol_data_by_symbol = {}
symbol_by_dataset_symbol = {}
def update(self, algorithm: QCAlgorithm, slice: Slice) -> List[Insight]:
insights = []
# Collect rankings for all selected symbols for ranking them
points = slice.Get(BrainStockRanking2Day)
if points is None:
return []
symbols = []
ranks = []
for point in points.Values:
symbols.append(self.symbol_by_dataset_symbol[point.symbol])
ranks.append(point.rank)
# Rank each symbol's Brain ML ranking relative to each other for positional sizing
if len(ranks) == 0:
return []
ranks = [sorted(ranks).index(rank) + 1 for rank in ranks]
# Place orders according to the ML ranking, the better the rank, the higher the estimated return and hence weight
for i, rank in enumerate(ranks):
weight = rank / sum(ranks)
insights.append(Insight.price(symbols[i], timedelta(days=7), InsightDirection.UP, None, None, None, weight))
return insights
def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
for security in changes.added_securities:
symbol = security.symbol
symbol_data = SymbolData(algorithm, symbol)
self.symbol_data_by_symbol[symbol] = symbol_data
self.symbol_by_dataset_symbol[symbol_data.dataset_symbol] = symbol
for security in changes.removed_securities:
symbol_data = self.symbol_data_by_symbol.pop(security.symbol, None)
if symbol_data:
symbol_data.dispose()
for dataset_symbol, symbol in self.symbol_by_dataset_symbol.items():
if symbol == security.symbol:
self.symbol_by_dataset_symbol.pop(dataset_symbol)
break
class SymbolData:
def __init__(self, algorithm, symbol):
self.algorithm = algorithm
# Requesting data to get 2 days estimated relative ranking
self.dataset_symbol = algorithm.add_data(BrainStockRanking2Day, symbol).symbol
# Historical data
history = algorithm.history(self.dataset_symbol, 365, Resolution.DAILY)
algorithm.debug(f"We got {len(history)} items from our history request for {symbol}")
def dispose(self):
# Unsubscribe from the Brain ML Ranking feed for this security to release computation resources
self.algorithm.remove_security(self.dataset_symbol)
using QuantConnect.DataSource;
namespace QuantConnect
{
public class BrainMLRankingDataAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 7, 8);
SetCash(100000);
// Select based on ML ranking data
AddUniverse<BrainStockRankingUniverse>(altCoarse =>
{
// Select the ones that expected to out-perform the median of the whole market in 2-3 days
return from d in altCoarse.OfType<BrainStockRankingUniverse>()
where d.Rank2Days > 0.2m && d.Rank3Days > 0.2m
select d.Symbol;
});
AddAlpha(new BrainMLRankingAlphaModel());
SetPortfolioConstruction(new InsightWeightingPortfolioConstructionModel());
AddRiskManagement(new NullRiskManagementModel());
SetExecution(new ImmediateExecutionModel());
}
}
public class BrainMLRankingAlphaModel : AlphaModel
{
private Dictionary<Symbol, SymbolData> _symbolDataBySymbol = new Dictionary<Symbol, SymbolData>();
private Dictionary<Symbol, Symbol> _symbolByDatasetSymbol = new Dictionary<Symbol, Symbol>();
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice slice)
{
var insights = new List<Insight>();
// Collect rankings for all selected symbols for ranking them
var points = slice.Get<BrainStockRanking2Day>();
if (points == null)
{
return insights;
}
var symbols = new List<Symbol>();
var ranks = new List<decimal>();
foreach (var point in points.Values)
{
symbols.Add(_symbolByDatasetSymbol[point.Symbol]);
ranks.Add(point.Rank);
}
// Rank each symbol's Brain ML ranking relative to the other symbols for positional sizing
if (ranks.Count() == 0)
{
return insights;
}
var sortedRanksTemp = new List<decimal>(ranks);
sortedRanksTemp.Sort();
var sortedRanks = new List<decimal>();
for (var i = 0; i < symbols.Count(); i++)
{
sortedRanks.Add(sortedRanksTemp.IndexOf(ranks[i]) + 1);
}
// Place orders according to the ML ranking, the better the rank, the higher the estimated return and hence weight
for (var i = 0; i < symbols.Count(); i++)
{
var rank = sortedRanks[i];
var weight = rank / sortedRanks.Sum();
insights.Add(Insight.Price(symbols[i], TimeSpan.FromDays(7), InsightDirection.Up, null, null, null, (double)weight));
}
return insights;
}
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
{
foreach (var security in changes.AddedSecurities)
{
var symbol = security.Symbol;
var symbolData = new SymbolData(algorithm, symbol);
_symbolDataBySymbol.Add(symbol, symbolData);
_symbolByDatasetSymbol.Add(symbolData.datasetSymbol, symbol);
}
foreach (var security in changes.RemovedSecurities)
{
var symbol = security.Symbol;
if (_symbolDataBySymbol.ContainsKey(symbol))
{
_symbolDataBySymbol[symbol].dispose();
_symbolDataBySymbol.Remove(symbol);
}
foreach (var entry in _symbolByDatasetSymbol)
{
if (entry.Value == symbol)
{
_symbolByDatasetSymbol.Remove(entry.Key);
}
}
}
}
}
public class SymbolData
{
private QCAlgorithm _algorithm;
public Symbol datasetSymbol;
public SymbolData(QCAlgorithm algorithm, Symbol symbol)
{
_algorithm = algorithm;
// Requesting data to get 2 days estimated relative ranking
datasetSymbol = algorithm.AddData<BrainStockRanking2Day>(symbol).Symbol;
// Historical data
var history = algorithm.History<BrainStockRanking2Day>(datasetSymbol, 365, Resolution.Daily);
algorithm.Debug($"We got {history.Count()} items from our history request for {symbol}");
}
public void dispose()
{
// Unsubscribe from the Brain ML Ranking feed for this security to release computation resources
_algorithm.RemoveSecurity(datasetSymbol);
}
}
}
The following example lists US Equities having the highest 2-day rank.
#r "../QuantConnect.DataSource.BrainSentiment.dll"
using QuantConnect.DataSource;
var qb = new QuantBook();
// Requesting data
var aapl = qb.AddEquity("AAPL", Resolution.Daily).Symbol;
var symbol = qb.AddData<BrainStockRanking2Day>(aapl).Symbol;
// Historical data
var history = qb.History<BrainStockRanking2Day>(symbol, 30, Resolution.Daily);
foreach (BrainStockRanking2Day rank in history)
{
Console.WriteLine($"{rank} at {rank.EndTime}");
}
// Add Universe Selection
IEnumerable<Symbol> UniverseSelection(IEnumerable<BaseData> altCoarse)
{
return (from d in altCoarse.OfType<BrainStockRankingUniverse>()
orderby d.Rank2Days descending select d.Symbol).Take(10);
}
var universe = qb.AddUniverse<BrainStockRankingUniverse>(UniverseSelection);
// Historical Universe data
var universeHistory = qb.UniverseHistory(universe, qb.Time.AddDays(-5), qb.Time);
foreach (var ranks in universeHistory)
{
foreach (BrainStockRankingUniverse rank in ranks)
{
Console.WriteLine($"{rank.Symbol} 2-day rank at {rank.EndTime}: {rank.Rank2Days}");
}
}
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.Rank2Days, 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.Rank2Days}")
Brain ML Stock Ranking is allowed to be used in the cloud for personal and commercial projects with a subscription. The data is permissioned for use within the licensed organization only
Subscription Required | License Now
Brain ML Stock Ranking can be downloaded on premise with the LEAN CLI, for a charge per file downloaded. This download is for the licensed organization's internal LEAN use only and cannot be redistributed or converted in any format.
Starting at 100 QCC/file | Learn More
LEAN CLI is a cross-platform wrapper on the QuantConnect algorithmic trading engine called LEAN. The CLI makes using LEAN incredibly easy, reducing most of the pain points of developing and managing an algorithmic trading strategy to a few lines of bash.
Using the CLI you can download the same data QuantConnect hosts in the cloud for a small fee. These fees are per file downloaded, and are paid for in QuantConnect-Credits (QCC). We recommend purchasing credits to enable downloading.
The CLI command generator is a helpful tool to generate a copy-paste command to download this dataset from the form below.
lean data download \
--dataset "Brain ML Stock Ranking" \
--ticker "AAPL, MSFT" \
--horizon "3" \
--start "20240402" \
--end "20250402"
lean data download `
--dataset "Brain ML Stock Ranking" `
--ticker "AAPL, MSFT" `
--horizon "3" `
--start "20240402" `
--end "20250402"
Brain ML Ranking archived in LEAN format for on premise backtesting and research. One file per month, per ticker.
Harness Brain ML ranking data in the QuantConnect Cloud for your backtesting and live trading purposes.
Harness Brain ML ranking Universe data in the QuantConnect Cloud for your backtesting and live trading purposes.
What people are saying about this
This product has not received any reviews yet, be the first to post one!
Rate the Module:
Provider offers 3 licensing options
Explore free and paid datasets available on QuantConnect covering fundamentals, pricing, and alternative options.
Dataset Status from to
No Runs
OK
Degraded
Failure
Explore free and paid datasets available on QuantConnect covering fundamentals, pricing, and alternative options.
Lorem ipsum dolor sit amet conjectura lorem ipsum dolor sit amet conjectura lorem ipsum
Configuration Keys
Environment Variables
Lorem ipsum dolor sit amet conjectura lorem ipsum dolor sit amet conjectura lorem ipsum
File Link
Lorem ipsum dolor sit amet conjectura lorem ipsum dolor sit amet conjectura lorem ipsum
Lorem ipsum dolor sit amet conjectura lorem ipsum dolor sit amet conjectura lorem ipsum
Upload a manually created tar or zip file to all cloud data systems.
Add a link and click the Sync Dataset button to upload the dataset
Upload Destinations
The dataset synchronizer is an internal tool for the QuantConnect team to upload data to the
cloud data storage environments. It supports TAR files which are extracted in the root directory
of the cloud data environments.
Take extreme care to carefully structure your data TAR package with
the same folders as the LEAN data folder. Ensure all folders and file names are lowercase as Linux is case-sensitive.
Support
Algorithm Lab is your playground for developing and refining trading algorithms with QuantConnect. Utilize advanced tools, historical data, and robust backtesting to enhance your trading strategies. Transform your ideas into actionable insights and optimize your trading approach with ease.
Sign Up for FreeAlready have an account Log In.
â‘
â‘
â‘
â‘
â‘
Hover and click over the stars to rate us.
It looks like you are not fully satisfied with your experience on QuantConnect, please take a moment to let us know how we can improve our services for you:
If you have a minute to spare, please leave us a review on Trustpilot.
Stories like yours help others see the full potential of QuantConnect.
Organization Name |
---|
Upgrade to Team plan or higher to enable custom invoicing
Changes will be applied to future invoices.
Users will be able to join by following the link in the invitation email.
You’ve been invited by Jared Broad to join his G-Force Organization.
Would you like to accept the invitation?
Are you sure you want to delete the encryption key "undefined"?
Caution: We will not be able to decrypt encrypted projects without the original key.
Drag & Drop or
Keys are added to the local storage in your web browser and not uploaded to QuantConnect. To use an encrypted project on another computer you will need to bring a copy of the key.
This project is encrypted using the key .
This project will be encrypted using the key .