diff --git a/project-templates/csharp/ai/Main.cs b/project-templates/csharp/ai/Main.cs index 6bf16f5a4b..36a095591c 100644 --- a/project-templates/csharp/ai/Main.cs +++ b/project-templates/csharp/ai/Main.cs @@ -69,9 +69,9 @@ /// public class AccordVectorMachinesAlgorithm : QCAlgorithm { - // Define the size of the data used to train the model - // It will use _lookback sets with _inputSize members - // Those members are rate of return + // Define the size of the data used to train the model. + // It will use _lookback sets with _inputSize members. + // Those members are rate of return. private const int _lookback = 30; private const int _inputSize = 5; private Equity _equity; @@ -82,6 +82,7 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; Accord.Math.Random.Generator.Seed = 0; @@ -104,11 +105,11 @@ private void TrainAndTrade() return; } - // Convert the rolling window of rate of change into the Learn method + // Convert the rolling window of rate of change into the Learn method. var targets = new double[_lookback]; var inputs = new double[_lookback][]; - // Use the sign of the returns to predict the direction + // Use the sign of the returns to predict the direction. for (var i = 0; i < _lookback; i++) { var returns = new double[_inputSize]; @@ -121,13 +122,13 @@ private void TrainAndTrade() inputs[i] = returns; } - // Train SupportVectorMachine using SetHoldings("SPY", percentage); + // Train SupportVectorMachine using SetHoldings("SPY", percentage);. var teacher = new LinearCoordinateDescent(); teacher.Learn(inputs, targets); var svm = teacher.Model; - // Compute the value for the last rate of change + // Compute the value for the last rate of change. var value = svm.Score(new double[] { Math.Sign(_roc.Window[0]) }); if (value.IsNaNOrZero()) return; diff --git a/project-templates/csharp/alternative-data-universe-braincompanyfilinglanguagemetricsuniverseall/Main.cs b/project-templates/csharp/alternative-data-universe-braincompanyfilinglanguagemetricsuniverseall/Main.cs index 556b94d293..ae2a500cbb 100644 --- a/project-templates/csharp/alternative-data-universe-braincompanyfilinglanguagemetricsuniverseall/Main.cs +++ b/project-templates/csharp/alternative-data-universe-braincompanyfilinglanguagemetricsuniverseall/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities with positive sentiment in their latest SEC filings. _universe = AddUniverse(data => { @@ -26,7 +27,7 @@ where d.ReportSentiment.Sentiment > 0m select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -42,7 +43,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-brainsentimentindicatoruniverse/Main.cs b/project-templates/csharp/alternative-data-universe-brainsentimentindicatoruniverse/Main.cs index 9978704bf0..6b7de9fecf 100644 --- a/project-templates/csharp/alternative-data-universe-brainsentimentindicatoruniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-brainsentimentindicatoruniverse/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities with positive 7-day media sentiment and active mention coverage. _universe = AddUniverse(data => { @@ -25,7 +26,7 @@ where d.TotalArticleMentions7Days > 0m && d.Sentiment7Days > 0m select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -41,7 +42,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-brainstockrankinguniverse/Main.cs b/project-templates/csharp/alternative-data-universe-brainstockrankinguniverse/Main.cs index 8958772342..6018a4c9a0 100644 --- a/project-templates/csharp/alternative-data-universe-brainstockrankinguniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-brainstockrankinguniverse/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities with positive Brain ML rankings across 2-, 3-, and 5-day horizons. _universe = AddUniverse(data => { @@ -25,7 +26,7 @@ where d.Rank2Days > 0m && d.Rank3Days > 0m && d.Rank5Days > 0m select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -41,7 +42,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-coingeckouniverse/Main.cs b/project-templates/csharp/alternative-data-universe-coingeckouniverse/Main.cs index a084861bc2..c1e2ca6918 100644 --- a/project-templates/csharp/alternative-data-universe-coingeckouniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-coingeckouniverse/Main.cs @@ -17,6 +17,7 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; SetAccountCurrency("USD"); // Trade the largest CoinGecko coins on Coinbase quoted in USD. @@ -26,7 +27,7 @@ public override void Initialize() .Select(x => x.Key.Symbol) .ToList(); - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of the top 10 CoinGecko coins by market cap that we can trade. _universe = AddUniverse("CoinGeckoUniverse", Resolution.Daily, data => { @@ -56,7 +57,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-eodhdupcomingdividends/Main.cs b/project-templates/csharp/alternative-data-universe-eodhdupcomingdividends/Main.cs index 078e84a504..9ff7be0fd8 100644 --- a/project-templates/csharp/alternative-data-universe-eodhdupcomingdividends/Main.cs +++ b/project-templates/csharp/alternative-data-universe-eodhdupcomingdividends/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities going ex-dividend in the next day with a meaningful payout. _universe = AddUniverse(data => { @@ -25,7 +26,7 @@ public override void Initialize() select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -41,7 +42,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-eodhdupcomingearnings/Main.cs b/project-templates/csharp/alternative-data-universe-eodhdupcomingearnings/Main.cs index 2737b1b01b..fe09406e11 100644 --- a/project-templates/csharp/alternative-data-universe-eodhdupcomingearnings/Main.cs +++ b/project-templates/csharp/alternative-data-universe-eodhdupcomingearnings/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities reporting earnings in the next 3 days with a positive estimate. _universe = AddUniverse(data => { @@ -25,7 +26,7 @@ public override void Initialize() select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -41,7 +42,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-eodhdupcomingipos/Main.cs b/project-templates/csharp/alternative-data-universe-eodhdupcomingipos/Main.cs index 502076b611..e0f911d7ae 100644 --- a/project-templates/csharp/alternative-data-universe-eodhdupcomingipos/Main.cs +++ b/project-templates/csharp/alternative-data-universe-eodhdupcomingipos/Main.cs @@ -17,8 +17,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of confirmed non-penny upcoming IPOs. _universe = AddUniverse(data => { @@ -32,7 +33,7 @@ where _dealTypesWanted.Contains(d.DealType) select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -48,7 +49,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-eodhdupcomingsplits/Main.cs b/project-templates/csharp/alternative-data-universe-eodhdupcomingsplits/Main.cs index 1a21e25f66..a888da802c 100644 --- a/project-templates/csharp/alternative-data-universe-eodhdupcomingsplits/Main.cs +++ b/project-templates/csharp/alternative-data-universe-eodhdupcomingsplits/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities with a forward stock split in the next 3 days. _universe = AddUniverse(data => { @@ -25,7 +26,7 @@ public override void Initialize() select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -41,7 +42,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-quivercnbcsuniverse/Main.cs b/project-templates/csharp/alternative-data-universe-quivercnbcsuniverse/Main.cs index e489b1fbf8..f1089d20d1 100644 --- a/project-templates/csharp/alternative-data-universe-quivercnbcsuniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-quivercnbcsuniverse/Main.cs @@ -15,9 +15,10 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; // Trade daily on CNBC opinion updates. - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities flagged by 3+ positive CNBC opinions. _universe = AddUniverse(data => { @@ -29,7 +30,7 @@ where g.Count(x => x.Direction == OrderDirection.Buy) >= 3 select g.Key; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -45,7 +46,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-quivergovernmentcontractuniverse/Main.cs b/project-templates/csharp/alternative-data-universe-quivergovernmentcontractuniverse/Main.cs index 01f574dba0..6e0757fd64 100644 --- a/project-templates/csharp/alternative-data-universe-quivergovernmentcontractuniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-quivergovernmentcontractuniverse/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities with frequent, sizable US government contracts. _universe = AddUniverse(data => { @@ -25,7 +26,7 @@ where g.Count() >= 3 && g.Sum(x => x.Amount) > 50000m select g.Key; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -41,7 +42,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-quiverinsidertradinguniverse/Main.cs b/project-templates/csharp/alternative-data-universe-quiverinsidertradinguniverse/Main.cs index 8bde4aafff..21a8305519 100644 --- a/project-templates/csharp/alternative-data-universe-quiverinsidertradinguniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-quiverinsidertradinguniverse/Main.cs @@ -15,8 +15,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of the 10 US Equities with the largest insider-trading dollar volume. _universe = AddUniverse(data => { @@ -40,7 +41,7 @@ public override void Initialize() .Select(kvp => kvp.Key); }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -56,7 +57,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-quiverlobbyinguniverse/Main.cs b/project-templates/csharp/alternative-data-universe-quiverlobbyinguniverse/Main.cs index 47c837458b..f4966320c1 100644 --- a/project-templates/csharp/alternative-data-universe-quiverlobbyinguniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-quiverlobbyinguniverse/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities with material corporate lobbying spend. _universe = AddUniverse("QuiverLobbyingUniverse", Resolution.Daily, data => { @@ -25,7 +26,7 @@ where g.Sum(x => x.Amount) >= 100000m select g.Key; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -41,7 +42,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-quiverquantcongressuniverse/Main.cs b/project-templates/csharp/alternative-data-universe-quiverquantcongressuniverse/Main.cs index 3792ef252b..ffbf7ef80d 100644 --- a/project-templates/csharp/alternative-data-universe-quiverquantcongressuniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-quiverquantcongressuniverse/Main.cs @@ -15,8 +15,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of US Equities recently bought by US Congress members in trades over $200K. _universe = AddUniverse(data => { @@ -26,7 +27,7 @@ public override void Initialize() select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -42,7 +43,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-smartinsiderintentionuniverse/Main.cs b/project-templates/csharp/alternative-data-universe-smartinsiderintentionuniverse/Main.cs index c5959cbb69..afb6235fc7 100644 --- a/project-templates/csharp/alternative-data-universe-smartinsiderintentionuniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-smartinsiderintentionuniverse/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of large-cap US Equities announcing meaningful buyback intentions. _universe = AddUniverse(data => { @@ -25,7 +26,7 @@ where d.Percentage > 0.005m && d.USDMarketCap > 100000000m select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -41,7 +42,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe-smartinsidertransactionuniverse/Main.cs b/project-templates/csharp/alternative-data-universe-smartinsidertransactionuniverse/Main.cs index a29e1337f7..ca6a3ce717 100644 --- a/project-templates/csharp/alternative-data-universe-smartinsidertransactionuniverse/Main.cs +++ b/project-templates/csharp/alternative-data-universe-smartinsidertransactionuniverse/Main.cs @@ -14,8 +14,9 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Universe of large-cap US Equities executing meaningful share buybacks. _universe = AddUniverse(data => { @@ -25,7 +26,7 @@ where d.BuybackPercentage > 0.005m && d.USDMarketCap > 100000000m select d.Symbol; }); - // Rebalance shortly after the open so today's universe is locked in. + // Rebalance before market open to trade today's universe. Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(9, 0, 0), Rebalance); } @@ -41,7 +42,7 @@ private void Rebalance() .Select(symbol => new PortfolioTarget(symbol, weight)) .ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } } diff --git a/project-templates/csharp/alternative-data-universe/Main.cs b/project-templates/csharp/alternative-data-universe/Main.cs index 75ffc1344e..ed5b04a045 100644 --- a/project-templates/csharp/alternative-data-universe/Main.cs +++ b/project-templates/csharp/alternative-data-universe/Main.cs @@ -75,10 +75,10 @@ public override void Initialize() // Seed the last price as price since we need to use the underlying price for option contract filtering when it join the universe. Settings.SeedInitialPrices = true; // Trade on daily basis based on daily upcoming earnings signals. - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; // Option trading requires raw price for strike price comparison. UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw; - // Universe consists of equities with upcoming earnings events. + // Universe consists of Equities with upcoming earnings events. AddUniverse((earnings) => { foreach(var i in Enumerable.Range(1,5).Reverse()) { @@ -99,7 +99,7 @@ public override void Initialize() public override void OnSecuritiesChanged(SecurityChanges changes) { - // Actions only based on the equity universe changes. + // Actions only based on the Equity universe changes. foreach (var security in changes.RemovedSecurities.Where(x=> x.Type == SecurityType.Equity)) { // Liquidate any assigned position. @@ -112,14 +112,14 @@ public override void OnSecuritiesChanged(SecurityChanges changes) } } - // Actions only based on the equity universe changes. + // Actions only based on the Equity universe changes. foreach (var security in changes.AddedSecurities.Where(x=> x.Type == SecurityType.Equity)) { // Select the option contracts to construct a straddle to trade the volatility. var (call, put) = SelectOptionContracts(security); if (call == null || put == null) { - continue; + continue; } _optionsBySymbol[security] = (call, put); // Request the option contract data for trading. @@ -132,7 +132,7 @@ public override void OnSecuritiesChanged(SecurityChanges changes) Leg.Create(put, 1) ], 1 - ); + ); } } diff --git a/project-templates/csharp/alternative-data/Main.cs b/project-templates/csharp/alternative-data/Main.cs index 6ae1069ddc..02276c2f72 100644 --- a/project-templates/csharp/alternative-data/Main.cs +++ b/project-templates/csharp/alternative-data/Main.cs @@ -1,68 +1,15 @@ -#region imports - using System; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Globalization; - using System.Drawing; - using QuantConnect; - using QuantConnect.Algorithm.Framework; - using QuantConnect.Algorithm.Framework.Selection; - using QuantConnect.Algorithm.Framework.Alphas; - using QuantConnect.Algorithm.Framework.Portfolio; - using QuantConnect.Algorithm.Framework.Portfolio.SignalExports; - using QuantConnect.Algorithm.Framework.Execution; - using QuantConnect.Algorithm.Framework.Risk; - using QuantConnect.Algorithm.Selection; - using QuantConnect.Api; - using QuantConnect.Parameters; - using QuantConnect.Benchmarks; - using QuantConnect.Brokerages; - using QuantConnect.Commands; - using QuantConnect.Configuration; - using QuantConnect.Util; - using QuantConnect.Interfaces; - using QuantConnect.Algorithm; - using QuantConnect.Indicators; - using QuantConnect.Data; - using QuantConnect.Data.Auxiliary; - using QuantConnect.Data.Consolidators; - using QuantConnect.Data.Custom; - using QuantConnect.Data.Custom.IconicTypes; - using QuantConnect.DataSource; - using QuantConnect.Data.Fundamental; - using QuantConnect.Data.Market; - using QuantConnect.Data.Shortable; - using QuantConnect.Data.UniverseSelection; - using QuantConnect.Notifications; - using QuantConnect.Orders; - using QuantConnect.Orders.Fees; - using QuantConnect.Orders.Fills; - using QuantConnect.Orders.OptionExercise; - using QuantConnect.Orders.Slippage; - using QuantConnect.Orders.TimeInForces; - using QuantConnect.Python; - using QuantConnect.Scheduling; - using QuantConnect.Securities; - using QuantConnect.Securities.Equity; - using QuantConnect.Securities.Future; - using QuantConnect.Securities.Option; - using QuantConnect.Securities.Positions; - using QuantConnect.Securities.Forex; - using QuantConnect.Securities.Crypto; - using QuantConnect.Securities.CryptoFuture; - using QuantConnect.Securities.IndexOption; - using QuantConnect.Securities.Interfaces; - using QuantConnect.Securities.Volatility; - using QuantConnect.Storage; - using QuantConnect.Statistics; - using QCAlgorithmFramework = QuantConnect.Algorithm.QCAlgorithm; - using QCAlgorithmFrameworkBridge = QuantConnect.Algorithm.QCAlgorithm; - using Calendar = QuantConnect.Data.Consolidators.Calendar; -#endregion +using System.Linq; +using QuantConnect; +using QuantConnect.Algorithm; +using QuantConnect.Data; +using QuantConnect.DataSource; +using QuantConnect.Securities.Equity; + +public class BrainCompanyFilingNLPDataAlgorithm : QCAlgorithm +{ + private Equity _equity; + private Symbol _filingData; -public class BrainMLRankingDataAlgorithm : QCAlgorithm -{ public override void Initialize() { SetStartDate(2024, 9, 1); @@ -70,32 +17,23 @@ public override void Initialize() SetCash(100000); // Seed the price of each asset with its last known price to avoid trading errors. Settings.SeedInitialPrices = true; - // We cherry picked 5 largest stocks, high trading volume provides better information and credibility for ML ranking - var tickers = new string[] {"AAPL", "TSLA", "MSFT", "F", "KO"}; - foreach (var ticker in tickers) - { - // Requesting data to get 2 days estimated relative ranking - var equity = AddEquity(ticker, Resolution.Daily); - AddData(equity); - } + // Request company filing data to obtain sentiment scores from company reports. + // Combine sentiment with fundamental context, past performance, and forward-looking provisions. + _equity = AddEquity("AAPL", Resolution.Daily); + _filingData = AddData(_equity.Symbol).Symbol; + // Historical data + var history = History(_filingData, 365, Resolution.Daily); + Debug($"We got {history.Count()} items from our history request for {_filingData}"); } public override void OnData(Slice slice) { - // Collect rankings for all symbols for ranking them - var points = slice.Get(); - if (points == null) + // Trade based on the updated report sentiment. + if (slice.ContainsKey(_filingData)) { - return; + var sentiment = slice[_filingData].ReportSentiment.Sentiment; + // Buy when sentiment is positive to express the expected positive return projection. + SetHoldings(_equity.Symbol, sentiment > 0 ? 1 : 0); } - var sumOfRanks = points.Values.Select(x => Math.Abs(x.Rank)).Sum() * 0.9m; - if (sumOfRanks == 0) return; - - // Rank each symbol's Brain ML ranking relative to the other symbols for positional sizing - points.Values.DoForEach(x => Plot("Rank", x.Symbol.Underlying.Value, x.Rank)); - - // Place orders, the better the rank, the higher the estimated return and hence weight - var targets = points.Values.Select(x => new PortfolioTarget(x.Symbol.Underlying, x.Rank / sumOfRanks)).ToList(); - SetHoldings(targets); } } diff --git a/project-templates/csharp/cfd/Main.cs b/project-templates/csharp/cfd/Main.cs index 5adb0a708c..36dacebad3 100644 --- a/project-templates/csharp/cfd/Main.cs +++ b/project-templates/csharp/cfd/Main.cs @@ -70,8 +70,8 @@ public override void Initialize() SetEndDate(2024, 12, 31); // Seed the price of each asset with its last known price to avoid trading errors. Settings.SeedInitialPrices = true; - // Let's select CFD contracts that trade in different market - // hours so the algorithm is always invested. + // Let's select CFD contracts that trade in different market. + // Hours so the algorithm is always invested. foreach (var ticker in new[] { "DE30EUR", "SG30SGD", "US30USD" }) { // Add the CFD. diff --git a/project-templates/csharp/chained-universe/Main.cs b/project-templates/csharp/chained-universe/Main.cs index cc9a6acc3e..55ec180bf4 100644 --- a/project-templates/csharp/chained-universe/Main.cs +++ b/project-templates/csharp/chained-universe/Main.cs @@ -97,7 +97,7 @@ private IEnumerable FundamentalSelection(IEnumerable fundam private void PlaceOrders() { - // We will keep the ETF weights by scale it up to sum 1 + // We will keep the ETF weights by scale it up to sum 1. var sumOfWeight = _universe.Selected.Sum(x => _weightBySymbol[x]); Plot("Universe", "Sum Of Weight (%)", sumOfWeight * 100m); var targets = _universe.Selected.Select(x => new PortfolioTarget(x, _weightBySymbol[x] / sumOfWeight)).ToList(); diff --git a/project-templates/csharp/crypto-futures/Main.cs b/project-templates/csharp/crypto-futures/Main.cs index 407d0fd387..1137dd8086 100644 --- a/project-templates/csharp/crypto-futures/Main.cs +++ b/project-templates/csharp/crypto-futures/Main.cs @@ -67,7 +67,7 @@ public override void Initialize() { SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); - // Set the account current to USDT as we will trade USDT quoted coins + // Set the account current to USDT as we will trade USDT quoted coins. SetAccountCurrency("USDT", 100000); // Set the brokerage and account type to match your brokerage environment for accurate fee and margin behavior. SetBrokerageModel(BrokerageName.Binance, AccountType.Margin); @@ -90,6 +90,6 @@ public override void OnData(Slice slice) private void Rebalance() { var targets = Securities.Keys.Select(x => new PortfolioTarget(x, .3m)).ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } diff --git a/project-templates/csharp/crypto-static/Main.cs b/project-templates/csharp/crypto-static/Main.cs index 03c10eed99..16f2fcbd6c 100644 --- a/project-templates/csharp/crypto-static/Main.cs +++ b/project-templates/csharp/crypto-static/Main.cs @@ -68,7 +68,7 @@ public override void Initialize() { SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); - // Set the account current to USDT as we will trade USDT quoted coins + // Set the account current to USDT as we will trade USDT quoted coins. SetAccountCurrency("USDT", 100000); // Set the brokerage and account type to match your brokerage environment for accurate fee and margin behavior. SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Cash); @@ -83,6 +83,6 @@ public override void Initialize() private void Rebalance() { var targets = Securities.Keys.Select(x => new PortfolioTarget(x, .3m)).ToList(); - SetHoldings(targets, liquidateExistingHoldings: true); + SetHoldings(targets, true); } } diff --git a/project-templates/csharp/crypto-universe/Main.cs b/project-templates/csharp/crypto-universe/Main.cs index 2ce2baf197..4edb2c52dc 100644 --- a/project-templates/csharp/crypto-universe/Main.cs +++ b/project-templates/csharp/crypto-universe/Main.cs @@ -71,7 +71,7 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); Settings.SeedInitialPrices = true; - // Set the account currency to USDT + // Set the account currency to USDT. SetAccountCurrency("USDT"); SetBrokerageModel(BrokerageName.Coinbase, AccountType.Cash); diff --git a/project-templates/csharp/custom-consolidators/Main.cs b/project-templates/csharp/custom-consolidators/Main.cs index 802ed2464a..059d6fdd13 100644 --- a/project-templates/csharp/custom-consolidators/Main.cs +++ b/project-templates/csharp/custom-consolidators/Main.cs @@ -74,8 +74,8 @@ public override void Initialize() _pair.Ema = new ExponentialMovingAverage(10); // Create a QuoteBar consolidator with a custom consolidation period. var consolidator = new QuoteBarConsolidator(DailyForexConsolidationPeriod); - // You can also create a consolidator with a period of one day and start time of 17 - // var consolidator = new QuoteBarConsolidator(TimeSpan.FromDays(1), TimeSpan.FromHours(17)); + // You can also create a consolidator with a period of one day and start time of 17. + // Var consolidator = new QuoteBarConsolidator(TimeSpan.FromDays(1), TimeSpan.FromHours(17));. // Attach a consolidation handler that will receive the consolidated bars. consolidator.DataConsolidated += ConsolidationHandler; // Subscribe the consolidator for automatic updates with the prices of the pair. diff --git a/project-templates/csharp/custom-data-ticker-mapping/Main.cs b/project-templates/csharp/custom-data-ticker-mapping/Main.cs index 2ce3e78ab2..fd3364ba50 100644 --- a/project-templates/csharp/custom-data-ticker-mapping/Main.cs +++ b/project-templates/csharp/custom-data-ticker-mapping/Main.cs @@ -78,7 +78,7 @@ public override void Initialize() SetStartDate(2020, 1, 1); SetEndDate(2024, 12, 31); - // Save the data to the object store + // Save the data to the object store. if (!ObjectStore.ContainsKey("selected_trades.csv")) ObjectStore.Save("selected_trades.csv", Content); @@ -122,14 +122,14 @@ public override BaseData Reader(SubscriptionDataConfig config, string line, Date { var ticker = data[1]; var time = DateTime.Parse(data[0], CultureInfo.InvariantCulture); - // Create the SecurityIdentifier with the point-in-time ticker and the current date - // In this example, we trade META in 2020 when its ticker was FB - // Then, we will see it when it is META + // Create the SecurityIdentifier with the point-in-time ticker and the current date. + // In this example, we trade META in 2020 when its ticker was FB. + // Then, we will see it when it is META. var securityID = SecurityIdentifier.GenerateEquity(ticker, Market.USA, mappingResolveDate: time); - + if (securityID.Date.Year < 1998) { - // Ticker not found in QuantConnect database on this date + // Ticker not found in QuantConnect database on this date. return null; } diff --git a/project-templates/csharp/custom-data/Main.cs b/project-templates/csharp/custom-data/Main.cs index 1edaef3d60..bf65aad6f9 100644 --- a/project-templates/csharp/custom-data/Main.cs +++ b/project-templates/csharp/custom-data/Main.cs @@ -87,7 +87,7 @@ public class Bitstamp : BaseData { public int Timestamp = 0; public decimal Open = 0, High = 0, Low = 0, Close = 0, Bid = 0, Ask = 0, WeightedPrice = 0, VolumeBTC = 0, VolumeUSD = 0; - + public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode) { if (isLiveMode) @@ -108,8 +108,8 @@ public override BaseData Reader(SubscriptionDataConfig config, string line, Date // In live trading, parse the JSON file. if (isLiveMode) { - //Example Line Format: - //{"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"} + // Example Line Format: + // {"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}. coin = JsonConvert.DeserializeObject(line); coin.EndTime = DateTime.UtcNow.ConvertFromUtc(config.ExchangeTimeZone); coin.Time = coin.EndTime.AddDays(-1); @@ -118,9 +118,9 @@ public override BaseData Reader(SubscriptionDataConfig config, string line, Date } // In backtests, parse the CSV file. - //Example Line Format: - //Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price - //2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356 + // Example Line Format: + // Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price. + // 2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356. if (!char.IsDigit(line[0])) { return null; diff --git a/project-templates/csharp/custom-indicator/Main.cs b/project-templates/csharp/custom-indicator/Main.cs index 64374489a6..1c2484fd4c 100644 --- a/project-templates/csharp/custom-indicator/Main.cs +++ b/project-templates/csharp/custom-indicator/Main.cs @@ -113,33 +113,33 @@ public class CustomMoneyFlowIndex : TradeBarIndicator, IIndicatorWarmUpPeriodPro private RollingWindow _positiveMoneyFlow; public override bool IsReady => _positiveMoneyFlow.IsReady; public int WarmUpPeriod => _positiveMoneyFlow.Size; - + public CustomMoneyFlowIndex(int period) : base("CustomMFI") { _negativeMoneyFlow = new(period); _positiveMoneyFlow = new(period); _previousTypicalPrice = 0m; } - + protected override decimal ComputeNextValue(TradeBar input) { // Estimate the money flow by averaging the price multiplied by volume. var typicalPrice = (input.High + input.Low + input.Close) / 3; var moneyFlow = typicalPrice * input.Volume; - + // We need to avoid double rounding errors. _negativeMoneyFlow.Add(typicalPrice < _previousTypicalPrice ? moneyFlow: 0); _positiveMoneyFlow.Add(typicalPrice > _previousTypicalPrice ? moneyFlow: 0); _previousTypicalPrice = moneyFlow; - + // Add the period money flow to calculate the aggregated money flow. var positiveMoneyFlowSum = _positiveMoneyFlow.Sum(); var totalMoneyFlow = positiveMoneyFlowSum + _negativeMoneyFlow.Sum(); - + // Set the value to be the positive money flow ratio. return totalMoneyFlow == 0 ? 100m : 100m * positiveMoneyFlowSum / totalMoneyFlow; } - + public override void Reset() { _previousTypicalPrice = 0m; diff --git a/project-templates/csharp/custom-models/Main.cs b/project-templates/csharp/custom-models/Main.cs index b8cbdf7e33..be9640bc14 100644 --- a/project-templates/csharp/custom-models/Main.cs +++ b/project-templates/csharp/custom-models/Main.cs @@ -67,18 +67,19 @@ public override void Initialize() SetStartDate(2024, 9, 12); SetEndDate(2024, 10, 1); SetCash(1000000); + Settings.SeedInitialPrices = true; - // The brokerage model sets the reality models that reflect the brokerage behavior + // The brokerage model sets the reality models that reflect the brokerage behavior. SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); - - // Override some of the models - AddSecurityInitializer(security => + + // Override some of the models. + AddSecurityInitializer(security => { security.SetFeeModel(new CustomFeeModel(this)); security.SetFillModel(new CustomFillModel(this)); security.SetSlippageModel(new CustomSlippageModel(this)); - - // We can set different models for different asset classes + + // We can set different models for different asset classes. if (security.Type.IsOption()) { security.SetBuyingPowerModel(BuyingPowerModel.Null); @@ -89,7 +90,7 @@ public override void Initialize() } }); - // Request SPY data to trade after we set the model and security initializer + // Request SPY data to trade after we set the model and security initializer. AddEquity("SPY"); } @@ -114,7 +115,7 @@ public CustomFillModel(QCAlgorithm algorithm) public override OrderEvent MarketFill(Security asset, MarketOrder order) { - // this model randomly fills market orders + // This model randomly fills market orders. decimal absoluteRemaining; if (!_absoluteRemainingByOrderId.TryGetValue(order.Id, out absoluteRemaining)) @@ -156,7 +157,7 @@ public CustomFeeModel(QCAlgorithm algorithm) public override OrderFee GetOrderFee(OrderFeeParameters parameters) { - // custom fee math + // Custom fee math. var fee = Math.Max( 1m, parameters.Security.Price*parameters.Order.AbsoluteQuantity*0.00001m); @@ -177,7 +178,7 @@ public CustomSlippageModel(QCAlgorithm algorithm) public decimal GetSlippageApproximation(Security asset, Order order) { - // custom slippage math + // Custom slippage math. var slippage = asset.Price*0.0001m*(decimal) Math.Log10(2*(double) order.AbsoluteQuantity); _algorithm.Log($"CustomSlippageModel: {slippage}"); @@ -197,7 +198,7 @@ public CustomBuyingPowerModel(QCAlgorithm algorithm) public override HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerForOrder( HasSufficientBuyingPowerForOrderParameters parameters) { - // custom behavior: this model will assume that there is always enough buying power + // Custom behavior: this model will assume that there is always enough buying power. var hasSufficientBuyingPowerForOrderResult = new HasSufficientBuyingPowerForOrderResult(true); _algorithm.Log($"CustomBuyingPowerModel: {hasSufficientBuyingPowerForOrderResult.IsSufficient}"); @@ -206,7 +207,7 @@ public override HasSufficientBuyingPowerForOrderResult HasSufficientBuyingPowerF } /// - /// The simple fill model shows how to implement a simpler version of + /// The simple fill model shows how to implement a simpler version of /// the most popular order fills: Market, Stop Market and Limit /// public class SimpleCustomFillModel : FillModel @@ -229,8 +230,8 @@ private static TradeBar GetTradeBar(Security asset, OrderDirection orderDirectio { var tradeBar = asset.Cache.GetData(); if (tradeBar != null) return tradeBar; - - // Tick-resolution data doesn't have TradeBar, use the asset price + + // Tick-resolution data doesn't have TradeBar, use the asset price. var price = asset.Price; return new TradeBar(asset.LocalTime, asset.Symbol, price, price, price, price, 0); } @@ -254,7 +255,7 @@ public override OrderEvent StopMarketFill(Security asset, StopMarketOrder order) var stopPrice = order.StopPrice; var tradeBar = GetTradeBar(asset, order.Direction); - + return order.Direction switch { OrderDirection.Buy => tradeBar.Low < stopPrice diff --git a/project-templates/csharp/equities-static-universe/Main.cs b/project-templates/csharp/equities-static-universe/Main.cs index 3588d37bff..cb758f5185 100644 --- a/project-templates/csharp/equities-static-universe/Main.cs +++ b/project-templates/csharp/equities-static-universe/Main.cs @@ -68,6 +68,7 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; Settings.AutomaticIndicatorWarmUp = true; var tickers = new string[] {"SPY", "QQQ", "IWM"}; foreach (var ticker in tickers) diff --git a/project-templates/csharp/equities-universe/Main.cs b/project-templates/csharp/equities-universe/Main.cs index 83265529fa..d04a18134f 100644 --- a/project-templates/csharp/equities-universe/Main.cs +++ b/project-templates/csharp/equities-universe/Main.cs @@ -64,15 +64,15 @@ public class EmaCrossUniverseSelectionAlgorithm : QCAlgorithm { - // tolerance to prevent bouncing + // Tolerance to prevent bouncing. const decimal _tolerance = 0.01m; private const int _count = 10; - // use Buffer+Count to leave a little in cash + // Use Buffer+Count to leave a little in cash. private const decimal _targetPercent = 0.09m; private Universe _universe; - // holds our coarse fundamental indicators by symbol + // Holds our coarse fundamental indicators by symbol. private readonly ConcurrentDictionary _averages = []; /// @@ -85,20 +85,20 @@ public override void Initialize() SetCash(100000); Settings.SeedInitialPrices = true; UniverseSettings.Leverage = 2.0m; - UniverseSettings.Resolution = Resolution.Daily; + UniverseSettings.Resolution = Resolution.Minute; _universe = AddUniverse(coarse => { return (from cf in coarse - // grab th SelectionData instance for this symbol + // Grab th SelectionData instance for this symbol. let avg = _averages.GetOrAdd(cf.Symbol, sym => new SelectionData()) - // Update returns true when the indicators are ready, so don't accept until they are + // Update returns true when the indicators are ready, so don't accept until they are. where avg.Update(cf.EndTime, cf.AdjustedPrice) - // and only pick symbols who have their market cap above 1Bi and 100 day ema over their 300 day ema + // And only pick symbols who have their market cap above 1Bi and 100 day ema over their 300 day ema. where cf.MarketCap > 10000000000 && avg.Fast > avg.Slow * (1 + _tolerance) - // prefer symbols with a larger delta by percentage between the two averages + // Prefer symbols with a larger delta by percentage between the two averages. orderby avg.ScaledDelta descending - // we only need to return the symbol and return 'Count' symbols + // We only need to return the symbol and return 'Count' symbols. select cf.Symbol).Take(_count); }); @@ -111,13 +111,13 @@ orderby avg.ScaledDelta descending /// Slice object keyed by symbol containing the stock data public override void OnData(Slice slice) { - // we'll simply go long each security in the universe + // We'll simply go long each security in the universe. var targets = _universe.Selected.Where(x => Securities[x].HasData) .Select(x => new PortfolioTarget(x, _targetPercent)).ToList(); SetHoldings(targets, true); } - // class used to improve readability of the coarse selection function + // Class used to improve readability of the coarse selection function. private class SelectionData { public readonly ExponentialMovingAverage Fast; @@ -129,10 +129,10 @@ public SelectionData() Slow = new ExponentialMovingAverage(300); } - // computes an object score of how much large the fast is than the slow + // Computes an object score of how much large the fast is than the slow. public decimal ScaledDelta => (Fast - Slow)/((Fast + Slow)/2m); - // updates the EMA50 and EMA100 indicators, returning true when they're both ready + // Updates the EMA50 and EMA100 indicators, returning true when they're both ready. public bool Update(DateTime time, decimal value) { return Fast.Update(time, value) & Slow.Update(time, value); diff --git a/project-templates/csharp/equity-options-static/Main.cs b/project-templates/csharp/equity-options-static/Main.cs index 4beb1a99b1..6685d324f1 100644 --- a/project-templates/csharp/equity-options-static/Main.cs +++ b/project-templates/csharp/equity-options-static/Main.cs @@ -65,7 +65,7 @@ public class EquityOptionExampleAlgorithm : QCAlgorithm { private Equity _spy; - + public override void Initialize() { SetStartDate(2024, 9, 1); @@ -78,20 +78,20 @@ public override void Initialize() Schedule.On(DateRules.Every(DayOfWeek.Monday), TimeRules.AfterMarketOpen(_spy, 1), BuyCoveredCall); } - + /// /// Buy a Covered Call: Buy the underlying and sell the ATM call. /// private void BuyCoveredCall() { var nextFriday = Time.AddDays(4).Date; - + var atmCall = OptionChain(_spy) .Where(x => x.Right == OptionRight.Call && x.Expiry.Date == nextFriday) .OrderBy(x => Math.Abs(_spy.Price - x.Strike)) .FirstOrDefault(); - // If we cannot find a contract expiring on Friday, it is likely a holiday + // If we cannot find a contract expiring on Friday, it is likely a holiday. // For simplicity, we will not trade and close the underlying position, if any. if (atmCall == null) { @@ -101,14 +101,14 @@ private void BuyCoveredCall() var contract = AddOptionContract(atmCall); var contractMultiplier = contract.ContractMultiplier; - - // We will invest 100% of the portfolio value observing the contract multiplier - // For example, if 100% of the portfolio value is 345 shares of SPY, we will invest 300 + + // We will invest 100% of the portfolio value observing the contract multiplier. + // For example, if 100% of the portfolio value is 345 shares of SPY, we will invest 300. // Then, we sell 3 contracts of ATM call. If we are exercised, the position is closed. var equityOrderQuantity = Math.Floor(CalculateOrderQuantity(_spy, 1d) / contractMultiplier) * contractMultiplier; - // If we are invested in the underlying, the hedge takes into account the final quantity + // If we are invested in the underlying, the hedge takes into account the final quantity. var atmCallOrderQuantity = -(_spy.Holdings.Quantity + equityOrderQuantity) / contractMultiplier; - + if (equityOrderQuantity != 0) { MarketOrder(_spy, equityOrderQuantity); diff --git a/project-templates/csharp/equity-options-universe/Main.cs b/project-templates/csharp/equity-options-universe/Main.cs index e38415ac31..56c45ca6ab 100644 --- a/project-templates/csharp/equity-options-universe/Main.cs +++ b/project-templates/csharp/equity-options-universe/Main.cs @@ -75,7 +75,7 @@ public override void Initialize() // It provides better accuracy in filtering, and subscribe only to the needed contracts to save computation resources. _option.SetFilter(u => u.Straddle(30)); } - + public override void OnData(Slice slice) { // Only wants the option chain of the selected symbol. @@ -84,7 +84,7 @@ public override void OnData(Slice slice) // There should only be 1 expiry and 1 strike from the 2 contracts returned, getting from either contract is fine. var expiry = chain.First().Expiry; var strike = chain.First().Strike; - + // Forms a long straddle option strategy using abstraction method ensure accuracy. var longStraddle = OptionStrategies.Straddle(_option, strike, expiry); Buy(longStraddle, 1); diff --git a/project-templates/csharp/financial-advisors/Main.cs b/project-templates/csharp/financial-advisors/Main.cs index 56f0d5502d..0ae3bb386e 100644 --- a/project-templates/csharp/financial-advisors/Main.cs +++ b/project-templates/csharp/financial-advisors/Main.cs @@ -69,10 +69,10 @@ public override void Initialize() SetStartDate(2024, 9, 12); SetEndDate(2024, 10, 1); - // Financial Advisor is a live trading feature of the Interactive Brokers integration + // Financial Advisor is a live trading feature of the Interactive Brokers integration. SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); - // Set the default order properties so all orders apply these settings + // Set the default order properties so all orders apply these settings. DefaultOrderProperties = new InteractiveBrokersOrderProperties() { FaGroup = "TestGroupEQ", @@ -99,7 +99,7 @@ private void NotifyAll(string subject, string message) message = $"{Time:yyyyMMdd}: {subject} > {message}"; Log(message); // See https://www.quantconnect.com/docs/v2/writing-algorithms/live-trading/notifications - // for all notification methods + // For all notification methods. Notify.Sms("+16191234567", message); } diff --git a/project-templates/csharp/forex/Main.cs b/project-templates/csharp/forex/Main.cs index 8816dc1626..026daf2672 100644 --- a/project-templates/csharp/forex/Main.cs +++ b/project-templates/csharp/forex/Main.cs @@ -81,20 +81,20 @@ public override void Initialize() } } } - + public override void OnData(Slice slice) { // Ensure we have quote data in the current slice. foreach(var (symbol, quoteBar) in slice.QuoteBars) { - // Bid-ask spread = Ask price - Bid price + // Bid-ask spread = Ask price - Bid price. var bidAskSpread = quoteBar.Ask.Close - quoteBar.Bid.Close; // Update the spread minimum indicator to calculate the lowest bid-ask spread over the last 12 hours. dynamic forex = Securities[symbol]; forex.SpreadLow.Update(quoteBar.EndTime, bidAskSpread); - - // Trade if the current spread is the lowest bid-ask spread, - // since it is the most efficient, liquid price with lowest slippage. + + // Trade if the current spread is the lowest bid-ask spread,. + // Since it is the most efficient, liquid price with lowest slippage. if (!forex.Invested && bidAskSpread == forex.SpreadLow.Current.Value) { MarketOrder(forex, 1000); diff --git a/project-templates/csharp/future-options/Main.cs b/project-templates/csharp/future-options/Main.cs index cfcc338d99..4540d68a23 100644 --- a/project-templates/csharp/future-options/Main.cs +++ b/project-templates/csharp/future-options/Main.cs @@ -82,7 +82,7 @@ public override void Initialize() // It simplifies from further filtering and reduce computation on redundant subscription. AddFutureOption(_underlying, (u) => u.CallSpread(5, 5, -5)); } - + public override void OnData(Slice slice) { if (Portfolio.Invested) @@ -90,17 +90,17 @@ public override void OnData(Slice slice) // Create canonical symbol for the mapped future contract, since we need that to access the option chain. var symbol = QuantConnect.Symbol.CreateCanonicalOption(_underlying.Mapped); - + // Get option chain data for the mapped future only. // It requires 2 contracts with different strikes to form a call spread, so we make sure at least 2 contracts are present. if (!slice.OptionChains.TryGetValue(symbol, out var chain) || chain.Count() < 2) return; - + // Separate the contracts by strike, as we need to access their strike. var expiry = chain.Min(x => x.Expiry); var itmStrike = chain.Min(x => x.Strike); var otmStrike = chain.Max(x => x.Strike); - + // Use abstraction method to order a bull call spread to avoid manual error. var optionStrategy = OptionStrategies.BullCallSpread(symbol, itmStrike, otmStrike, expiry); Buy(optionStrategy, 1); diff --git a/project-templates/csharp/futures/Main.cs b/project-templates/csharp/futures/Main.cs index 4740bc6215..d432e52eaf 100644 --- a/project-templates/csharp/futures/Main.cs +++ b/project-templates/csharp/futures/Main.cs @@ -97,7 +97,7 @@ public override void OnSymbolChangedEvents(SymbolChangedEvents symbolChangedEven var newSymbol = Symbol(changedEvent.NewSymbol); var quantity = Portfolio[oldSymbol].Quantity; - // Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract + // Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract. var tag = $"Rollover - Symbol changed at {Time}: {oldSymbol.Value} -> {newSymbol.Value}"; Liquidate(symbol: oldSymbol, tag: tag); if (quantity != 0) MarketOrder(newSymbol, quantity, tag: tag); diff --git a/project-templates/csharp/history-and-etf-universe/Main.cs b/project-templates/csharp/history-and-etf-universe/Main.cs index e92ce1742d..e2650620c4 100644 --- a/project-templates/csharp/history-and-etf-universe/Main.cs +++ b/project-templates/csharp/history-and-etf-universe/Main.cs @@ -79,7 +79,7 @@ public override void Initialize() private IEnumerable ETFConstituentsFilter(IEnumerable constituents) { var atrBySymbol = constituents.Select( - c => + c => { var atr = new AverageTrueRange(14); WarmUpIndicator(c.Symbol, atr, Resolution.Daily); @@ -89,8 +89,8 @@ private IEnumerable ETFConstituentsFilter(IEnumerable x.Symbol, x => x.ATR); - // Select all QQQ constituents by high ATR value - _weightBySymbol.Clear(); + // Select all QQQ constituents by high ATR value. + _weightBySymbol.Clear(); constituents .Where(c=> atrBySymbol.ContainsKey(c.Symbol)) .DoForEach(c => _weightBySymbol.Add(c.Symbol, c.Weight ?? 0)); @@ -100,7 +100,7 @@ private IEnumerable ETFConstituentsFilter(IEnumerable _weightBySymbol[x]); Plot("Universe", "Sum Of Weight (%)", sumOfWeight * 100m); var targets = _universe.Selected.Select(x => new PortfolioTarget(x, _weightBySymbol[x] / sumOfWeight)).ToList(); diff --git a/project-templates/csharp/index-options-static/Main.cs b/project-templates/csharp/index-options-static/Main.cs index 6661a1d99e..6b0265d9ee 100644 --- a/project-templates/csharp/index-options-static/Main.cs +++ b/project-templates/csharp/index-options-static/Main.cs @@ -75,10 +75,10 @@ public override void Initialize() Settings.AutomaticIndicatorWarmUp = true; UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero; - // Warm-up the option contracts as soon as it is added to the algorithm + // Warm-up the option contracts as soon as it is added to the algorithm. Settings.SeedInitialPrices = true; - // The EMA/price cross will determine we trade ATM contracts + // The EMA/price cross will determine we trade ATM contracts. var index = AddIndex("SPX"); EMA(index.Symbol, 60).Updated += TradeAtTheMoneyContract; @@ -87,7 +87,7 @@ public override void Initialize() public void TradeAtTheMoneyContract(object sender, IndicatorDataPoint current) { - // Pace trades every 10 minutes + // Pace trades every 10 minutes. var lastTrateTime = _lastTicket?.Time ?? DateTime.MinValue; if ((UtcTime-lastTrateTime).TotalMinutes < 10) return; @@ -95,7 +95,7 @@ public void TradeAtTheMoneyContract(object sender, IndicatorDataPoint current) if (!ema.IsReady) return; var spot = Securities[current.Symbol].Price; - + if (spot > current && spot > ema[-1]) { var atmCall = GetAtTheMoneyContract(OptionRight.Call, spot); @@ -129,7 +129,7 @@ private Option GetAtTheMoneyContract(OptionRight right, decimal spot) { return null; } - + return AddOptionContract(atm); } } diff --git a/project-templates/csharp/index-options-universe/Main.cs b/project-templates/csharp/index-options-universe/Main.cs index 0e86f46342..03b48223cd 100644 --- a/project-templates/csharp/index-options-universe/Main.cs +++ b/project-templates/csharp/index-options-universe/Main.cs @@ -70,12 +70,13 @@ public override void Initialize() SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(100000); + Settings.SeedInitialPrices = true; // Subscribe to the option chain. _option = AddIndexOption("SPX", "SPXW"); // Filter the option universe to only select 0DTE options. _option.SetFilter(u => u.Expiration(0, 0).Strikes(-1, 1)); // Filter the option universe by Delta. The last SetFilter call prevails. - // _option.SetFilter(optionFilterUniverse => optionFilterUniverse.Delta(0.25m, 0.75m)); + // _option.SetFilter(optionFilterUniverse => optionFilterUniverse.Delta(0.25m, 0.75m));. } public override void OnData(Slice slice) diff --git a/project-templates/csharp/intraday-greeks-based-options-selection/Main.cs b/project-templates/csharp/intraday-greeks-based-options-selection/Main.cs index aacc08464b..d92e122d21 100644 --- a/project-templates/csharp/intraday-greeks-based-options-selection/Main.cs +++ b/project-templates/csharp/intraday-greeks-based-options-selection/Main.cs @@ -78,10 +78,10 @@ public override void Initialize() Settings.AutomaticIndicatorWarmUp = true; UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero; - // Warm-up the option contracts as soon as it is added to the algorithm + // Warm-up the option contracts as soon as it is added to the algorithm. Settings.SeedInitialPrices = true; - // The EMA/price cross will determine we trade ATM contracts + // The EMA/price cross will determine we trade ATM contracts. _index = AddIndex("RUT"); EMA(_index, 60).Updated += TradeTargetDeltaContract; @@ -91,7 +91,7 @@ public override void Initialize() public void TradeTargetDeltaContract(object sender, IndicatorDataPoint current) { - // Pace trades every 10 minutes + // Pace trades every 10 minutes. var lastTrateTime = _lastTicket?.Time ?? DateTime.MinValue; if ((UtcTime-lastTrateTime).TotalMinutes < 10) return; @@ -99,7 +99,7 @@ public void TradeTargetDeltaContract(object sender, IndicatorDataPoint current) if (!ema.IsReady) return; var spot = _index.Price; - + if (spot > current && spot > ema[-1]) { var atmCall = GetTargetDeltaContract(OptionRight.Call, spot); @@ -125,7 +125,7 @@ private Option GetTargetDeltaContract(OptionRight right, decimal spot, decimal t var chain = OptionChain(_optionChainSymbol); var expiry = chain.Min(x => x.Expiry); - // We will select the 10 contracts nearest to the money and then select the nearest contract with a given delta + // We will select the 10 contracts nearest to the money and then select the nearest contract with a given delta. var targetDeltaContract = chain .Where(x => x.Expiry == expiry && x.Right == right) .OrderBy(x => Math.Abs(spot - x.Strike)) @@ -144,7 +144,7 @@ private Option GetTargetDeltaContract(OptionRight right, decimal spot, decimal t { return null; } - + return AddOptionContract(targetDeltaContract.Symbol); } } diff --git a/project-templates/csharp/intraday-index-options-selection/Main.cs b/project-templates/csharp/intraday-index-options-selection/Main.cs index 23f031cd64..bf53d132f1 100644 --- a/project-templates/csharp/intraday-index-options-selection/Main.cs +++ b/project-templates/csharp/intraday-index-options-selection/Main.cs @@ -75,13 +75,13 @@ public override void Initialize() SetCash(500000); UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero; - // Warm-up the option contracts as soon as it is added to the algorithm + // Warm-up the option contracts as soon as it is added to the algorithm. Settings.SeedInitialPrices = true; // Create the option chain symbol for the SPXW weekly index option. var index = AddIndex("SPX"); _optionChainSymbol = QuantConnect.Symbol.CreateCanonicalOption(index, "SPXW", Market.USA, "?SPXW"); - + // Populate the updated option chain immediately to trade with. PopulateOptionChain(); @@ -99,9 +99,9 @@ private void PopulateOptionChain() var expiry = chain.Min(x => x.Expiry); _chain = [.. chain.Where(x => x.Expiry==expiry)]; } - + public void Filter() - { + { if (_chain.IsNullOrEmpty()) return; var underlying = Securities[_optionChainSymbol.Underlying]; @@ -120,10 +120,10 @@ public void Filter() { AddOptionContract(contract); } - // Since we are trading 0DTE, they will expire on end of day - // so we don't need to remove them explicitly + // Since we are trading 0DTE, they will expire on end of day. + // So we don't need to remove them explicitly. } - + public override void OnData(Slice slice) { // Only trade on updated data. @@ -138,8 +138,8 @@ public override void OnData(Slice slice) .FirstOrDefault(); // We will buy the ATM call if we don't have it. - // We are not selling the calls we have purchased previously - // So, we will buy a lot of contracts if underlying price moves a lot + // We are not selling the calls we have purchased previously. + // So, we will buy a lot of contracts if underlying price moves a lot. if (atmCall != null && !Portfolio[atmCall].Invested) MarketOrder(atmCall, 1); } diff --git a/project-templates/csharp/intraday-indicator-scans/Main.cs b/project-templates/csharp/intraday-indicator-scans/Main.cs index fa45895b51..c7398984d2 100644 --- a/project-templates/csharp/intraday-indicator-scans/Main.cs +++ b/project-templates/csharp/intraday-indicator-scans/Main.cs @@ -92,8 +92,8 @@ public override void OnSecuritiesChanged(SecurityChanges changes) private IEnumerable ETFConstituentsFilter(IEnumerable constituents) { - // Select all QQQ constituents by high ATR value - _weightBySymbol.Clear(); + // Select all QQQ constituents by high ATR value. + _weightBySymbol.Clear(); constituents.DoForEach(c => _weightBySymbol.Add(c.Symbol, c.Weight ?? 0)); return _weightBySymbol.Keys; } @@ -110,7 +110,7 @@ private void PlaceOrders() .OrderBy(security => security.Atr) .TakeLast(10) .Select(security => security.Symbol as Symbol); - // We will keep the ETF weights by scale it up to sum 1 + // We will keep the ETF weights by scale it up to sum 1. var sumOfWeight = selected.Sum(x => _weightBySymbol[x]); if (sumOfWeight == 0m) { @@ -118,7 +118,7 @@ private void PlaceOrders() } Plot("Universe", "Sum Of Weight (%)", sumOfWeight * 100m); var targets = selected.Select(x => new PortfolioTarget(x, _weightBySymbol[x] / sumOfWeight)).ToList(); - // Remove securities that are not top ATR + // Remove securities that are not top ATR. SetHoldings(targets, true); } } diff --git a/project-templates/csharp/live-trading-features/Main.cs b/project-templates/csharp/live-trading-features/Main.cs index 6aab85ef8f..70c75bf938 100644 --- a/project-templates/csharp/live-trading-features/Main.cs +++ b/project-templates/csharp/live-trading-features/Main.cs @@ -84,7 +84,7 @@ private void NotifyAll(string subject, string message) message = $"{Time:yyyyMMdd}: {subject} > {message}"; Log(message); // See https://www.quantconnect.com/docs/v2/writing-algorithms/live-trading/notifications - // for all notification methods + // For all notification methods. Notify.Sms("+16191234567", message); } @@ -148,7 +148,7 @@ private void NotifyEmaCross(Slice slice) NotifyAll($"OnCommand :: brokerage disconnected", $"Cannot place order for {data}"); return false; } - + // If we click the email link to confirm the trade, the algorithm will place the order. SetHoldings(data.Ticker, data.Size); return true; diff --git a/project-templates/csharp/trade-management/Main.cs b/project-templates/csharp/trade-management/Main.cs index d3acca2d83..d677d4bad9 100644 --- a/project-templates/csharp/trade-management/Main.cs +++ b/project-templates/csharp/trade-management/Main.cs @@ -75,15 +75,15 @@ public override void Initialize() } public override void OnData(Slice slice) - { - // If we have open stop loss and take profit orders, we won't place new orders + { + // If we have open stop loss and take profit orders, we won't place new orders. if (_spy.hasOCO || !slice.Bars.TryGetValue(_spy, out TradeBar bar)) return; - // If the price is above the EMA, we will buy 75% of the portfolio value - // and place the OCO orders to sell it. - // Otherwise, we will short 75% of the portfolio value - // and place OCO orders to rebuy. + // If the price is above the EMA, we will buy 75% of the portfolio value. + // And place the OCO orders to sell it. + // Otherwise, we will short 75% of the portfolio value. + // And place OCO orders to rebuy. var ema = _spy.Ema; var price = _spy.Price; var weight = ema > price ? .75m : -.75m; @@ -112,7 +112,7 @@ public override void OnOrderEvent(OrderEvent orderEvent) equity.stopLoss.Cancel(); equity.hasOCO = false; break; - } + } } } } diff --git a/project-templates/python/alternative-data-chain-universe-brainsentimentindicatoruniverse/main.py b/project-templates/python/alternative-data-chain-universe-brainsentimentindicatoruniverse/main.py index 4bb84e410a..641f0e3149 100644 --- a/project-templates/python/alternative-data-chain-universe-brainsentimentindicatoruniverse/main.py +++ b/project-templates/python/alternative-data-chain-universe-brainsentimentindicatoruniverse/main.py @@ -2,41 +2,44 @@ from AlgorithmImports import * # endregion -class BrainSentimentIndicatorChainedUniverseAlgorithm(QCAlgorithm): +class BrainSentimentIndicatorChainedUniverseAlgorithm(QCAlgorithm): _fundamental: list[Symbol] = [] def initialize(self) -> None: self.set_start_date(2024, 9, 1) self.set_end_date(2024, 12, 31) - self.set_cash(100000) - + self.set_cash(100_000) + self.settings.seed_initial_prices = True self.universe_settings.resolution = Resolution.DAILY - # First universe: top 100 US Equities by dollar volume; emits Universe.UNCHANGED. + # Add a fundamental universe to track the most liquid US Equities by dollar volume. self.add_universe(self._fundamental_filter) - # Second universe: positive 7-day media sentiment with active mention coverage, intersected with the fundamental list. + # Add a Brain Sentiment universe, restricted to high-sentiment names within the fundamental list. self._universe = self.add_universe(BrainSentimentIndicatorUniverse, self._select_assets) - - # Rebalance shortly after the open so today's intersection is locked in. - self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.at(9, 0, 0), self._rebalance) + # Rebalance shortly after the open. + self.schedule.on( + self.date_rules.every_day("SPY"), + self.time_rules.at(9, 0), + self._rebalance + ) def _fundamental_filter(self, fundamental: List[Fundamental]) -> Universe.UnchangedUniverse: - sorted_by_dollar_volume = sorted(fundamental, key=lambda x: x.dollar_volume, reverse=True) - self._fundamental = [c.symbol for c in sorted_by_dollar_volume[:100]] + self._fundamental = [c.symbol for c in sorted(fundamental, key=lambda x: x.dollar_volume)[-100:]] return Universe.UNCHANGED def _select_assets(self, alt_coarse: List[BrainSentimentIndicatorUniverse]) -> List[Symbol]: - # Keep names with both active mention coverage and positive 7-day sentiment. + # Keep only names with active mention coverage and positive sentiment. alt = [d.symbol for d in alt_coarse - if d.total_article_mentions_7_days and d.total_article_mentions_7_days > 0 - and d.sentiment_7_days and d.sentiment_7_days > 0] - return list(set(self._fundamental) & set(alt)) + if d.total_article_mentions_7_days and + d.total_article_mentions_7_days > 0 and + d.sentiment_7_days and + d.sentiment_7_days > 0] + return [s for s in self._fundamental if s in alt] def _rebalance(self) -> None: if not self._universe.selected: return - + # Enter the universe equally weighted across all selected assets. weight = 1 / len(self._universe.selected) targets = [PortfolioTarget(symbol, weight) for symbol in self._universe.selected] - - self.set_holdings(targets, liquidate_existing_holdings=True) + self.set_holdings(targets, True)