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,008 People Enrolled
Learn algorithmic trading with python for FX. Guided strategy development in easily digestible portions.
Author: QuantConnect
Free | 20,588 People Enrolled
Learn algorithmic trading with python for Futures. Guided strategy development in easily digestible portions.
Author: QuantConnect
Free | 7,423 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,792 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 Sentiment Indicator
Dataset by Brain
The Brain Sentiment Indicator dataset by Brain tracks the public sentiment around US Equities. The data covers 4,500 US Equities, starts in August 2016, and is delivered on a daily frequency. This dataset is created by analyzing financial news using Natural Language Processing techniques while taking into account the similarity and repetition of news on the same topic. The sentiment score assigned to each stock ranges from -1 (most negative) to +1 (most positive). The sentiment score corresponds to the average sentiment for each piece of news. The score is updated daily and is available on two time scales: 7 days and 30 days. For more information, see 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 Sentiment Indicator dataset:
self.aapl = self.add_equity("AAPL", Resolution.DAILY).symbol
self.dataset_7day_symbol = self.add_data(BrainSentimentIndicator7Day, self.aapl).symbol
self.dataset_30day_symbol = self.add_data(BrainSentimentIndicator30Day, self.aapl).symbol
self._universe = self.add_universe(BrainSentimentIndicatorUniverse, self.universe_selection)
_symbol = AddEquity("AAPL", Resolution.Daily).Symbol;
_dataset7DaySymbol = AddData<BrainSentimentIndicator7Day>(_symbol).Symbol;
_dataset30DaySymbol = AddData<BrainSentimentIndicator30Day>(_symbol).Symbol;
_universe = AddUniverse<BrainSentimentIndicatorUniverse>(UniverseSelection);
The following table describes the dataset properties:
Property | Value |
---|---|
Start Date | August 2016 |
Asset Coverage* | 4,500 US Equities |
Data Density | Sparse |
Resolution | Daily |
Timezone | UTC |
The Brain Sentiment Indicator dataset enables you to incorporate sentiment from financial news sources into your strategies. Examples include the following strategies:
Disclaimer: The dataset is provided by the data provider for informational purposes only and does 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 Sentiment Indicator dataset provides BrainSentimentIndicatorBase and BrainSentimentIndicatorUniverse objects.
BrainSentimentIndicatorBase objects have the following attributes:
BrainSentimentIndicatorUniverse objects have the following attributes:
To add Brain Sentiment Indicator 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 BrainSentimentDataAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2019, 1, 1)
self.set_end_date(2021, 7, 8)
self.set_cash(100000)
symbol = self.add_equity("AAPL", Resolution.DAILY).symbol
self.dataset_7day_symbol = self.add_data(BrainSentimentIndicator7Day, symbol).symbol
self.dataset_30day_symbol = self.add_data(BrainSentimentIndicator30Day, symbol).symbol
namespace QuantConnect
{
public class BrainSentimentDataAlgorithm : QCAlgorithm
{
private Symbol _dataset7DaySymbol, _dataset30DaySymbol;
public override void Initialize()
{
SetStartDate(2019, 1, 1);
SetEndDate(2021, 7, 8);
SetCash(100000);
var symbol = AddEquity("AAPL", Resolution.Daily).Symbol;
_dataset7DaySymbol = AddData<BrainSentimentIndicator7Day>(symbol).Symbol;
_dataset30DaySymbol = AddData<BrainSentimentIndicator30Day>(symbol).Symbol;
}
}
}
To get the current Brain Sentiment Indicator 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.dataset_7day_symbol):
data_point = slice[self.dataset_7day_symbol]
self.log(f"{self.dataset_7day_symbol} sentiment at {slice.time}: {data_point.sentiment}")
if slice.contains_key(self.dataset_30day_symbol):
data_point = slice[self.dataset_30day_symbol]
self.log(f"{self.dataset_30day_symbol} sentiment at {slice.time}: {data_point.sentiment}")
public override void OnData(Slice slice)
{
if (slice.ContainsKey(_dataset7DaySymbol))
{
var dataPoint = slice[_dataset7DaySymbol];
Log($"{_dataset7DaySymbol} sentiment at {slice.Time}: {dataPoint.Sentiment}");
}
if (slice.ContainsKey(_dataset30DaySymbol))
{
var dataPoint = slice[_dataset30DaySymbol];
Log($"{_dataset30DaySymbol} sentiment at {slice.Time}: {dataPoint.Sentiment}");
}
}
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(BrainSentimentIndicator7Day).items():
self.log(f"{dataset_symbol} sentiment at {slice.time}: {data_point.sentiment}")
for dataset_symbol, data_point in slice.get(BrainSentimentIndicator30Day).items():
self.log(f"{dataset_symbol} sentiment at {slice.time}: {data_point.sentiment}")
public override void OnData(Slice slice)
{
foreach (var kvp in slice.Get<BrainSentimentIndicator7Day>())
{
var datasetSymbol = kvp.Key;
var dataPoint = kvp.Value;
Log($"{datasetSymbol} sentiment at {slice.Time}: {dataPoint.Sentiment}");
}
foreach (var kvp in slice.Get<BrainSentimentIndicator30Day>())
{
var datasetSymbol = kvp.Key;
var dataPoint = kvp.Value;
Log($"{datasetSymbol} sentiment at {slice.Time}: {dataPoint.Sentiment}");
}
}
To get historical Brain Sentiment Indicator 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
week_history_df = self.history(self.dataset_7day_symbol, 100, Resolution.DAILY)
month_history_df = self.history(self.dataset_30day_symbol, 100, Resolution.DAILY)
history_df = self.history([self.dataset_7day_symbol, self.dataset_30day_symbol], 100, Resolution.DAILY)
# Dataset objects
week_history_bars = self.history[BrainSentimentIndicator7Day](self.dataset_7day_symbol, 100, Resolution.DAILY)
month_history_bars = self.history[BrainSentimentIndicator30Day](self.dataset_30day_symbol, 100, Resolution.DAILY)
// Dataset objects
var weekHistory = History<BrainSentimentIndicator7Day>(_dataset7DaySymbol, 100, Resolution.Daily);
var monthHistory = History<BrainSentimentIndicator30Day>(_dataset30DaySymbol, 100, Resolution.Daily);
// Slice objects
var history = History(new[] {_dataset7DaySymbol, _dataset30DaySymbol}, 100, Resolution.Daily);
For more information about historical data, see History Requests.
To select a dynamic universe of US Equities based on Brain Sentiment Indicator data, call the AddUniverseadd_universe method with the BrainSentimentIndicatorUniverse class and a selection function.
def initialize(self) -> None:
self._universe = self.add_universe(BrainSentimentIndicatorUniverse, self.universe_selection)
def universe_selection(self, alt_coarse: List[BrainSentimentIndicatorUniverse]) -> List[Symbol]:
return [d.symbol for d in alt_coarse \
if d.total_article_mentions7_days > 0 \
and d.sentiment7_days]
private Universe _universe;
public override void Initialize()
{
_universe = AddUniverse<BrainSentimentIndicatorUniverse>(altCoarse=>
{
return from d in altCoarse.OfType<BrainSentimentIndicatorUniverse>()
where d.TotalArticleMentions7Days > 0m && d.Sentiment7Days > 0m
select d.Symbol;
});
}
The Brain Sentiment Indicator universe runs at 7 AM Eastern Time (ET) in live trading. 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 sentiments in universeHistory)
{
foreach (BrainSentimentIndicatorUniverse sentiment in sentiments)
{
Log($"{sentiment.Symbol} 7-day sentiment at {sentiment.EndTime}: {sentiment.Sentiment7Days}");
}
}
# DataFrame example where the columns are the BrainSentimentIndicatorUniverse attributes:
history_df = self.history(self._universe, 30, Resolution.DAILY, flatten=True)
# Series example where the values are lists of BrainSentimentIndicatorUniverse objects:
universe_history = self.history(self._universe, 30, Resolution.DAILY)
for (_, time), sentiments in universe_history.items():
for sentiment in sentiments:
self.log(f"{sentiment.symbol} 7-day sentiment at {sentiment.end_time}: {sentiment.sentiment7_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 sentiments in universeHistory)
{
foreach (BrainSentimentIndicatorUniverse sentiment in sentiments)
{
Console.WriteLine($"{sentiment.Symbol} 7-day sentiment at {sentiment.EndTime}: {sentiment.Sentiment7Days}");
}
}
# DataFrame example where the columns are the BrainSentimentIndicatorUniverse attributes:
history_df = qb.universe_history(universe, qb.time-timedelta(30), qb.time, flatten=True)
# Series example where the values are lists of BrainSentimentIndicatorUniverse objects:
universe_history = qb.universe_history(universe, qb.time-timedelta(30), qb.time)
for (_, time), sentiments in universe_history.items():
for sentiment in sentiments:
print(f"{sentiment.symbol} 7-day sentiment at {sentiment.end_time}: {sentiment.sentiment7_days}")
You can call the Historyhistory method in Research.
To remove a subscription, call the RemoveSecurityremove_security method.
self.remove_security(self.dataset_7day_symbol)
self.remove_security(self.dataset_30day_symbol)
RemoveSecurity(_dataset7DaySymbol);
RemoveSecurity(_dataset30DaySymbol);
If you subscribe to Brain Sentiment Indicator 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 Sentiment Indicator dataset provides BrainSentimentIndicatorBase and BrainSentimentIndicatorUniverse objects.
BrainSentimentIndicatorBase objects have the following attributes:
BrainSentimentIndicatorUniverse objects have the following attributes:
The following example algorithm buys Apple when the 30-day Brain Sentiment indicator increases. Otherwise, it remains in cash.
from AlgorithmImports import *
from QuantConnect.DataSource import *
class BrainSentimentDataAlgorithm(QCAlgorithm):
latest_sentiment_value = None
target_holdings = 0
def initialize(self) -> None:
self.set_start_date(2019, 1, 1)
self.set_end_date(2021, 7, 8)
self.set_cash(100000)
# Requesting the processed longer term (30-day) sentiment score data for sentiment trading
self.aapl = self.add_equity("AAPL", Resolution.DAILY).symbol
self.dataset_symbol = self.add_data(BrainSentimentIndicator30Day, self.aapl).symbol
# Historical data
history = self.history(self.dataset_symbol, 100, Resolution.DAILY)
self.debug(f"We got {len(history)} items from our history request for {self.dataset_symbol}")
if history.empty:
return
# Warm up historical sentiment values, cache for comparing last sentiment score to trade, making it immediately tradable signal
previous_sentiment_values = history.loc[self.dataset_symbol].sentiment.values
for sentiment in previous_sentiment_values:
self.update(sentiment)
def update(self, sentiment: float) -> None:
# Comparing the last sentiment score and decide to buy if the sentiment increases to ride the popularity
if self.latest_sentiment_value is not None:
self.target_holdings = int(sentiment > self.latest_sentiment_value)
self.latest_sentiment_value = sentiment
def on_data(self, slice: Slice) -> None:
# Update trade direction based on updated data
if slice.contains_key(self.dataset_symbol):
sentiment = slice[self.dataset_symbol].sentiment
self.update(sentiment)
# Ensure we have security data in the current slice to avoid stale fill
if not (slice.contains_key(self.aapl) and slice[self.aapl] is not None):
return
# Buy if sentiment increase, liquidate otherwise to ride on the popularity of the equity
if self.target_holdings != self.portfolio.invested:
self.set_holdings(self.aapl, self.target_holdings)
using QuantConnect.DataSource;
namespace QuantConnect
{
public class BrainSentimentDataAlgorithm : QCAlgorithm
{
private Symbol _symbol;
private Symbol _datasetSymbol;
private decimal? _latestSentimentValue = null;
private int _targetHoldings = 0;
public override void Initialize()
{
SetStartDate(2019, 1, 1);
SetEndDate(2021, 7, 8);
SetCash(100000);
// Requesting the processed longer term (30-day) sentiment score data for sentiment trading
_symbol = AddEquity("AAPL", Resolution.Daily).Symbol;
_datasetSymbol = AddData<BrainSentimentIndicator30Day>(_symbol).Symbol;
// Historical data
var history = History<BrainSentimentIndicator30Day>(_datasetSymbol, 100, Resolution.Daily);
Debug($"We got {history.Count()} items from our history request for {_datasetSymbol}");
// Warm up historical sentiment values, cache for comparing last sentiment score to trade, making it immediately tradable signal
var previousSentimentValues = history.Select(x => x.Sentiment);
foreach (var sentiment in previousSentimentValues)
{
Update(sentiment);
}
}
public void Update(decimal sentiment)
{
// Comparing the last sentiment score and decide to buy if the sentiment increases to ride the popularity
if (_latestSentimentValue != null)
{
_targetHoldings = sentiment > _latestSentimentValue ? 1 : 0;
}
_latestSentimentValue = sentiment;
}
public override void OnData(Slice slice)
{
// Update trade direction based on updated data
if (slice.ContainsKey(_datasetSymbol))
{
var sentiment = slice[_datasetSymbol].Sentiment;
Update(sentiment);
}
// Ensure we have security data in the current slice to avoid stale fill
// Buy if sentiment increase, liquidate otherwise to ride on the popularity of the equity
if (slice.Bar.ContainsKey(_symbol) && _targetHoldings == 1 != Portfolio.Invested)
{
SetHoldings(_symbol, _targetHoldings);
}
}
}
}
The following example algorithm creates a dynamic universe of US Equities that have been mentioned in an article over the last seven days. It then buys the subset of Equities that have increasing sentiment and forms an equal-weighted portfolio.
from AlgorithmImports import *
from QuantConnect.DataSource import *
class BrainSentimentDataAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2019, 1, 1)
self.set_end_date(2021, 7, 8)
self.set_cash(100000)
self.settings.minimum_order_margin_portfolio_percentage = 0
self.universe_settings.resolution = Resolution.DAILY
# Filter base on sentiment data
self.add_universe(BrainSentimentIndicatorUniverse, self.universe_selection)
self.add_alpha(BrainSentimentAlphaModel())
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
self.add_risk_management(NullRiskManagementModel())
self.set_execution(ImmediateExecutionModel())
def universe_selection(self, alt_coarse: List[BrainSentimentIndicatorUniverse]) -> List[Symbol]:
# Filter for any sentiment on last 7 days to trade on sentiment news
return [d.symbol for d in alt_coarse \
if d.SentimentalArticleMentions7Days is not None and d.SentimentalArticleMentions7Days > 0]
class BrainSentimentAlphaModel(AlphaModel):
symbol_data_by_symbol = {}
def update(self, algorithm: QCAlgorithm, slice: Slice) -> List[Insight]:
insights = []
for symbol, symbol_data in self.symbol_data_by_symbol.items():
# Update trade direction based on updated data
if slice.contains_key(symbol_data.dataset_symbol) and slice[symbol_data.dataset_symbol] is not None:
sentiment = slice[symbol_data.dataset_symbol].sentiment
symbol_data.update(sentiment)
# Ensure we have security data in the current slice to avoid stale fill
if not (slice.contains_key(symbol) and slice[symbol] is not None):
continue
# Buy if sentiment increase, liquidate otherwise to ride on the popularity of the equity
if symbol_data.target_direction == InsightDirection.UP != algorithm.portfolio[symbol].invested:
insights.append(Insight.price(symbol, timedelta(days=100), symbol_data.target_direction))
return insights
def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
for security in changes.added_securities:
symbol = security.symbol
self.symbol_data_by_symbol[symbol] = SymbolData(algorithm, symbol)
for security in changes.removed_securities:
symbol_data = self.symbol_data_by_symbol.pop(security.symbol, None)
if symbol_data:
symbol_data.dispose()
class SymbolData:
target_direction = InsightDirection.FLAT
_latest_sentiment_value = None
def __init__(self, algorithm: QCAlgorithm, symbol: Symbol) -> None:
self.algorithm = algorithm
# Requesting the processed longer term (30-day) sentiment score data for sentiment trading
self.dataset_symbol = algorithm.add_data(BrainSentimentIndicator30Day, symbol).symbol
# Historical data
history = algorithm.history(self.dataset_symbol, 100, Resolution.DAILY)
algorithm.debug(f"We got {len(history)} items from our history request for {self.dataset_symbol}")
if history.empty:
return
# Warm up historical sentiment values, cache for comparing last sentiment score to trade, making it immediately tradable signal
previous_sentiment_values = history.loc[self.dataset_symbol].sentiment.values
for sentiment in previous_sentiment_values:
self.update(sentiment)
def dispose(self) -> None:
# Unsubscribe from the Brain Sentiment feed for this security to release computational resources
self.algorithm.remove_security(self.dataset_symbol)
def update(self, sentiment: float) -> None:
# Comparing the last sentiment score and decide to buy if the sentiment increases to ride the popularity
if self._latest_sentiment_value is not None:
if sentiment > self._latest_sentiment_value:
self.target_direction = InsightDirection.UP
else:
self.target_direction = InsightDirection.FLAT
self._latest_sentiment_value = sentiment
using QuantConnect.DataSource;
namespace QuantConnect
{
public class BrainSentimentDataAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2019, 1, 1);
SetEndDate(2021, 7, 8);
SetCash(100000);
Settings.MinimumOrderMarginPortfolioPercentage = 0;
UniverseSettings.Resolution = Resolution.Daily;
// Filter by sentiment data
AddUniverse<BrainSentimentIndicatorUniverse>(altCoarse =>
{
// Filter for any sentiment on last 7 days to trade on sentiment news
return from d in altCoarse.OfType<BrainSentimentIndicatorUniverse>()
where d.TotalArticleMentions7Days > 0m
select d.Symbol;
});
AddAlpha(new BrainSentimentAlphaModel());
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
AddRiskManagement(new NullRiskManagementModel());
SetExecution(new ImmediateExecutionModel());
}
}
public class BrainSentimentAlphaModel : AlphaModel
{
private Dictionary<Symbol, SymbolData> _symbolDataBySymbol = new Dictionary<Symbol, SymbolData>();
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice slice)
{
var insights = new List<Insight>();
foreach (var entry in _symbolDataBySymbol)
{
var symbol = entry.Key;
var symbolData = entry.Value;
// Update trade direction based on updated data
if (slice.ContainsKey(symbolData.datasetSymbol) && slice[symbolData.datasetSymbol] != null)
{
var sentiment = slice[symbolData.datasetSymbol].Sentiment;
symbolData.Update(sentiment);
}
// Ensure we have security data in the current slice to avoid stale fill
if (!(slice.ContainsKey(symbol) && slice[symbol] != null))
{
continue;
}
// Buy if sentiment increase, liquidate otherwise to ride on the popularity of the equity
if (symbolData.targetDirection == InsightDirection.Up != algorithm.Portfolio[symbol].Invested)
{
insights.Add(Insight.Price(symbol, TimeSpan.FromDays(365), symbolData.targetDirection));
}
}
return insights;
}
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
{
foreach (var security in changes.AddedSecurities)
{
var symbol = security.Symbol;
_symbolDataBySymbol.Add(symbol, new SymbolData(algorithm, symbol));
}
foreach (var security in changes.RemovedSecurities)
{
var symbol = security.Symbol;
if (_symbolDataBySymbol.ContainsKey(symbol))
{
_symbolDataBySymbol[symbol].dispose();
_symbolDataBySymbol.Remove(symbol);
}
}
}
}
public class SymbolData
{
public Symbol datasetSymbol;
public InsightDirection targetDirection = InsightDirection.Flat;
private QCAlgorithm _algorithm;
private decimal? _latestSentimentValue = null;
public SymbolData(QCAlgorithm algorithm, Symbol symbol)
{
_algorithm = algorithm;
// Requesting the processed longer term (30-day) sentiment score data for sentiment trading
datasetSymbol = algorithm.AddData<BrainSentimentIndicator30Day>(symbol).Symbol;
// Historical data
var history = algorithm.History<BrainSentimentIndicator30Day>(datasetSymbol, 100, Resolution.Daily);
algorithm.Debug($"We got {history.Count()} items from our history request for {symbol}");
if (history.Count() == 0)
{
return;
}
// Warm up historical sentiment values, cache for comparing last sentiment score to trade, making it immediately tradable signal
var previousSentimentValues = history.Select(x => x.Sentiment);
foreach (var sentiment in previousSentimentValues)
{
Update(sentiment);
}
}
public void dispose()
{
// Unsubscribe from the Brain Sentiment feed for this security to release computational resources
_algorithm.RemoveSecurity(datasetSymbol);
}
public void Update(decimal sentiment)
{
// Comparing the last sentiment score and decide to buy if the sentiment increases to ride the popularity
if (_latestSentimentValue != null)
{
targetDirection = sentiment > _latestSentimentValue ? InsightDirection.Up : InsightDirection.Flat;
}
_latestSentimentValue = sentiment;
}
}
}
The following example lists US Equities having the highest 7-day sentiment.
#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<BrainSentimentIndicator30Day>(aapl).Symbol;
// Historical data
var history = qb.History<BrainSentimentIndicator30Day>(symbol, 30, Resolution.Daily);
foreach (BrainSentimentIndicator30Day sentiment in history)
{
Console.WriteLine($"{sentiment} at {sentiment.EndTime}");
}
// Add Universe Selection
IEnumerable<Symbol> UniverseSelection(IEnumerable<BaseData> altCoarse)
{
return (from d in altCoarse.OfType<BrainSentimentIndicatorUniverse>()
orderby d.Sentiment7Days descending select d.Symbol).Take(10);
}
var universe = qb.AddUniverse<BrainSentimentIndicatorUniverse>(UniverseSelection);
// Historical Universe data
var universeHistory = qb.UniverseHistory(universe, qb.Time.AddDays(-5), qb.Time);
foreach (var sentiments in universeHistory)
{
foreach (BrainSentimentIndicatorUniverse sentiment in sentiments)
{
Console.WriteLine($"{sentiment.Symbol} 7-day sentiment at {sentiment.EndTime}: {sentiment.Sentiment7Days}");
}
}
qb = QuantBook()
# Requesting Data
aapl = qb.add_equity("AAPL", Resolution.DAILY).symbol
symbol = qb.add_data(BrainSentimentIndicator30Day, aapl).symbol
# Historical data
history = qb.history(BrainSentimentIndicator30Day, symbol, 30, Resolution.DAILY)
for (symbol, time), row in history.iterrows():
print(f"{symbol} sentiment at {time}: {row['sentiment']}")
# Add Universe Selection
def universe_selection(alt_coarse: List[BrainSentimentIndicatorUniverse]) -> List[Symbol]:
return [d.symbol for d in sorted([x for x in alt_coarse if x.SentimentalArticleMentions7Days],
key=lambda x: x.SentimentalArticleMentions7Days, reverse=True)[:10]]
universe = qb.add_universe(BrainSentimentIndicatorUniverse, universe_selection)
# Historical Universe data
universe_history = qb.universe_history(universe, qb.time-timedelta(5), qb.time)
for (_, time), sentiments in universe_history.items():
for sentiment in sentiments:
print(f"{sentiment.symbol} 7-day sentiment at {sentiment.end_time}: {sentiment.SentimentalArticleMentions7Days}")
Brain Sentiment Indicator 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 Sentiment Indicator 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 Sentiment Indicator" \
--ticker "AAPL, MSFT" \
--scale "7" \
--start "20240402" \
--end "20250402"
lean data download `
--dataset "Brain Sentiment Indicator" `
--ticker "AAPL, MSFT" `
--scale "7" `
--start "20240402" `
--end "20250402"
Brain Sentiment Indicator archived in LEAN format for on premise backtesting and research. One file per ticker per month.
Harness Brain Sentiment analysis data in the QuantConnect Cloud for your backtesting and live trading purposes.
Harness Brain Sentiment Universe analysis 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 .