程序员的量化交易(34)--QuantConnect_Lean如何定义Indicator指标2

简介:


指标(Indicator)由三大关键组件组成:
1. 实现你指标的类
2. 在ACAlgorithm基类中的Helper方法,用于简化对你指标实现的调用。
3. 测试方法用于测试指标的表现。
为了实现一个指标,上述所有组件需要实现。下面的教程会带你浏览这些组件。我们将会使用  AroonOscillator作为案例。我们不会去介绍指标的基本概念。

1. 实现你的指标(Implementing Your Indicator)

你的指标类应该在工程根下的QuantConnect.Indicators项目下实现。它必须是一个单独的类,不能缩写,名如“AroonOscillator.cs”。
第一步
指标必须是下面指标基类的一个派生:
Indicator – 如果你的指标只需要单个值(例如ExponontialMovingAverage),你就可以用Indicator作为基类。
TradeBarIndicator – 如果你的指标需要用到TradeBars,那么你的指标必须是由TradeBarIndicator类扩展而来的。(例如AroonOscillator)。
WindowIndicator - 如果你的指标需要一个rolling window of data(数据的滚动窗口),那么你就要继承这个类。(例如Minimum)。


所有的指标都必须实现下面四个组件,为了在Lean中正常运作。
Constructor – 实现你的构造函数,用于接收和保存必要的指标配置信息。例如Aroon指标需要Aroon Up 和 Aroon Down值。
IsReady – 它是一个Boolean值,用于指示算法是否有了充足的历史价格数据用于算出指标的值。Aroon只有当有了n个周期的样本数据后才能开始计算。
ComputeNextValue()- 用提供的数据,计算和返回下一个指标的值。这里是你实现指标具体算法的地方。
保持可扩展性
Aroon作为案例是非常有代表性的,它有多个属性,Aroon-Up和Aroon-Down。这两个值在计算Aroon的时候都需要用到,但只有delta(up – down)会返回。这个例子中的dela叫做Aroon Percentage(比例)。许多指标会有一个主值(Primary value),多个属性,用于交易决策。


为了处理这些情况-每个属性都应该作为子指标(sub-indicator)。你可以查看下AroonOscillator.cs的源码。Aroon创建了AroonUp,AroonDown指标作为属性。这使得你可以单独的使用这些子指标。
例如下面的代码:
var smaAroonUp = sma.Of( aroon.AroonUp )
就直接用属性(子指标)。


现在我们贴出AroonOscillator的代码:

using QuantConnect.Data.Market;


namespace QuantConnect.Indicators
{
    /// 
    /// The Aroon Oscillator is the difference between AroonUp and AroonDown. The value of this
    /// indicator fluctuats between -100 and +100. An upward trend bias is present when the oscillator
    /// is positive, and a negative trend bias is present when the oscillator is negative. AroonUp/Down
    /// values over 75 identify strong trends in their respective direction.
    /// 
    public class AroonOscillator : TradeBarIndicator
    {
        /// 
        /// Gets the AroonUp indicator
        /// 
        public IndicatorBase AroonUp { get; private set; }


        /// 
        /// Gets the AroonDown indicator
        /// 
        public IndicatorBase AroonDown { get; private set; }


        /// 
        /// Gets a flag indicating when this indicator is ready and fully initialized
        /// 
        public override bool IsReady
        {
            get { return AroonUp.IsReady && AroonDown.IsReady; }
        }


