Key Concepts

Getting Started

GET STARTED WITH WRITING ALGORITHMS

Guide through creating a project, running your first backtest, and live algo trading.

Terminal Home Page

Follow these steps to write your first trading algorithm:

1. Create a new project.

The process to creating a new project depends on if you use the Cloud Platform, Local Platform, or CLI.

2. In the Initializeinitialize method, add a universe to the algorithm.

For example, you may want to trade the US Equities that make up the S&P 500.

// Define the _universe member at the class level.
private Universe _universe;
_universe = Universe.ETF("SPY");
AddUniverse(_universe);
self._universe = self.universe.etf('SPY')
self.add_universe(self._universe)

3. In the Initializeinitialize method, enable the following settings.

Settings.AutomaticIndicatorWarmUp = true;
Settings.SeedInitialPrices = true;
self.settings.automatic_indicator_warm_up = True
self.settings.seed_initial_prices = True

4. In the Initializeinitialize method, add a Scheduled Event to rebalance the portfolio each week.

Schedule.On(DateRules.WeekStart("SPY"), TimeRules.At(8, 0), Rebalance);
self.schedule.on(self.date_rules.week_start('SPY'), self.time_rules.at(8, 0), self._rebalance)

5. Add an OnSecuritiesChangedon_securities_changed method that creates an indicator for each stock in the universe.

For example, you may want to track the trailing 1-month returns of each stock.

public override void OnSecuritiesChanged(SecurityChanges changes)
{
    foreach (dynamic security in changes.AddedSecurities)
    {
        security.Roc = ROC(security, 21, Resolution.Daily);
    }
}
def on_securities_changed(self, changes):
    for security in changes.added_securities:
        security.roc = self.roc(security, 21, Resolution.DAILY)

Duck typing the indicator onto the Security object saves you from creating a new data structure.

6. Add your trading rules and position sizing to the Rebalance_rebalance method that runs each week.

private void Rebalance()
{
    // Get the stocks that are currently in the universe.
    var securities = _universe.Selected.Select(symbol => Securities[symbol]);
    // Select the 10 stocks with the greatest trailing returns.
    var selectedAssets = securities.Where(s => ((dynamic)s).Roc.IsReady).OrderBy(s => ((dynamic)s).Roc).TakeLast(10);
    // Form an equal-weighted portfolio.
    var targets = selectedAssets.Select(security => new PortfolioTarget(security.Symbol, 1m / selectedAssets.Count())).ToList();
    SetHoldings(targets, true);
}
def _rebalance(self):
    # Get the stocks that are currently in the universe.
    securities = [self.securities[symbol] for symbol in self._universe.selected]
    # Select the 10 stocks with the greatest trailing returns.
    selected_assets = sorted([s for s in securities if s.roc.is_ready], key=lambda s: s.roc)[-10:]
    # Form an equal-weighted portfolio.
    targets = [PortfolioTarget(security.symbol, 1/len(selected_assets)) for security in selected_assets]
    self.set_holdings(targets, True)

7. Delete the OnDataon_data method that comes with the template algorithm.

Congratulations! You just wrote your first trading algorithm.

public class BasicTemplateAlgorithm : QCAlgorithm
{
    private Universe _universe;
    public override void Initialize()
    {
        SetStartDate(2020, 1, 1);
        SetEndDate(2021, 1, 1);
        SetCash(100000);
        _universe = Universe.ETF("SPY");
        AddUniverse(_universe);
        Settings.AutomaticIndicatorWarmUp = true;
        Settings.SeedInitialPrices = true;
        Schedule.On(DateRules.WeekStart("SPY"), TimeRules.At(8, 0), Rebalance);
    }

    public override void OnSecuritiesChanged(SecurityChanges changes)
    {
        foreach (dynamic security in changes.AddedSecurities)
        {
            security.Roc = ROC(security, 21, Resolution.Daily);
        }
    }

    private void Rebalance()
    {
        // Get the stocks that are currently in the universe.
        var securities = _universe.Selected.Select(symbol => Securities[symbol]);
        // Select the 10 stocks with the greatest trailing returns.
        var selectedAssets = securities.Where(s => ((dynamic)s).Roc.IsReady).OrderBy(s => ((dynamic)s).Roc).TakeLast(10);
        // Form an equal-weighted portfolio.
        var targets = selectedAssets.Select(security => new PortfolioTarget(security.Symbol, 1m / selectedAssets.Count())).ToList();
        SetHoldings(targets, true);
    }
}
from AlgorithmImports import *


class BasicTemplateAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2020, 1, 1)
        self.set_end_date(2021, 1, 1)
        self.set_cash(100000)
        self._universe = self.universe.etf('SPY')
        self.add_universe(self._universe)
        self.settings.automatic_indicator_warm_up = True
        self.settings.seed_initial_prices = True
        self.schedule.on(self.date_rules.week_start('SPY'), self.time_rules.at(8, 0), self._rebalance)

    def on_securities_changed(self, changes):
        for security in changes.added_securities:
            security.roc = self.roc(security, 21, Resolution.DAILY)

    def _rebalance(self):
        # Get the stocks that are currently in the universe.
        securities = [self.securities[symbol] for symbol in self._universe.selected]
        # Select the 10 stocks with the greatest trailing returns.
        selected_assets = sorted([s for s in securities if s.roc.is_ready], key=lambda s: s.roc)[-10:]
        # Form an equal-weighted portfolio.
        targets = [PortfolioTarget(security.symbol, 1/len(selected_assets)) for security in selected_assets]
        self.set_holdings(targets, True)

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: