Converting a Trading Algorithm to Emit Directional Insights
Summary
This demonstration shows how to adapt a conventional trading algorithm to a framework that uses directional insights. It applies daily MACD to SPY and compares the MACD line with its signal line using a tolerance. When the normalized difference exceeds the positive or negative threshold, the algorithm emits an up or down insight before setting its holdings long or short. A flat insight and liquidation are shown as an optional pattern.
The example also illustrates waiting until the indicator is ready and valid security data is available, then plotting the MACD components and price. It specifies a historical date range and daily resolution, but provides no reported backtest results or evidence that the signals are profitable. The example teaches framework integration and signal sequencing rather than a validated standalone strategy; it does not detail transaction costs, risk controls, or how the threshold and prediction horizon were selected.
Key ideas
- The example pairs each long or short order with a directional insight for the same security.
- It emits the insight before changing portfolio holdings.
- A normalized MACD-to-signal difference and tolerance determine whether the signal points up or down.
- The algorithm waits for indicator readiness and usable market data before acting.
- The source illustrates integration mechanics but reports no trading performance.
Tags
Full text
# ConvertToFrameworkAlgorithm
# ConvertToFrameworkAlgorithm
Demonstration algorithm showing how to easily convert an old algorithm into the framework.
Demonstration algorithm showing how to easily convert an old algorithm into the framework. ### 1. When making orders, also create insights for the correct direction (up/down/flat), can also set insight prediction period/magnitude/direction 2. Emit insights before placing any trades 3. Profit :)
## Source (Apache-2.0)
```python
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from AlgorithmImports import *
### <summary>
### Demonstration algorithm showing how to easily convert an old algorithm into the framework.
###
### 1. When making orders, also create insights for the correct direction (up/down/flat), can also set insight prediction period/magnitude/direction
### 2. Emit insights before placing any trades
### 3. Profit :)
### </summary>
### <meta name="tag" content="indicators" />
### <meta name="tag" content="indicator classes" />
### <meta name="tag" content="plotting indicators" />
class ConvertToFrameworkAlgorithm(QCAlgorithm):
'''Demonstration algorithm showing how to easily convert an old algorithm into the framework.'''
fast_ema_period = 12
slow_ema_period = 26
def initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2004, 1, 1)
self.set_end_date(2015, 1, 1)
self._symbol = self.add_security(SecurityType.EQUITY, 'SPY', Resolution.DAILY).symbol
# define our daily macd(12,26) with a 9 day signal
self._macd = self.macd(self._symbol, self.fast_ema_period, self.slow_ema_period, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)
def on_data(self, data):
'''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Args:
data: Slice object with your stock data'''
# wait for our indicator to be ready
if not self._macd.is_ready or not data.contains_key(self._symbol) or data[self._symbol] is None: return
holding = self.portfolio[self._symbol]
signal_delta_percent = float(self._macd.current.value - self._macd.signal.current.value) / float(self._macd.fast.current.value)
tolerance = 0.0025
# if our macd is greater than our signal, then let's go long
if holding.quantity <= 0 and signal_delta_percent > tolerance:
# 1. Call emit_insights with insights created in correct direction, here we're going long
# The emit_insights method can accept multiple insights separated by commas
self.emit_insights(
# Creates an insight for our symbol, predicting that it will move up within the fast ema period number of days
Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.UP)
)
# longterm says buy as well
self.set_holdings(self._symbol, 1)
# if our macd is less than our signal, then let's go short
elif holding.quantity >= 0 and signal_delta_percent < -tolerance:
# 1. Call emit_insights with insights created in correct direction, here we're going short
# The emit_insights method can accept multiple insights separated by commas
self.emit_insights(
# Creates an insight for our symbol, predicting that it will move down within the fast ema period number of days
Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.DOWN)
)
self.set_holdings(self._symbol, -1)
# if we wanted to liquidate our positions
## 1. Call emit_insights with insights create in the correct direction -- Flat
#self.emit_insights(
# Creates an insight for our symbol, predicting that it will move down or up within the fast ema period number of days, depending on our current position
# Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.FLAT)
#)
# self.liquidate()
# plot both lines
self.plot("MACD", self._macd, self._macd.signal)
self.plot(self._symbol.value, self._macd.fast, self._macd.slow)
self.plot(self._symbol.value, "Open", data[self._symbol].open)
```Shown in full with attribution under the source's licence. Licence: Apache-2.0
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.