        /// 
        /// Creates a new AroonOscillator from the specified up/down periods.
        /// 
        /// 
The lookback period to determine the highest high for the AroonDown /// The lookback period to determine the lowest low for the AroonUp public AroonOscillator(int upPeriod, int downPeriod) : this(string.Format("AROON({0},{1})", upPeriod, downPeriod), upPeriod, downPeriod) { } /// /// Creates a new AroonOscillator from the specified up/down periods. /// /// The name of this indicator /// The lookback period to determine the highest high for the AroonDown /// The lookback period to determine the lowest low for the AroonUp public AroonOscillator(string name, int upPeriod, int downPeriod) : base(name) { var max = new Maximum(name + "_Max", upPeriod + 1); AroonUp = new FunctionalIndicator(name + "_AroonUp", input => ComputeAroonUp(upPeriod, max, input), aroonUp => max.IsReady, () => max.Reset() ); var min = new Minimum(name + "_Min", downPeriod + 1); AroonDown = new FunctionalIndicator(name + "_AroonDown", input => ComputeAroonDown(downPeriod, min, input), aroonDown => min.IsReady, () => min.Reset() ); } /// /// Computes the next value of this indicator from the given state /// /// The input given to the indicator /// A new value for this indicator protected override decimal ComputeNextValue(TradeBar input) { AroonUp.Update(input.Time, input.High); AroonDown.Update(input.Time, input.Low); return AroonUp - AroonDown; } /// /// AroonUp = 100 * (period - {periods since max})/period /// /// The AroonUp period /// A Maximum indicator used to compute periods since max /// The next input data /// The AroonUp value private static decimal ComputeAroonUp(int upPeriod, Maximum max, IndicatorDataPoint input) { max.Update(input); return 100m * (upPeriod - max.PeriodsSinceMaximum) / upPeriod; } /// /// AroonDown = 100 * (period - {periods since min})/period /// /// The AroonDown period /// A Minimum indicator used to compute periods since min /// The next input data /// The AroonDown value private static decimal ComputeAroonDown(int downPeriod, Minimum min, IndicatorDataPoint input) { min.Update(input); return 100m * (downPeriod - min.PeriodsSinceMinimum) / downPeriod; } /// /// Resets this indicator and both sub-indicators (AroonUp and AroonDown) /// public override void Reset() { AroonUp.Reset(); AroonDown.Reset(); base.Reset(); } } }


2 在QCAlgorithm中安装Helper方法

在你实现了indicator(指标)之后,i需要将它安装到基类中。指标可以手工的创建和更新,不过我们加你使用helper方法,这样后面使用起来会简单很多。
在Aroon的案例中,实现是在AroonOscillator类,但它的helper方法是在QCAlgorithm中。这个helper方法—AROON—总是是大写的,总是返回一个指标实现类的实例对象。
public AroonOscillator AROON(string symbol, int upPeriod, int downPeriod, Resolution? resolution = null)  {
      var name = CreateIndicatorName(symbol, string.Format("AROON({0},{1})", upPeriod, downPeriod), resolution);
      var aroon = new AroonOscillator(name, upPeriod, downPeriod);
      RegisterIndicator(symbol, aroon, resolution);
      return aroon;
}



在helper方法中,你需要创建你指标的一个唯一的名字,使用你指标实现类的构造函数去构造一个指标实例,将其注册(注册后意味着指标的值会随着symbol(指定证券)的价格数据变动而自动的变动)。

3 创建测试方法

3.1 准备测试数据

 将准备好的测试数据放到QuantConnect.Tests\TestData目录下。

3.2 写测试类

在QuantConnect.Tests\Indicators下面。可以拷贝已经有的进行改写。

using System;
using NUnit.Framework;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;

namespace QuantConnect.Tests.Indicators
{
    [TestFixture]
    public class AroonOscillatorTests
    {
        [Test]
        public void ComparesWithExternalData()
        {
            var aroon = new AroonOscillator(14, 14);
            TestHelper.TestIndicator(aroon, "spy_aroon_oscillator.txt", "Aroon Oscillator 14",
                (i, expected) => Assert.AreEqual(expected, (double)aroon.Current.Value, 1e-3));
        }

