Overall Statistics
Total Orders
3050
Average Win
4.29%
Average Loss
-2.20%
Compounding Annual Return
82.667%
Drawdown
58.700%
Expectancy
0.159
Start Equity
100000
End Equity
3733460.6
Net Profit
3633.461%
Sharpe Ratio
1.225
Sortino Ratio
1.662
Probabilistic Sharpe Ratio
43.031%
Loss Rate
61%
Win Rate
39%
Profit-Loss Ratio
1.96
Alpha
0.767
Beta
-0.329
Annual Standard Deviation
0.606
Annual Variance
0.367
Information Ratio
1.03
Tracking Error
0.645
Treynor Ratio
-2.254
Total Fees
$371339.40
Estimated Strategy Capacity
$270000000.00
Lowest Capacity Asset
ES YTG30NVEFCW1
Portfolio Turnover
1663.12%
# region imports
from AlgorithmImports import *
# endregion


class NoiseAreaBreakoutAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2019, 5, 1)
        self.set_end_date(2025, 5, 1)
        self.set_cash(100_000)
        # Set some parameters.
        self._trading_interval_length = timedelta(minutes=30)
        self._avg_move_lookback = 14  # days
        self._target_volatility = 0.02 # 0.02 = 2%
        self._max_exposure = 4  # 4 = 400%
        # Add a universe of Futures contracts to trade.
        self._future = self.add_future(
            Futures.Indices.SP_500_E_MINI,
            data_mapping_mode=DataMappingMode.LAST_TRADING_DAY,
            data_normalization_mode=DataNormalizationMode.BACKWARDS_PANAMA_CANAL,
            contract_depth_offset=0
        )
        self._future.set_filter(0, 180)
        self._future.vwap = self.vwap(self._future.symbol)
        self._future.daily_volatility = IndicatorExtensions.of(StandardDeviation(14), self.roc(self._future.symbol, 1, Resolution.DAILY))
        self._future.avg_move_by_interval = {}
        self._future.yesterdays_close = None
        self._future.todays_open = None
        # Add a Scheduled Event to place orders 30 minutes after market open.
        date_rule = self.date_rules.every_day(self._future.symbol)
        self.schedule.on(date_rule, self.time_rules.after_market_close(self._future.symbol, 1), lambda: setattr(self._future, 'yesterdays_close', self._future.price))
        self.schedule.on(date_rule, self.time_rules.after_market_open(self._future.symbol, 1), lambda: setattr(self._future, 'todays_open', self._future.open))
        self.schedule.on(date_rule, self.time_rules.every(self._trading_interval_length), self._rebalance)
        self.schedule.on(date_rule, self.time_rules.before_market_close(self._future.symbol, 1), self.liquidate)
        # Set a warm-up period to warm-up the indicators.
        self.set_warm_up(timedelta(30))

    def _rebalance(self):
        # Wait until the market is open.
        t = self.time
        if (not self._future.yesterdays_close or
            not self._future.exchange.hours.is_open(t, False) or
            not self._future.exchange.hours.is_open(t - self._trading_interval_length, False)):
            return
        # Create an indicator for this time interval if it doesn't already exist.
        trading_interval = (t.hour, t.minute)
        if trading_interval not in self._future.avg_move_by_interval:
            self._future.avg_move_by_interval[trading_interval] = SimpleMovingAverage(self._avg_move_lookback)
        avg_move = self._future.avg_move_by_interval[trading_interval]
        # Update the average move indicator.
        move = abs(self._future.price / self._future.todays_open - 1)
        if not avg_move.update(t, move):
            return
        # Wait until the daily volatility indicator is ready.
        if not self._future.daily_volatility.is_ready or self.is_warming_up:
            return
        # Calculate the noise area.
        upper_bound = max(self._future.yesterdays_close, self._future.todays_open) * (1+avg_move.current.value)
        lower_bound = min(self._future.yesterdays_close, self._future.todays_open) * (1-avg_move.current.value)
        # Scan for entries.
        weight = min(self._max_exposure, self._target_volatility/self._future.daily_volatility.current.value) / self._max_exposure
        contract = self.securities[self._future.mapped]
        if not contract.holdings.is_long and self._future.price > upper_bound:
            self.set_holdings(contract.symbol, weight)
        elif not contract.holdings.is_short and self._future.price < lower_bound:
            self.set_holdings(contract.symbol, -weight)
        # Scan for exits.
        elif (contract.holdings.is_long and self._future.price < max(upper_bound, self._future.vwap.current.value) or
            contract.holdings.is_short and self._future.price > min(lower_bound, self._future.vwap.current.value)):
            self.liquidate()
        # Plot the current state.
        self.plot('Weight', 'value', weight)
        self.plot('Noise Area', 'Upper Bound', upper_bound)
        self.plot('Noise Area', 'Lower Bound', lower_bound)
        self.plot('Noise Area', 'Price', self._future.price)
        self.plot('Noise Area', 'VWAP', self._future.vwap.current.value)
        self.plot('Volatility', 'Future', self._future.daily_volatility.current.value)