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 | 95,933 People Enrolled
Learn algorithmic trading with python for FX. Guided strategy development in easily digestible portions.
Author: QuantConnect
Free | 20,562 People Enrolled
Learn algorithmic trading with python for Futures. Guided strategy development in easily digestible portions.
Author: QuantConnect
Free | 7,417 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,745 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 >
US Fundamental Data
Dataset by Morningstar
The US Fundamental Data by Morningstar tracks US Equity fundamentals. The data covers 8,000 US Equities, starts in January 1998, and is delivered on a daily frequency. This dataset is created by using a combination of string matching, Regular Expressions, and Machine Learning to gather the fundamental data published by companies.
For older symbols, the file date is approximated 45 days after the as of date. When a filing date is present on the Morningstar data, it is used. As we are a quant platform, all the data is loaded using "As Original Reported" figures. If there was a mistake reporting the figure, this will not be fixed later. The market typically responds quickly to these initially reported figures. Data is available for multiple periods depending on the property. Periods available include: 1 mo, 2 mo, 3 mo, 6 mo, 9 mo, 12 mo, 1 Yr, 2 Yr, 3 Yr, and 5 Yr. Morningstar symbols cover the NYSE, NASDAQ, AMEX, and BATS exchanges.
In live trading, Morningstar data is delivered to your algorithm at approximately 6 am each day. The majority of the fundamental data update occurs once per month. This includes updates to all of the key information for each security Morningstar supports. On top of this monthly update, there are daily updates of the financial ratios.
As Morningstar data arrives, it updates the master copy and is passed into your algorithm, similar to how TradeBars are fill-forwarded in your data feed. If there have been no updates for a day, you'll receive the same fundamental data.
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.
QuantConnect/LEAN combines the data of this dataset with US Coarse Universe data in runtime.
Morningstar was founded by Joe Mansueto in 1984 with the goal of empowering investors by connecting people to the investing information and tools they need. Morningstar provides access extensive line of products and services for individual investors, financial advisors, asset managers, and retirement plan providers. Morningstar provides data on approximately 525,000 investment offerings including stocks, mutual funds, and similar vehicles, along with real-time global market data on nearly 18 million equities, indexes, futures, options, commodities, and precious metals, in addition to foreign exchange and Treasury markets. Morningstar also offers investment management services through its investment advisory subsidiaries, with $244 billion in assets under advisement or management as of 2021.
The following snippets demonstrate how to request data from the US Fundamental dataset:
equity = self.add_equity("IBM")
ibm_fundamental = equity.fundamentals
var equity = AddEquity("IBM");
var ibmFundamental = equity.Fundamentals;
ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)
ibm_fundamental = self.fundamentals(ibm)
var ibm = QuantConnect.Symbol.Create("IBM", SecurityType.Equity, Market.USA);
var ibmFundamental = Fundamentals(ibm);
def initialize(self) -> None:
self._universe = self.add_universe(self.fundamental_filter_function)
def fundamental_filter_function(self, fundamental: List[Fundamental]):
filtered = [f for f in fundamental if f.has_fundamental_data and f.price > 10 and not np.isnan(f.valuation_ratios.pe_ratio)]
sorted_by_pe_ratio = sorted(filtered, key=lambda f: f.valuation_ratios.pe_ratio)
return [f.symbol for f in sorted_by_pe_ratio[:10]]
public override void Initialize()
{
_universe = AddUniverseSelection(new FundamentalUniverseSelectionModel(FundamentalFilterFunction));
}
public override List<Symbol> FundamentalFilterFunction(List<Fundamental> fundamental)
{
return (from f in fundamental
where f.HasFundamentalData && f.Price > 10 && !Double.IsNaN(f.ValuationRatios.PERatio)
orderby f.ValuationRatios.PERatio
select f.Symbol).Take(10);
}
The following table describes the dataset properties:
Property | Value |
---|---|
Start Date | January 1998 |
Asset Coverage | 8,000 US Equities |
Corporate Indicators / Tracked Fields | 900 Fields |
Data Density | Sparse |
Resolution | Daily |
Timezone | New York |
The US Fundamentals dataset enables you to design strategies harnessing fundamental data points. Examples include the following strategies:
For more example algorithms, see Examples.
The US Fundamentals dataset provides Fundamental objects. To filter Fundamental objects, you can use the MorningstarSectorCode, MorningstarIndustryGroupCode, and MorningstarIndustryCode enumeration values.
Fundamental objects have the following attributes:
Sectors are large super categories of data. To access the sector of an Equity, use the MorningstarSectorCode property.
filteredFundamentals = fundamental.Where(x =>
x.AssetClassification.MorningstarSectorCode == MorningstarSectorCode.Technology);
filtered_fundamentals = [x for x in fundamental
if x.asset_classification.morningstar_sector_code == MorningstarSectorCode.TECHNOLOGY]
The MorningstarSectorCode enumeration has the following members:
Industry groups are clusters of related industries that tie together. To access the industry group of an Equity, use the MorningstarIndustryGroupCode property.
filteredFundamentals = fundamental.Where(x =>
x.AssetClassification.MorningstarIndustryGroupCode == MorningstarIndustryGroupCode.ApplicationSoftware);
filtered_fundamentals = [x for x in fundamental
if x.asset_classification.morningstar_industry_group_code == MorningstarIndustryGroupCode.APPLICATION_SOFTWARE]
The MorningstarIndustryGroupCode enumeration has the following members:
Industries are the finest classification level available and are the individual industries according to the Morningstar classification system. To access the industry group of an Equity, use the MorningstarIndustryCode property.
filteredFundamentals = fundamental.Where(x =>
x.AssetClassification.MorningstarIndustryCode == MorningstarIndustryCode.SoftwareApplication);
filtered_fundamentals = [x for x in fundamental
if x.asset_classification.morningstar_industry_code == MorningstarIndustryCode.SOFTWARE_APPLICATION]
The MorningstarIndustryCode enumeration has the following members:
The exchange ID represents the exchange that lists the Equity. To access the exchange ID of an Equity, use the PrimaryExchangeID property.
filteredFundamentals = fundamental.Where(x =>
x.CompanyReference.PrimaryExchangeID == "NAS");
filtered_fundamentals = [x for x in fundamental
if x.company_reference.primary_exchange_id == "NAS"]
The exchanges are represented by the following string values:
String Representation | Exchange |
---|---|
NYS | New York Stock Exchange (NYSE) |
NAS | NASDAQ |
ASE | American Stock Exchange (AMEX) |
TSE | Tokyo Stock Exchange |
AMS | Amsterdam Internet Exchange |
SGO | Santiago Stock Exchange |
XMAD | Madrid Stock Exchange |
ASX | Australian Securities Exchange |
BVMF | B3 (stock exchange) |
LON | London Stock Exchange |
TKS | Istanbul Stock Exchange Settlement and Custody Bank |
SHG | Shanghai Exchange |
LIM | Lima Stock Exchange |
FRA | Frankfurt Stock Exchange |
JSE | Johannesburg Stock Exchange |
MIL | Milan Stock Exchange |
TAE | Tel Aviv Stock Exchange |
STO | Stockholm Stock Exchange |
ETR | Deutsche Boerse Xetra Core |
PAR | Paris Stock Exchange |
BUE | Buenos Aires Stock Exchange |
KRX | Korea Exchange |
SWX | SIX Swiss Exchange |
PINX | Pink Sheets (OTC) |
CSE | Canadian Securities Exchange |
PHS | Philippine Stock Exchange |
MEX | Mexican Stock Exchange |
TAI | Taiwan Stock Exchange |
IDX | Indonesia Stock Exchange |
OSL | Oslo Stock Exchange |
BOG | Colombia Stock Exchange |
NSE | National Stock Exchange of India |
HEL | Nasdaq Helsinki |
MISX | Moscow Exchange |
HKG | Hong Kong Stock Exchange |
IST | Istanbul Stock Exchange |
BOM | Bombay Stock Exchange |
TSX | Toronto Stock Exchange |
BRU | Brussels Stock Exchange |
BATS | BATS Global Markets |
ARCX | NYSE Arca |
GREY | Grey Market (OTC) |
DUS | Dusseldorf Stock Exchange |
BER | Berlin Stock Exchange |
ROCO | Taipei Exchange |
CNQ | Canadian Trading and Quotation System Inc. |
BSP | Bangko Sentral ng Pilipinas |
NEOE | NEO Exchange |
You don't need any special code to request US Fundamental Data. You can access the current and historical fundamental data for any of the US Equities that this dataset includes.
class MorningStarDataAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2021, 1, 1)
self.set_end_date(2021, 7, 1)
self.set_cash(100000)
self.universe_settings.asynchronous = True
# Option 1: Subscribe to individual US Equity assets
self.add_equity("IBM")
# Option 2A: Create a fundamental universe (classic version)
self._universe = self.add_universe(self.fundamental_function)
# Option 2B: Create a fundamental universe (framework version)
self.add_universe_selection(FundamentalUniverseSelectionModel(self.fundamental_function))
namespace QuantConnect
{
private Universe _universe;
public class MorningStarDataAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 7, 1);
SetCash(100000);
UniverseSettings.Asynchronous = true;
// Option 1: Subscribe to individual US Equity assets
AddEquity("IBM");
// Option 2A: Create a fundamental universe (classic version)
_universe = AddUniverse(FundamentalFilterFunction);
// Option 2B: Create a fundamental universe (framework version)
AddUniverseSelection(new FundamentalUniverseSelectionModel(FundamentalFilterFunction));
}
}
}
For more information about universe settings, see Settings.
If you add a fundamental universe to your algorithm, you can access fundamental data in the universe selection function.
def fundamental_function(self, fundamental: List[Fundamental]) -> List[Symbol]:
return [f.symbol for f in fundamental if f.price > 10 and f.valuation_ratios.pe_ratio > 30]
public IEnumerable<Symbol> FundamentalFunction(IEnumerable<Fundamental> fundamental)
{
return fundamental.Where(f => f.Price > 10 && f.ValuationRatios.PERatios > 30).Select(f => f.Symbol);
}
To get fundamental data for Equities in your algorithm, use the Fundamentalsfundamentals property of the Equity objects. The fundamental data represent the corporate fundamentals for the current algorithm time.
fundamentals = self.securities[symbol].fundamentals
var fundamentals = Securities[symbol].Fundamentals;
To get fundamental data for Equities, regardless of whether or not you have subscribed to them in your algorithm, call the Fundamentalsfundamentals method. If you pass one Symbol, the method returns a Fundamental object. If you pass a list of Symbol objects, the method returns a list of Fundamental objects.
// Single asset
var ibm = QuantConnect.Symbol.Create("IBM", SecurityType.Equity, Market.USA);
var ibmFundamental = Fundamentals(ibm);
// Multiple assets
var nb = QuantConnect.Symbol.Create("NB", SecurityType.Equity, Market.USA);
var fundamentals = Fundamentals(new List<Symbol>{ nb, ibm }).ToList();
# Single asset
ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)
ibm_fundamental = self.fundamentals(ibm)
# Multiple assets
nb = Symbol.create("NB", SecurityType.EQUITY, Market.USA)
fundamentals = self.fundamentals([ nb, ibm ])
You can get historical fundamental data in an algorithm and in the Research Environment.
To get historical fundamental data in an algorithm, call the Historyhistory method with Fundamental type and the Equity Symbol or the Universe object. If there is no data in the period you request, the history result is empty.
var ibm = QuantConnect.Symbol.Create("IBM", SecurityType.Equity, Market.USA);
// Fundamental objects
var fundamentalHistory = History<Fundamental>(ibm, TimeSpan.FromDays(30));
// Fundamentals objects for all US Equities (including delisted companies)
var fundamentalsHistory = History<Fundamentals>(TimeSpan.FromDays(30));
// Collection of Fundamental objects for all US Equities (including delisted companies)
var collectionHistory = History(_universe, 30, Resolution.Daily);
foreach (var fundamental in collectionHistory)
{
// Cast to Fundamental is required
var highestMarketCap = fundamental.OfType<Fundamental>().OrderByDescending(x => x.MarketCap).Take(5);
}
ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)
# DataFrame object where the columns are the Fundamental attributes
asset_df_history = self.history(Fundamental, ibm, timedelta(30), flatten=True)
# Fundamental objects
fundamental_history= self.history[Fundamental](ibm, timedelta(30))
# Fundamentals objects for all US Equities (including delisted companies)
fundamentals_history = self.history[Fundamentals](timedelta(30))
# Multi-index Series objects where the values are lists of Fundamental objects
series_history = self.history(self.universe, 30, Resolution.DAILY)
for (universe_symbol, time), fundamentals in series_history.items():
highest_market_cap = sorted(fundamentals, key=lambda x: x.market_cap)[-5:]
To get historical data in the Research Environment, call any of the preceding methods or call the UniverseHistoryuniverse_history method with the Universe object, a start date, and an end date. This method returns the filtered universe. Alternatively, call the GetFundamentalget_fundamental method with the Equity Symbol, a Fundamental property, a start date, and an end date. If there is no data in the period you request, the history result is empty.
# DataFrame object where the columns are the Fundamental attributes
universe_history_df = qb.universe_history(universe, qb.time-timedelta(30), qb.time, flatten=True)
# Multi-index Series objects where the values are lists of Fundamental objects
universe_history = qb.universe_history(universe, qb.time-timedelta(30), qb.time)
for (universe_symbol, time), fundamentals in universe_history.items():
for fundamental in fundamentals:
print(f"{fundamental.symbol} market cap at {fundamental.end_time}: {fundamental.market_cap}")
# DataFrame of a single Fundamental attribute
history = qb.get_fundamental(symbol, "ValuationRatios.pe_ratios", datetime(2021, 1, 1), datetime(2021, 7, 1))
var universeHistory = qb.UniverseHistory(universe, qb.Time.AddDays(-30), qb.Time);
foreach (var fundamentals in universeHistory)
{
foreach (Fundamental fundamental in fundamentals)
{
Console.WriteLine($"{fundamental.Symbol} market cap at {fundamental.EndTime}: {fundamental.MarketCap}");
}
}
var history = qb.GetFundamental(symbol, "ValuationRatios.PERatios", new DateTime(2021, 1, 1), new DateTime(2021, 7, 1));
For more information about historical US Equity fundamental data, see Equity Fundamental Data.
The US Fundamentals dataset provides Fundamental objects. To filter Fundamental objects, you can use the MorningstarSectorCode, MorningstarIndustryGroupCode, and MorningstarIndustryCode enumeration values.
Fundamental objects have the following attributes:
Sectors are large super categories of data. To access the sector of an Equity, use the MorningstarSectorCode property.
filteredFundamentals = fundamental.Where(x =>
x.AssetClassification.MorningstarSectorCode == MorningstarSectorCode.Technology);
filtered_fundamentals = [x for x in fundamental
if x.asset_classification.morningstar_sector_code == MorningstarSectorCode.TECHNOLOGY]
The MorningstarSectorCode enumeration has the following members:
Industry groups are clusters of related industries that tie together. To access the industry group of an Equity, use the MorningstarIndustryGroupCode property.
filteredFundamentals = fundamental.Where(x =>
x.AssetClassification.MorningstarIndustryGroupCode == MorningstarIndustryGroupCode.Software);
filtered_fundamentals = [x for x in fundamental
if x.asset_classification.morningstar_industry_group_code == MorningstarIndustryGroupCode.SOFTWARE]
The MorningstarIndustryGroupCode enumeration has the following members:
Industries are the finest classification level available and are the individual industries according to the Morningstar classification system. To access the industry group of an Equity, use the MorningstarIndustryCode property.
filteredFundamentals = fundamental.Where(x =>
x.AssetClassification.MorningstarIndustryCode == MorningstarIndustryCode.SoftwareApplication);
filtered_fundamentals = [x for x in fundamental
if x.asset_classification.morningstar_industry_code == MorningstarIndustryCode.SOFTWARE_APPLICATION]
The MorningstarIndustryCode enumeration has the following members:
The exchange ID represents the exchange that lists the Equity. To access the exchange ID of an Equity, use the PrimaryExchangeID property.
filteredFundamentals = fundamental.Where(x =>
x.CompanyReference.PrimaryExchangeID == "NAS");
filtered_fundamentals = [x for x in fundamental
if x.company_reference.primary_exchange_id == "NAS"]
The exchanges are represented by the following string values:
String Representation | Exchange |
---|---|
NYS | New York Stock Exchange (NYSE) |
NAS | NASDAQ |
ASE | American Stock Exchange (AMEX) |
TSE | Tokyo Stock Exchange |
AMS | Amsterdam Internet Exchange |
SGO | Santiago Stock Exchange |
XMAD | Madrid Stock Exchange |
ASX | Australian Securities Exchange |
BVMF | B3 (stock exchange) |
LON | London Stock Exchange |
TKS | Istanbul Stock Exchange Settlement and Custody Bank |
SHG | Shanghai Exchange |
LIM | Lima Stock Exchange |
FRA | Frankfurt Stock Exchange |
JSE | Johannesburg Stock Exchange |
MIL | Milan Stock Exchange |
TAE | Tel Aviv Stock Exchange |
STO | Stockholm Stock Exchange |
ETR | Deutsche Boerse Xetra Core |
PAR | Paris Stock Exchange |
BUE | Buenos Aires Stock Exchange |
KRX | Korea Exchange |
SWX | SIX Swiss Exchange |
PINX | Pink Sheets (OTC) |
CSE | Canadian Securities Exchange |
PHS | Philippine Stock Exchange |
MEX | Mexican Stock Exchange |
TAI | Taiwan Stock Exchange |
IDX | Indonesia Stock Exchange |
OSL | Oslo Stock Exchange |
BOG | Colombia Stock Exchange |
NSE | National Stock Exchange of India |
HEL | Nasdaq Helsinki |
MISX | Moscow Exchange |
HKG | Hong Kong Stock Exchange |
IST | Istanbul Stock Exchange |
BOM | Bombay Stock Exchange |
TSX | Toronto Stock Exchange |
BRU | Brussels Stock Exchange |
BATS | BATS Global Markets |
ARCX | NYSE Arca |
GREY | Grey Market (OTC) |
DUS | Dusseldorf Stock Exchange |
BER | Berlin Stock Exchange |
ROCO | Taipei Exchange |
CNQ | Canadian Trading and Quotation System Inc. |
BSP | Bangko Sentral ng Pilipinas |
NEOE | NEO Exchange |
The following example algorithm creates a dynamic universe of US Equities. The first stage filter selects the 100 most liquid US Equities and the second stage filter selects the 10 assets with the greatest PE ratio. The algorithm then forms an equal-weighted portfolio with the 10 assets in the universe.
from AlgorithmImports import *
from QuantConnect.DataSource import *
class MorningStarDataAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2021, 1, 1)
self.set_end_date(2021, 7, 1)
self.set_cash(100000)
self.universe_settings.resolution = Resolution.DAILY
self.universe_size = 10
# Add universe selection to filter with fundamental data
self.add_universe(self.fundamental_selection_function)
def fundamental_selection_function(self, fundamental: List[Fundamental]) -> List[Symbol]:
# Make sure fundamental data and PE ratio available
# To avoid penny stocks with high volatility, set price above $1
selected = [f for f in fundamental if f.has_fundamental_data and f.price > 1 and not np.isnan(f.valuation_ratios.pe_ratio)]
# Filter the top 100 high dollar volume equities to ensure liquidity
sorted_by_dollar_volume = sorted(selected, key=lambda f: f.dollar_volume, reverse=True)[:100]
# Get the top 10 PE Ratio stocks to follow speculations of a large number of capital
sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda f: f.valuation_ratios.pe_ratio, reverse=True)[:self.universe_size]
return [ f.symbol for f in sorted_by_pe_ratio ]
def on_data(self, slice: Slice) -> None:
# if we have no changes, do nothing
if self._changes is None: return
# liquidate removed securities, as not being the most popular stocks anymore
for security in self._changes.removed_securities:
if security.invested:
self.liquidate(security.symbol)
# we want 1/N allocation in each security in our universe to evenly dissipate risk
for security in self._changes.added_securities:
self.set_holdings(security.symbol, 1 / self.universe_size)
self._changes = None
def on_securities_changed(self, changes: SecurityChanges) -> None:
self._changes = changes
for security in changes.added_securities:
# Historical data
history = self.history(security.symbol, 7, Resolution.DAILY)
self.debug(f"We got {len(history)} from our history request for {security.symbol}")
using QuantConnect.DataSource;
namespace QuantConnect
{
public class MorningStarDataAlgorithm : QCAlgorithm
{
private int _universeSize = 10;
private SecurityChanges _changes = SecurityChanges.None;
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 7, 1);
SetCash(100000);
// Requesting data
UniverseSettings.Resolution = Resolution.Daily;
# Add universe selection to filter with fundamental data
AddUniverse(FundamentalSelectionFunction);
}
public IEnumerable<Symbol> FundamentalSelectionFunction(IEnumerable<Fundamental> fundamental)
{
// Make sure fundamental data and PE ratio available
// To avoid penny stocks with high volatility, set price above $1
// Filter the top 100 high dollar volume equities to ensure liquidity
// Get the top 10 PE Ratio stocks to follow speculations of a large number of capital
return fundamental
.Where(x => x.HasFundamentalData && x.Price > 1 && !Double.IsNaN(x.ValuationRatios.PERatio))
.OrderByDescending(x => x.DollarVolume)
.Take(100)
.OrderByDescending(x => x.ValuationRatios.PERatio)
.Take(_universeSize)
.Select(x => x.Symbol);
}
public override void OnData(Slice slice)
{
// if we have no changes, do nothing
if (_changes == SecurityChanges.None) return;
// liquidate removed securities, as not being the most popular stocks anymore
foreach (var security in _changes.RemovedSecurities)
{
if (security.Invested)
{
Liquidate(security.Symbol);
}
}
// we want 1/N allocation in each security in our universe to evenly dissipate risk
foreach (var security in _changes.AddedSecurities)
{
SetHoldings(security.Symbol, 1m / _universeSize);
}
_changes = SecurityChanges.None;
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
_changes = changes;
foreach (var security in changes.AddedSecurities)
{
// Historical data
var history = History(security.Symbol, 7, Resolution.Daily);
Debug($"We got {history.Count()} from our history request for {security.Symbol}");
}
}
}
}
The following example algorithm creates a dynamic universe of US Equities. The first stage filter selects the 100 most liquid US Equities and the second stage filter selects the 10 assets with the greatest PE ratio. The algorithm then forms an equal-weighted portfolio with the 10 assets in the universe.
from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
class MorningStarDataAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2021, 1, 1)
self.set_end_date(2021, 7, 1)
self.set_cash(100000)
# Add universe selection to filter with fundamental data
self.universe_settings.resolution = Resolution.DAILY
self.set_universe_selection(CustomFundamentalUniverseSelectionModel())
self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
# we want 1/N allocation in each security in our universe to evenly dissipate risk
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
self.add_risk_management(NullRiskManagementModel())
self.set_execution(ImmediateExecutionModel())
class CustomFundamentalUniverseSelectionModel(FundamentalUniverseSelectionModel):
def Select(self, algorithm: QCAlgorithm, fundamental: List[Fundamental]) -> List[Symbol]:
# Make sure fundamental data and PE ratio available
# To avoid penny stocks with high volatility, set price above $1
filtered = [x for x in fundamental if x.has_fundamental_data and x.price > 1 and not np.isnan(x.valuation_ratios.pe_ratio)]
# Filter the top 100 high dollar volume equities to ensure liquidity
sorted_by_dollar_volume = sorted(filtered, key=lambda x: x.dollar_volume, reverse=True)[:100]
# Get the top 10 PE Ratio stocks to follow speculations of a large number of capital
sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)[:10]
# take the top entries from our sorted collection
return [ x.symbol for x in sorted_by_pe_ratio ]
namespace QuantConnect
{
public class MorningStarDataAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 7, 1);
SetCash(100000);
// Add universe selection to filter with fundamental data
UniverseSettings.Resolution = Resolution.Daily;
AddUniverseSelection(new CustomFundamentalUniverseSelectionModel());
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
// we want 1/N allocation in each security in our universe to evenly dissipate risk
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
AddRiskManagement(new NullRiskManagementModel());
SetExecution(new ImmediateExecutionModel());
}
}
public class CustomFundamentalUniverseSelectionModel : FundamentalUniverseSelectionModel
{
public override IEnumerable<Symbol> Select(QCAlgorithm algorithm, IEnumerable<Fundamental> fundamental)
{
return fundamental
// Make sure fundamental data and PE ratio available
// To avoid penny stocks with high volatility, set price above $1
.Where(x => x.HasFundamentalData && x.Price > 1 && !Double.IsNaN(x.ValuationRatios.PERatio))
// Filter the top 100 high dollar volume equities to ensure liquidity
.OrderByDescending(x => x.DollarVolume)
.Take(100)
// Get the top 10 PE Ratio stocks to follow speculations of a large number of capital
.OrderByDescending(x => x.ValuationRatios.PERatio)
.Take(10)
.Select(x => x.Symbol);
}
}
}
The following example selects the 100 most liquid US Equities and lists the 10 assets with the greatest PE ratio.:
var qb = new QuantBook();
// Add Fundamental Universe Selection
IEnumerable<Symbol> FundamentalSelectionFunction(IEnumerable<Fundamental> fundamentals)
{
return fundamentals
.Where(x => !Double.IsNaN(x.ValuationRatios.PERatio))
.OrderByDescending(x => x.DollarVolume).Take(100)
.OrderByDescending(x => x.ValuationRatios.PERatio).Take(10)
.Select(x => x.Symbol);
}
var universe = qb.AddUniverse(FundamentalSelectionFunction);
// Historical Universe data
var universeHistory = qb.UniverseHistory(universe, qb.Time.AddDays(-30), qb.Time);
foreach (var fundamentals in universeHistory)
{
foreach (Fundamental fundamental in fundamentals)
{
Console.WriteLine($"{fundamental.Symbol} PE ratio at {fundamental.EndTime}: {fundamental.ValuationRatios.PERatio}");
}
}
qb = QuantBook()
# Add Fundamental Universe Selection
def fundamental_selection_function(fundamentals):
selected = [f for f in fundamentals if not np.isnan(f.valuation_ratios.pe_ratio)]
sorted_by_dollar_volume = sorted(selected, key=lambda f: f.dollar_volume, reverse=True)[:100]
sorted_by_pe_ratio = sorted(sorted_by_dollar_volume,
key=lambda f: f.valuation_ratios.pe_ratio, reverse=True)[:10]
return [ f.symbol for f in sorted_by_pe_ratio ]
universe = qb.add_universe(fundamental_selection_function)
# Historical Universe data
universe_history = qb.universe_history(universe, qb.time-timedelta(30), qb.time)
for (universe_symbol, time), fundamentals in universe_history.items():
for fundamental in fundamentals:
print(f"{fundamental.symbol} PE ratio volume at {fundamental.end_time}: {fundamental.valuation_ratios.pe_ratio}")
US Fundamental Data is allowed to be used in the cloud for personal and commercial projects for free. The data is permissioned for use within the licensed organization only
Free | Documentation
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.
Cloud access to Morning Star US Fundamental and Classification data since January 1998, available for research and universe selection.
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 1 licensing option
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 .