        [Test]
        public void ResetsProperly()
        {
            var aroon = new AroonOscillator(3, 3);
            aroon.Update(new TradeBar
            {
                Symbol = "SPY",
                Time = DateTime.Today,
                Open = 3m,
                High = 7m,
                Low = 2m,
                Close = 5m,
                Volume = 10
            });
            aroon.Update(new TradeBar
            {
                Symbol = "SPY",
                Time = DateTime.Today.AddSeconds(1),
                Open = 3m,
                High = 7m,
                Low = 2m,
                Close = 5m,
                Volume = 10
            });
            aroon.Update(new TradeBar
            {
                Symbol = "SPY",
                Time = DateTime.Today.AddSeconds(2),
                Open = 3m,
                High = 7m,
                Low = 2m,
                Close = 5m,
                Volume = 10
            });
            Assert.IsFalse(aroon.IsReady);
            aroon.Update(new TradeBar
            {
                Symbol = "SPY",
                Time = DateTime.Today.AddSeconds(3),
                Open = 3m,
                High = 7m,
                Low = 2m,
                Close = 5m,
                Volume = 10
            });
            Assert.IsTrue(aroon.IsReady);

            aroon.Reset();
            TestHelper.AssertIndicatorIsInDefaultState(aroon);
            TestHelper.AssertIndicatorIsInDefaultState(aroon.AroonUp);
            TestHelper.AssertIndicatorIsInDefaultState(aroon.AroonDown);
        }
    }
}


相关文章
|
存储 算法 API
【Qt 基本类】QDateTime类在C++中的应用与深度解析
【Qt 基本类】QDateTime类在C++中的应用与深度解析
1444 0
|
应用服务中间件 nginx 网络协议
|
Linux
centos7 如何处理 libQt5Widgets.so.5 问题
今天一同事发过来一个报错信息,提示如下:error while loading shared libraries: libQt5Widgets.so.5: cannot open shared object file: No such file or directory查了几个博客分享...
6186 0
|
9月前
|
Cloud Native Java 大数据
Java:三十载长青的编程语言,从入门到进阶的全维度解析
在全球编程语言的发展长河中,Java 无疑是最具生命力的存在之一。自 1995 年由 Sun Microsystems 发布以来,它历经互联网萌芽、移动互联网爆发、云原生时代崛起等多个技术周期,始终稳居 TIOBE 编程语言排行榜前列,成为企业级开发、大数据、安卓应用、云计算等领域的核心技术基石。
1617 1
|
JSON API 开发工具
快手平台根据关键词获取视频列表的 API 接口详解
本文介绍如何利用快手开放平台API,通过关键词搜索短视频。涵盖接口调用、参数配置、分页处理及响应解析,助开发者实现视频数据获取,适用于内容推荐、热点分析等场景,需注意权限、限流与数据合规。
2624 0
|
监控 算法 数据挖掘
项目介绍:RQAlpha量化框架
RQAlpha是Python算法回测与交易框架,支持多证券类型,提供数据获取、策略开发、回测、实盘模拟及数据分析等全套解决方案,具备灵活配置、易用性及强大扩展性。
项目介绍:RQAlpha量化框架
|
前端开发 数据库 对象存储
基于RuoYi-Flowable-Plus的若依ruoyi-nbcio支持本地图片上传与回显的功能实现(一)
基于RuoYi-Flowable-Plus的若依ruoyi-nbcio支持本地图片上传与回显的功能实现(一)
1804 0
|
人工智能 JSON 物联网
基于 PAI-ArtLab 使用 ComfyUI 搭建对话式 AI 女友
本实验介绍了一款名为“AI虚拟女友——胡桃”的应用,通过ComfyUI后端与WebUI展示效果,结合LLM节点和知识图谱工具包(KG),实现角色人设稳定及长期记忆功能。用户可通过输入信息与AI互动,并自定义人设知识图谱和角色LoRA。操作步骤包括登录PAI ArtLab平台、加载工作流文件、配置角色参数并与AI对话。此外,还提供了Graph RAG技术详解及常见问题解答,帮助用户更好地理解和使用该系统。
|
C# UED SEO
C# 异步方法async / await任务超时处理
通过使用 `Task.WhenAny`和 `Task.Delay`方法,您可以在C#中有效地实现异步任务的超时处理机制。这种方法允许您在指定时间内等待任务完成,并在任务超时时采取适当的措施,如抛出异常或执行备用操作。希望本文提供的详细解释和代码示例能帮助您在实际项目中更好地处理异步任务超时问题,提升应用程序的可靠性和用户体验。
948 3
|
Java Linux Android开发
java出现no XXX in java.library.path的解决办法及eclipse配置
java一般使用两个path:classpath 和 java.library.path classpath是指向jar包的位置 java.library.path是非java类包的位置如(dll,so) 解决办法: 1:LINUX下的系统变量LD_LIBRARY_PATH来添加java.
3629 0