### Keras Model Training Example Setup Source: https://www.quantconnect.com/docs/v2/research-environment/machine-learning/popular-libraries/keras Imports necessary Keras and QuantConnect libraries, initializes QuantBook, requests historical data, and calculates daily returns for feature engineering. ```python # Import the Keras library. from tensorflow.keras import utils, models from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras.optimizers import RMSprop from tensorflow.keras.saving import load_model # Instantiate the QuantBook for researching. qb = QuantBook() # Request the daily SPY history with the date range to be studied. symbol = qb.add_equity("SPY", Resolution.DAILY).symbol history = qb.history(symbol, datetime(2020, 1, 1), datetime(2022, 1, 1)).loc[symbol] # Obtain the daily returns to be the features and labels. daily_returns = history['close'].pct_change()[1:] # We use the previous 5 day returns as the features to be studied. # Get the 1-day forward return as the labels for the machine to learn. n_steps = 5 features = [] labels = [] for i in range(len(daily_returns)-n_steps): features.append(daily_returns.iloc[i:i+n_steps].values) labels.append(daily_returns.iloc[i+n_steps]) # Split the data as a training set and test set for validation. In this example, we use 70% of the data points to train the model and test with the rest. features = np.array(features) labels = np.array(labels) train_length = int(len(features) * 0.7) X_train = features[:train_length] X_test = features[train_length:] y_train = labels[:train_length] y_test = labels[train_length:] ``` -------------------------------- ### Get Historical Universe Data in Research (Python) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/brain/brain-language-metrics-on-company-filings Utilize the universe_history method with the universe object, start date, and end date for DataFrame or Series output. The DataFrame example flattens universe object attributes, while the Series example returns values as lists of universe objects. ```python # DataFrame example where the columns are the universe object attributes: history_df = qb.universe_history(universe, qb.time-timedelta(30), qb.time, flatten=True) # Series example where the values are lists of the universe objects: universe_history = qb.universe_history(universe, qb.time-timedelta(30), qb.time) for (_, time), universeDay in universe_history.items(): for language_metrics in universeDay: print(f"{language_metrics.symbol} sentiment at {language_metrics.end_time}: {language_metrics.report_sentiment.sentiment}") ``` -------------------------------- ### Install Anaconda on Linux Source: https://www.quantconnect.com/docs/v2/lean-cli/installation/installing-pip Run this command in the terminal to start the Anaconda installer script on a Linux system. Replace `` with the actual installer file name. ```bash bash ``` -------------------------------- ### Research Environment Setup and Indicator Calculation (C#) Source: https://www.quantconnect.com/docs/v2/research-environment/indicators/combining-indicators Import necessary packages, instantiate QuantBook, request data, and create composite indicators. This sets up the environment for calculating and analyzing indicator values. ```csharp // Import the QuantConnect, Plotly.NET, and Accord packages for calculation and plotting. using QuantConnect; using QuantConnect.Indicators; using QuantConnect.Research; using Plotly.NET; using Plotly.NET.Interactive; using Plotly.NET.LayoutObjects; // Instantiate the QuantBook instance for researching. var qb = new QuantBook(); // Request SPY data to work with the indicator. var symbol = qb.AddEquity("SPY").Symbol; // Create the SD on Return indicator with parameters to be studied. var roc = new RateOfChange(1); var sd = new StandardDeviation(252); var indicator = IndicatorExtensions.Of(sd, roc); // Get the history of SPY to update the indicator and trade. var history = qb.History(symbol, 500, Resolution.Daily).ToList(); var indicatorValues = new List(); var time = new List(); for (int i = 0; i < history.Count - 1; i++) { // Update the indicator value. var bar = history[i]; roc.Update(bar); indicatorValues.Add(indicator.Current.Value); time.Add(bar.EndTime); } // Create line chart of the SD of Return. var chart = Chart2D.Chart.Line( time, indicatorValues ); // Create a Layout as the plot settings. LinearAxis xAxis = new LinearAxis(); xAxis.SetValue("title", "Time"); LinearAxis yAxis = new LinearAxis(); yAxis.SetValue("title", "%ի"); Title title = Title.init($"Return SD of {symbol}"); Layout layout = new Layout(); layout.SetValue("xaxis", xAxis); layout.SetValue("yaxis", yAxis); layout.SetValue("title", title); // Assign the Layout to the chart. chart.WithLayout(layout); // Display the plot. display(chart) ``` -------------------------------- ### Install Miniforge on macOS (Apple Chip) Source: https://www.quantconnect.com/docs/v2/lean-cli/installation/installing-pip Execute this command in the terminal to start the Miniforge installer script on a Mac with an Apple chip. ```bash bash Miniforge3-MacOSX-arm64.sh ``` -------------------------------- ### Initialize Research Environment and Fetch Data (C#) Source: https://www.quantconnect.com/docs/v2/research-environment/applying-research/mean-reversion Sets up the QuantBook, defines a list of tickers, adds them to the algorithm with minute resolution, and fetches daily historical data for the specified date range. Ensure all tickers are valid and data is available for the requested period. ```csharp using QuantConnect; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Algorithm; using QuantConnect.Research; using System; using MathNet.Numerics.Distributions; // Instantiate a QuantBook var qb = new QuantBook(); // Select the desired tickers for research. var assets = new List() {"SHY", "TLT", "SHV", "TLH", "EDV", "BIL", "SPTL", "TBT", "TMF", "TMV", "TBF", "VGSH", "VGIT", "VGLT", "SCHO", "SCHR", "SPTS", "GOVT"}; // Call the AddEquity method with the tickers, and their corresponding resolution. foreach(var ticker in assets){ qb.AddEquity(ticker, Resolution.Minute); } // Call the History method with qb.Securities.Keys for all tickers, time argument(s), and resolution to request historical data for the symbol. var history = qb.History(qb.Securities.Keys, new DateTime(2020, 1, 1), new DateTime(2022, 1, 1), Resolution.Daily); ``` -------------------------------- ### Python Authentication and Project Setup Example Source: https://www.quantconnect.com/docs/v2/cloud-platform/api-reference/optimization-management/create-optimization Demonstrates how to authenticate with the QuantConnect API and set up a project ID for managing optimization jobs. Ensure your credentials and organization ID are replaced with actual values. ```python from base64 import b64encode from hashlib import sha256 from time import time from requests import get, post BASE_URL = 'https://www.quantconnect.com/api/v2/' # You need to replace these with your actual credentials. # You can request your credentials at https://www.quantconnect.com/settings/ # You can find our organization ID at https://www.quantconnect.com/organization/ USER_ID = 0 API_TOKEN = '____' ORGANIZATION_ID = '____' def get_headers(): # Get timestamp timestamp = f'{int(time())}' time_stamped_token = f'{API_TOKEN}:{timestamp}'.encode('utf-8') # Get hased API token hashed_token = sha256(time_stamped_token).hexdigest() authentication = f'{USER_ID}:{hashed_token}'.encode('utf-8') authentication = b64encode(authentication).decode('ascii') # Create headers dictionary. return { 'Authorization': f'Basic {authentication}', 'Timestamp': timestamp } # Authenticate to verify credentials response = post(f'{BASE_URL}/authenticate', headers = get_headers()) print(response.json()) # -------------------- # The project ID of the project to manage an optimization job project_id = 12345678 ``` -------------------------------- ### Read Live Insights Request Example Source: https://www.quantconnect.com/docs/v2/cloud-platform/api-reference/live-management/read-live-algorithm/insights This is an example of the JSON payload required to request insights from a live algorithm. Ensure 'end' - 'start' is less than 100. ```json { "algorithmId": "L-6e9d8a78f5af89d401f630585be90e43", "start": 0, "end": 100, "projectId": 23456789 } ``` -------------------------------- ### Get Historical Tick Data (Python) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/asset-classes/crypto Retrieves historical tick data for a specified cryptocurrency symbol as a DataFrame. This example shows how to get the data and then filter for trade ticks. ```Python class CryptoTickHistoryAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2024, 12, 19) self.set_end_date(2024, 12, 31) # Get the Symbol of a security. symbol = self.add_crypto('BTCUSD', market=Market.BITFINEX).symbol # Get the trailing 2 days of ticks for the security in DataFrame format. history = self.history(symbol, timedelta(2), Resolution.TICK) ``` ```Python # Select the rows in the DataFrame that represent trades. Drop the bid/ask columns since they are NaN. trade_ticks = history[history.quantity > 0].dropna(axis=1) ``` -------------------------------- ### Initialize FrameworkExecutionModelAlgorithm Source: https://www.quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/execution/key-concepts Sets up the algorithm with start/end dates, cash, universe selection, alpha model, portfolio construction, and execution model. ```python class FrameworkExecutionModelAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2024, 9, 1) self.set_end_date(2024, 12, 31) self.set_cash(100000000) # Add a universe of the most liquid stocks since their trend is more capital-supported. self.add_universe_selection(QC500UniverseSelectionModel()) # Emit insights all for selected stocks. self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(7))) # Equal weighting on each insight to dissipate capital risk evenly. self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) # Iceberg ordering to hide traces and avoid market impact. # Since quote data will be used, ensure the asset class and resolution are compatible. self.set_execution(IcebergExecutionModel(0.1)) ``` -------------------------------- ### Get Historical Indicator Data (Python) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/asset-classes/futures Retrieves historical indicator values for a security using the `indicator_history` method. This example shows how to get 21-day SMA values for the last 5 trading days. ```Python class FuturesIndicatorHistoryAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2024, 12, 19) self.set_end_date(2024, 12, 31) # Get the Symbol of a security. symbol = self.add_future(Futures.Indices.SP_500_E_MINI).symbol # Get the 21-day SMA values of the security for the last 5 trading days. history = self.indicator_history(SimpleMovingAverage(21), symbol, 5, Resolution.DAILY) ``` -------------------------------- ### Initialize QuantBook and Fetch History Source: https://www.quantconnect.com/docs/v2/research-environment/key-concepts/research-engine Demonstrates how to initialize a QuantBook instance and retrieve historical equity data in the research environment. ```C# // Initialize QuantBook var qb = new QuantBook(); // Subscribe to SPY data with QuantBook var symbol = qb.AddEquity("SPY").Symbol; // Make history call with QuantBook var history = qb.History(symbol, TimeSpan.FromDays(10), Resolution.Daily); ``` ```Python # Initialize QuantBook qb = QuantBook() # Subscribe to SPY data with QuantBook symbol = qb.add_equity("SPY").symbol # Make history call with QuantBook history = qb.history(symbol, timedelta(days=10), Resolution.DAILY) ``` -------------------------------- ### Get Historical Indicator Data (C#) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/asset-classes/futures Retrieves historical indicator values for a security using the `IndicatorHistory` method. This example shows how to get 21-day SMA values for the last 5 trading days. ```C# public class FuturesIndicatorHistoryAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2024, 12, 19); SetEndDate(2024, 12, 31); // Get the Symbol of a security. var symbol = AddFuture(Futures.Indices.SP500EMini).Symbol; // Get the 21-day SMA values of the security for the last 5 trading days. var history = IndicatorHistory(new SimpleMovingAverage(21), symbol, 5, Resolution.Daily); // Get the maximum of the SMA values. var maxSMA = history.Max(indicatorDataPoint => indicatorDataPoint.Current.Value); } } ``` -------------------------------- ### Live Deployment Configuration Example Source: https://www.quantconnect.com/docs/v2/cloud-platform/api-reference/project-management/create-project Specifies the configuration for a live deployment, including brokerage data, data providers, node information, and notification settings. ```json { "brokerageData": { "id": "string", "authentication": }, "dataProvidersData": [ { "id": "string" } ], "node": "string", "notifyInsights": true, "notifyOrderEvents": true, "autoRestart": true } ``` -------------------------------- ### Create Live Algorithm Request Example Source: https://www.quantconnect.com/docs/v2/cloud-platform/api-reference/live-management/create-live-algorithm This example demonstrates the structure of a request to create a live algorithm, including essential parameters and nested brokerage configurations. ```json { "versionId": "-1", "projectId": 23456789, "compileId": "5d1f2cba3a0ec7407c566614300502b5-173e0419674daf4144ce7c9931155ca8", "nodeId": "LN-c54129e1b4f667613d3f34542b787771", "brokerage": { "QuantConnectBrokerageSettings": object, "InteractiveBrokersBrokerageSettings": object, "TradierBrokerageSettings": object, "BitfinexSettings": object, "CoinbaseBrokerageSettings": { { "id": "CoinbaseBrokerage", "coinbase-api-name": "string", "coinbase-api-private-key": "string" }, }, "BinanceBrokerageSettings": { { "id": "BinanceBrokerage", "binance-exchange-name": "Binance", "binance-api-key": "string", "binance-api-secret": "string", "binance-use-testnet": "live" }, }, "BinanceUSBrokerageSettings": { { "id": "BinanceBrokerage", "binance-exchange-name": "BinanceUS", "binanceus-api-key": "string", "binanceus-api-secret": "string" }, }, "BinanceUSDMFuturesBrokerageSettings": { { "id": "BinanceBrokerage", "binance-exchange-name": "Binance-USDM-Futures", "binance-api-key": "string", "binance-api-secret": "string" }, }, "BinanceCOINFuturesBrokerageSettings": { { "id": "BinanceBrokerage", "binance-exchange-name": "Binance-COIN-Futures", "binance-api-key": "string", "binance-api-secret": "string" }, }, "TradingTechnologiesBrokerageSettings": object, "KrakenSettings": object, "BybitBrokerageSettings": { { "id": "BybitBrokerage", "bybit-api-key": "string", "bybit-api-secret": "string", "bybit-vip-level": "VIP0" }, }, "OandaSettings": object, "WolverineSettings": object, "CharlesSchwabSettings": object, "RBIBrokerageSettings": object, "TerminalLinkSettings": object, "TradeStationSettings": object, "TastytradeSettings": object, "AlpacaBrokerageSettings": object, "WebullBrokerageSettings": object, }, "dataProviders": } ``` -------------------------------- ### C# Example: Micro Gold vs Gold Futures Source: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/futures/handling-data This C# example shows how to use SymbolPropertiesDatabase to get contract multipliers for Micro Gold and Gold Future contracts. It then invests $500k nominal value into each. ```C# public class FutureNominalBuysAlgorithm : QCAlgorithm { private List _futures = new(); public override void Initialize() { SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); SetCash(1_000_000); // Set the continuous contract mapping criteria for both Futures // since we want to trade the most liquid contracts. foreach (var ticker in new[] { Futures.Metals.Gold, Futures.Metals.MicroGold }) { var future = AddFuture( ticker, extendedMarketHours: true, dataMappingMode: DataMappingMode.OpenInterest, dataNormalizationMode: DataNormalizationMode.BackwardsRatio, contractDepthOffset: 0 ); future.SetFilter(0, 180); _futures.Add(future); } } public override void OnData(Slice slice) { // Wait until we aren't invested and we have bars for all Futures. if (!Portfolio.Invested && _futures.All(f => slice.Bars.ContainsKey(f.Symbol))) { foreach (var future in _futures) { // Calculate the order size for $500k. Get the quotient // after dividing by the contract multiplier since the // order size must be whole number. var quantity = (int)Math.Floor( 500_000m / (future.Price * future.SymbolProperties.ContractMultiplier) ); if (quantity == 0) { continue; } MarketOrder(future.Mapped, quantity); } } } } ``` -------------------------------- ### Algorithm Initialization with Resolution Warm-up (C#) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/warm-up-periods Initializes an algorithm with specific dates, adds equity and crypto subscriptions, and sets a warm-up period using a specified resolution (Minute) and number of bars (100). This example also includes SMA indicators to demonstrate compatibility with different resolutions. ```csharp public class WarmUpWithTrailingDataSamplesAndResolutionAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); var spy = AddEquity("SPY", Resolution.Minute, fillForward: false).Symbol; var btc = AddCrypto("BTCUSD", Resolution.Second, fillForward: false).Symbol; var spySma = SMA(spy, 10); var btcSMA = SMA(btc, 10, Resolution.Minute); SetWarmUp(100, Resolution.Minute); } } ``` -------------------------------- ### Get Historical Estimize Data (C#) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/extractalpha/estimize Retrieve historical Estimize data using the History method in C#. This example shows how to get data as typed dataset objects or as a Slice object containing multiple datasets. ```C# // Dataset objects var concensusHistory = History(_estimizeConsensusSymbol, 100, Resolution.Daily); var estimateHistory = History(_estimizeEstimateSymbol, 100, Resolution.Daily); var releaseHistory = History(_estimizeReleaseSymbol, 100, Resolution.Daily); // Slice objects var history = History(new[]{_estimizeConsensusSymbol, _estimizeEstimateSymbol, _estimizeReleaseSymbol}, 10, Resolution.Daily); ``` -------------------------------- ### Get Historical Slice Data (Python) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/asset-classes/equity-options Use the `history` method without `Symbol` objects to get `Slice` data for all subscriptions. The default resolution is used if not specified. This example retrieves daily data for the last 5 days. ```python class SliceHistoryAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2024, 12, 1) self.set_end_date(2024, 12, 31) # Add some securities and datasets. equity = self.add_equity('SPY', data_normalization_mode=DataNormalizationMode.RAW) contract = sorted(self.option_chain(equity.symbol), key=lambda c: c.open_interest)[-1] self.add_option_contract(contract.symbol) # Get the historical Slice objects over the last 5 days for all the subcriptions in your algorithm. history = self.history(5, Resolution.DAILY) # Iterate through each historical Slice. for slice_ in history: # Iterate through each TradeBar in this Slice. for symbol, trade_bar in slice_.bars.items(): close = trade_bar.close ``` -------------------------------- ### Initialize Algorithm with Binance US Data Source: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/quantconnect/binance-us-crypto-price-data Set up the algorithm's start and end dates, initial cash, brokerage model, and request minute-resolution BTCUSD data from Binance US. ```Python class CoinAPIDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2020, 6, 1) self.set_end_date(2021, 6, 1) self.set_cash(100000) # BinanceUS accepts Cash account type only, AccountType.MARGIN will result in an exception. self.set_brokerage_model(BrokerageName.BINANCE_US, AccountType.CASH) self.btcbusd = self.add_crypto("BTCUSD", Resolution.MINUTE, Market.BINANCE_US).symbol ``` ```C# public class CoinAPIDataAlgorithm : QCAlgorithm { private Symbol _symbol; public override void Initialize() { SetStartDate(2020, 6, 1); SetEndDate(2021, 6, 1); SetCash(100000); // BinanceUS accepts Cash account type only, AccountType.Margin will result in an exception. SetBrokerageModel(BrokerageName.BinanceUS, AccountType.Cash); _symbol = AddCrypto("BTCUSD", Resolution.Minute, Market.BinanceUS).Symbol; } } ``` -------------------------------- ### Get Average Range Indicator History Source: https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/supported-indicators/average-range Demonstrates how to get the historical data for the Average Range indicator using different time period specifications. The `IndicatorHistory` method can accept a number of bars, a TimeSpan, or specific start and end dates. ```C# public class AverageRangeAlgorithm : QCAlgorithm { private Symbol _symbol; private AverageRange _ar; public override void Initialize() { _symbol = AddEquity("SPY", Resolution.Daily).Symbol; _ar = AR(_symbol, 20); var indicatorHistory = IndicatorHistory(_ar, _symbol, 100, Resolution.Minute); var timeSpanIndicatorHistory = IndicatorHistory(_ar, _symbol, TimeSpan.FromDays(10), Resolution.Minute); var timePeriodIndicatorHistory = IndicatorHistory(_ar, _symbol, new DateTime(2024, 7, 1), new DateTime(2024, 7, 5), Resolution.Minute); } } ``` ```Python class AverageRangeAlgorithm(QCAlgorithm): def initialize(self) -> None: self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol self._ar = self.ar(self._symbol, 20) indicator_history = self.indicator_history(self._ar, self._symbol, 100, Resolution.MINUTE) timedelta_indicator_history = self.indicator_history(self._ar, self._symbol, timedelta(days=10), Resolution.MINUTE) time_period_indicator_history = self.indicator_history(self._ar, self._symbol, datetime(2024, 7, 1), datetime(2024, 7, 5), Resolution.MINUTE) ``` -------------------------------- ### Initialize FrameworkRiskManagementAlgorithm Source: https://www.quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/risk-management/key-concepts Initializes a QuantConnect algorithm with universe selection, alpha model, portfolio construction, and TVaR risk management. ```python from scipy.stats import norm class FrameworkRiskManagementAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2024, 9, 1) self.set_end_date(2024, 9, 15) self.set_cash(1000000) # Add a universe of the most liquid stocks since their trend is more capital-supported. self.add_universe_selection(ETFConstituentsUniverseSelectionModel('SPY')) # Emit insights for all selected stocks, rebalancing every two weeks. self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(14))) # Equal weighting on each insight is needed to dissipate capital risk evenly. self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel()) # Liquidate on extreme catastrophic events. self.add_risk_management(TailValueAtRiskRiskManagementModel(0.05, 14)) ``` -------------------------------- ### Get Historical Universe Data in Research (C#) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/brain/brain-language-metrics-on-company-filings Call the UniverseHistory method with the Universe object, start date, and end date to get filtered historical universe data in research. An empty result indicates no data for the specified period. ```csharp var universeHistory = qb.UniverseHistory(universe, qb.Time.AddDays(-30), qb.Time); foreach (var universeDay in universeHistory) { foreach (BrainCompanyFilingLanguageMetricsUniverse10K languageMetrics in universeDay) { Console.WriteLine($"{languageMetrics.Symbol} sentiment at {languageMetrics.EndTime}: {languageMetrics.ReportSentiment.Sentiment}"); } } ``` -------------------------------- ### Manual Delta Indicator Algorithm Setup (C#) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/equity-options/greeks-and-implied-volatility/indicators This C# algorithm initializes the QuantConnect environment, subscribes to an equity, and sets up a scheduled event to update option contracts and indicators daily. It includes setup for a dividend yield provider and specifies an option pricing model. ```C# public class ManualDeltaIndicatorAlgorithm : QCAlgorithm { private Symbol _underlying; private DividendYieldProvider _dividendYieldProvider; // Define the Option pricing model. private readonly OptionPricingModelType _optionPricingModel = OptionPricingModelType.ForwardTree; private (Symbol option1, Symbol option2) _options; public override void Initialize() { SetStartDate(2024, 9, 1); SetEndDate(2024, 9, 30); SetCash(500000); // Seed the price of each asset with its last known price to avoid trading errors. Settings.SeedInitialPrices = true; // Subscribe to the underlying asset. _underlying = AddEquity("SPY", dataNormalizationMode: DataNormalizationMode.Raw).Symbol; // Set up dividend yield provider for the underlying _dividendYieldProvider = new(_underlying); // Set up a Scheduled Event to select contract and create the indicators every day before market open. Schedule.On( DateRules.EveryDay(_underlying), TimeRules.At(9, 0), UpdateContractsAndGreeks ); } ``` -------------------------------- ### Instantiate QuantBook and Request Equity Data Source: https://www.quantconnect.com/docs/v2/research-environment/indicators/combining-indicators Initializes the QuantBook instance and adds equity data for research. Ensure QuantBook is imported before use. ```python qb = QuantBook() symbol = qb.add_equity("SPY").symbol ``` -------------------------------- ### Get Trading Days Source: https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/trading-calendar Retrieves all trading events within a specified date range. Requires start and end DateTime objects. ```APIDOC ## GetTradingDays ### Description Retrieves all trading events across a range of dates. ### Method `GetTradingDays` ### Parameters - **startDate** (DateTime) - Required - The start date of the range. - **endDate** (DateTime) - Required - The end date of the range. ### Request Example (C#) ```csharp var startDate = new DateTime(2022, 6, 1); var endDate = new DateTime(2022, 7, 1); var tradingDays = TradingCalendar.GetTradingDays(startDate, endDate); ``` ### Request Example (Python) ```python from datetime import datetime start_date = datetime(2022, 6, 1) end_date = datetime(2022, 7, 1) trading_days = self.trading_calendar.get_trading_days(start_date, end_date) ``` ### Response - **tradingDays** (List[TradingDay]) - A list of trading days within the specified range. ``` -------------------------------- ### Initialize Algorithm with Bybit Data (C#) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/quantconnect/bybit-crypto-price-data Sets up the algorithm's start and end dates, account currency, brokerage model, and requests BTCUSDT data. Uses Margin account type for Bybit. ```csharp public class CoinAPIDataAlgorithm : QCAlgorithm { private Symbol _symbol; public override void Initialize() { SetStartDate(2020, 6, 1); SetEndDate(2021, 6, 1); // Set Account Currency to Tether SetAccountCurrency("USDT", 100000); // Bybit accepts both Cash and Margin account types. SetBrokerageModel(BrokerageName.Bybit, AccountType.Margin); _symbol = AddCrypto("BTCUSDT", Resolution.Minute, Market.Bybit).Symbol; } } ``` -------------------------------- ### Add Bitcoin Metadata Data Source: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/blockchain/bitcoin-metadata Demonstrates how to add the Bitcoin Metadata dataset to your algorithm. This snippet is used in the 'Getting Started' section. ```C# _symbol = AddCrypto("BTCUSD", Resolution.Daily, Market.Bitfinex).Symbol; _datasetSymbol = AddData(_symbol).Symbol; ``` -------------------------------- ### Example Non-Interactive Live Deploy Source: https://www.quantconnect.com/docs/v2/lean-cli/api-reference/lean-live-deploy This example demonstrates how to deploy a project for live trading in a non-interactive mode, specifying brokerage and data provider options directly on the command line. It overrides any default or configuration file settings for the specified options. ```bash $ lean live deploy "My Project" \ --brokerage "Paper Trading" \ --data-provider-live "Interactive Brokers" \ --ib-user-name trader777 \ --ib-account DU1234567 \ --ib-password hunter2 \ --ib-enable-delayed-streaming-data yes ``` -------------------------------- ### Add Bitcoin Metadata Data Source: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/blockchain/bitcoin-metadata Demonstrates how to add the Bitcoin Metadata dataset to your algorithm. This snippet is used in the 'Getting Started' section. ```Python self.btcusd = self.add_crypto("BTCUSD", Resolution.DAILY, Market.BITFINEX).symbol self.dataset_symbol = self.add_data(BitcoinMetadata, self.btcusd).symbol ``` -------------------------------- ### C# Manual Indicator Algorithm Setup Source: https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/indicator-universes Initializes a QCAlgorithm in C# with dictionaries to store Maximum indicators and SymbolData for each security. This setup is for manual indicator management within a universe selection context. ```csharp public class ManualIndicatorAlgorithm : QCAlgorithm { private Dictionary _maximumBySymbol = new(); private Dictionary _symbolData = new(); ``` -------------------------------- ### Get Option Chain (C#) Source: https://www.quantconnect.com/docs/v2/research-environment/datasets/equity-options/individual-contracts Retrieves the OptionChain for the underlying equity symbol, representing all tradable contracts on the set start date. ```csharp // Get the Option contracts that were tradable on January 1st, 2024. var chain = qb.OptionChain(underlyingSymbol); ``` -------------------------------- ### Python SuperTrend Indicator History Examples Source: https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/supported-indicators/super-trend Shows how to get SuperTrend indicator history with a bar count, timedelta, and specific dates in Python. ```Python class SuperTrendAlgorithm(QCAlgorithm): def initialize(self) -> None: self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol self._str = self.str(self._symbol, 20, 2, MovingAverageType.WILDERS) indicator_history = self.indicator_history(self._str, self._symbol, 100, Resolution.MINUTE) timedelta_indicator_history = self.indicator_history(self._str, self._symbol, timedelta(days=10), Resolution.MINUTE) time_period_indicator_history = self.indicator_history(self._str, self._symbol, datetime(2024, 7, 1), datetime(2024, 7, 5), Resolution.MINUTE) ``` -------------------------------- ### Initialize Bybit Crypto Algorithm Source: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/quantconnect/bybit-crypto-price-data Sets up the algorithm with Bybit brokerage, account currency, and adds BTCUSDT minute data. It also demonstrates fetching historical data and adding a dynamic universe for Bybit crypto pairs. ```C# public class CoinAPIDataAlgorithm : QCAlgorithm { private Crypto _btc; public override void Initialize() { SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); // Set the account currency to USDT, since you can't trade with // USD and the algorithm doesn't automatically convert USD & USDT // holdings. SetAccountCurrency("USDT", 100000); UniverseSettings.Asynchronous = true; // Bybit accepts both Cash and Margin account types. Select the // one you need for the best reality modeling. SetBrokerageModel(BrokerageName.Bybit, AccountType.Margin); // Add BTCUSDT data. _btc = AddCrypto("BTCUSDT", Resolution.Minute, Market.Bybit); // Historical data var history = History(_btc.Symbol, 30, Resolution.Daily); // Add a Crypto universe that selects trading pairs on Bybit. var universe = AddUniverse(CryptoUniverse.Bybit(SelectAssets)); // Historical Universe data var universeHistory = History(universe, 30, Resolution.Daily); foreach (var universeDay in universeHistory) { foreach (CryptoUniverse universeItem in universeDay) { var symbol = universeItem.Symbol; var price = universeItem.Close; } } } private IEnumerable SelectAssets(IEnumerable universeDay) { // Filter for materially traded Crypto pairs with significant // size and dollar volume, assuming higher capital flow in for // higher return. return from universeItem in universeDay where universeItem.Volume >= 100m && universeItem.VolumeInUsd > 10000000m select universeItem.Symbol; } public override void OnData(Slice slice) { // Speculate-invest all available free cash on BTCUSDT, repecting // the order quantity restrictions to avoid invalid orders. if (Portfolio.CashBook["BTC"].Amount != 0) { return; } // Define a buffer so that we can scale down the order size, // avoiding trading errors. var buffer = Math.Max(BybitFeeModel.TakerNonVIPFee, Settings.FreePortfolioValuePercentage); var quantity = Portfolio.CashBook["USDT"].Amount / _btc.AskPrice * (1-buffer); // Check if the quantity exceeds the minimum order size. On // Bybit, the minimum order size is measured in the base // currency (BTC in this case). if (Math.Abs(quantity) < _btc.SymbolProperties.MinimumOrderSize) { return; } MarketOrder(_btc, quantity); } } ``` -------------------------------- ### Python Example: Get Takuri Indicator History Source: https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/supported-indicators/candlestick-patterns/takuri Demonstrates how to get historical data for the Takuri indicator in Python. It shows requests based on a number of bars, a time span, and a specific date period. The default resolution matches the security subscription if not specified. ```python class TakuriAlgorithm(QCAlgorithm): def initialize(self) -> None: self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol self._takuri = self.candlestick_patterns.takuri(self._symbol) indicator_history = self.indicator_history(self._takuri, self._symbol, 100, Resolution.MINUTE) timedelta_indicator_history = self.indicator_history(self._takuri, self._symbol, timedelta(days=10), Resolution.MINUTE) time_period_indicator_history = self.indicator_history(self._takuri, self._symbol, datetime(2024, 7, 1), datetime(2024, 7, 5), Resolution.MINUTE) ``` -------------------------------- ### Initialize Algorithm with Kavout Composite Factor Bundle Source: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/kavout/composite-factor-bundle Sets up the algorithm's start and end dates, initial cash, and requests the Kavout Composite Factor Bundle data. This is a common setup for algorithms using this dataset. ```C# public class KavoutCompositeFactorBundleAlgorithm : QCAlgorithm { private Symbol _symbol, _datasetSymbol; public override void Initialize() { SetStartDate(2019, 1, 1); SetEndDate(2020, 6, 1); SetCash(100000); _symbol = AddEquity("AAPL", Resolution.Daily).Symbol; _datasetSymbol = AddData(_symbol).Symbol; } } ``` -------------------------------- ### Algorithm Initialization with Trailing Warm-up (C#) Source: https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/warm-up-periods Initializes an algorithm with specific start and end dates, adds equity and crypto subscriptions, and sets a warm-up period of 100 bars. This ensures sufficient historical data for analysis before live trading. ```csharp public class WarmUpWithTrailingDataSamplesAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2024, 9, 1); SetEndDate(2024, 12, 31); AddEquity("SPY", Resolution.Minute, fillForward: false); AddCrypto("BTCUSD", Resolution.Second, fillForward: false); SetWarmUp(100); } } ``` -------------------------------- ### C# Example: Get Takuri Indicator History Source: https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/supported-indicators/candlestick-patterns/takuri Demonstrates how to get historical data for the Takuri indicator in C#. It shows requests based on a number of bars, a time span, and a specific date period. The default resolution matches the security subscription if not specified. ```csharp public class TakuriAlgorithm : QCAlgorithm { private Symbol _symbol; private Takuri _takuri; public override void Initialize() { _symbol = AddEquity("SPY", Resolution.Daily).Symbol; _takuri = CandlestickPatterns.Takuri(_symbol); var indicatorHistory = IndicatorHistory(_takuri, _symbol, 100, Resolution.Minute); var timeSpanIndicatorHistory = IndicatorHistory(_takuri, _symbol, TimeSpan.FromDays(10), Resolution.Minute); var timePeriodIndicatorHistory = IndicatorHistory(_takuri, _symbol, new DateTime(2024, 7, 1), new DateTime(2024, 7, 5), Resolution.Minute); } } ``` -------------------------------- ### Deploy a Lean Cloud Project for Live Trading Source: https://www.quantconnect.com/docs/v2/lean-cli/api-reference/lean-cloud-live-deploy Starts live trading for a cloud project. Use the `--open` flag to automatically open the results URL in your browser. Requires membership in an organization on a paid tier. ```bash $ lean cloud live deploy [OPTIONS] PROJECT ``` -------------------------------- ### Trade at Opening Auction Python Example Source: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/us-equity/data-preparation This Python example shows how to schedule an event to place a Market On Open order, filling at the official opening auction price. It involves setting start and end dates, adding equity data, and scheduling a rebalance function. ```python class USEquityDataPreparationExampleAlgorithm(QCAlgorithm): def initialize(self): self.set_start_date(2024, 9, 1) self.set_end_date(2024, 12, 31) # Add Equity data. self._spy = self.add_equity("SPY", extended_market_hours=True).symbol # Create a Scheduled Event that rebalances with market on open orders. self.schedule.on( self.date_rules.every_day(self._spy), self.time_rules.before_market_open(self._spy, 30), self._rebalance ) def _rebalance(self): quantity = self.calculate_order_quantity(self._spy, 0.1) if quantity: self.market_on_open_order(self._spy, quantity) ```