c# - 将 RSI 从 pinescript 转换为 C#?

标签 c# finance pine-script tradingview-api

来自Trading View ,我们看到rsi可以用pinescript编写如下:

pine_rsi(x, y) => 
    u = max(x - x[1], 0) // upward change
    d = max(x[1] - x, 0) // downward change
    rs = rma(u, y) / rma(d, y)
    rsi = 100 - 100 / (1 + rs)

我用 C# 重写了这个:

public static double RelativeStrengthIndex(List<double> input, int samples)
{
    List<double> gains = new List<double>();
    List<double> losses = new List<double>();

    for (int i = input.Count - samples; i < input.Count; i++)
    {
        double change = input[i] - input[i - 1];
        gains.Add(change >= 0 ? change : 0);
        losses.Add(change < 0 ? -1 * change : 0);
    }

    double rs = RollingMovingAverage(gains, samples) / RollingMovingAverage(losses, samples);
    return 100 - 100 / (1 + rs);
}

但是,我的结果并不相同。它们的差异足以排除数据差异(交易 View 和其他提供商的数据可能略有不同)。我已经尝试解决这个问题有一段时间了,但已经完全放弃了。

有谁知道为什么我的代码会产生不同的结果?

最佳答案

我遇到了完全相同的问题,并发现 RSI 是基于 Rolling Moving Average (RMA)这是一个累积函数。对于 14 周期 RSI,您需要大约 100 个柱才能使其稳定。我必须将值放入 Excel 电子表格中才能解决这个问题并获得与 Pinescript 匹配的公式。

我最终基于此编写了自己的 C# RSI 函数并进行了测试,它得到了与 pinescript 相同的结果。基类AnalyzableBase来自Trady - 一个开源指标框架。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using HodlBot.Common.Extensions;
using Trady.Analysis;
using Trady.Analysis.Infrastructure;
using Trady.Core.Infrastructure;

namespace HodlBot.Lite.Strategy
{
    public class FastRsi<TOutput> : AnalyzableBase<IOhlcv, IOhlcv, decimal?, TOutput>
    {
        private readonly List<IOhlcv> _inputs;
        public int Period { get; }
        private List<decimal?> _rsi = new List<decimal?>();
        private int _periodMinus1;
        private List<DateTimeOffset> _dateTimes;
        private decimal _lastGain = 0;
        private decimal _lastLoss = 0;

        public FastRsi(IEnumerable<IOhlcv> inputs, int period) : base(inputs, i => i)
        {
            _inputs = inputs.ToList();
            _dateTimes = _inputs.Select(x => x.DateTime).ToList();
            Period = period;
            _rsi.Add(null);
            _periodMinus1 = period - 1;

            // RMA_Gain=((Gain*(Period-1)) + RMA_Gain[i-1])/Period
            for (int i = 1; i < _inputs.Count; i++)
            {
                decimal change = _inputs[i].Close - _inputs[i-1].Close;
                decimal gain = change > 0 ? change : 0;
                decimal loss = change < 0 ? -change : 0;
                decimal rmaGain = ((_lastGain * _periodMinus1) + gain) / period;
                decimal rmaLoss = ((_lastLoss * _periodMinus1) + loss) / period;
                decimal rs = rmaLoss == 0 ? 100 : rmaGain / rmaLoss;
                decimal rsi = 100 - (100 / (1 + rs));
                _rsi.Add(i < period ? null : (decimal?)rsi);

                _lastGain = rmaGain;
                _lastLoss = rmaLoss;
            }
        }

        public FastRsi<TOutput> AddOhlcv(IOhlcv ohlc)
        {
            _inputs.Add(ohlc);
            _dateTimes.Add(ohlc.DateTime);
            IReadOnlyList<IOhlcv> mappedInputs = _inputs;
            IReadOnlyList<DateTimeOffset> mappedDateTimes = _dateTimes;
            
            // Trady base class needs these to be able to compute a single index. 
            // TODO: Set these 
            typeof(FastRsi)
                .GetField("_mappedInputs", BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(this, mappedInputs);

            typeof(AnalyzableBase<IOhlcv, IOhlcv, decimal?, TOutput>)
                .GetField("_mappedDateTimes", BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(this, mappedDateTimes);

            int i = _mappedInputs.Count - 1;
            decimal change = i > 0 ? _mappedInputs[i].Close - _mappedInputs[i - 1].Close : 0;
            decimal gain = change > 0 ? change : 0;
            decimal loss = change < 0 ? -change : 0;
            decimal rmaGain = ((_lastGain * _periodMinus1) + gain) / Period;
            decimal rmaLoss = ((_lastLoss * _periodMinus1) + loss) / Period;
            decimal rs = rmaLoss == 0 ? 100 : rmaGain / rmaLoss;
            decimal rsi = 100 - (100 / (1 + rs));
            _rsi.Add(i < Period ? null : (decimal?)rsi);

            _lastGain = rmaGain;
            _lastLoss = rmaLoss;

            return this;
        }

        protected override decimal? ComputeByIndexImpl(IReadOnlyList<IOhlcv> mappedInputs, int index)
        {
            return _rsi[index];
        }
    }

    public class FastRsi : FastRsi<AnalyzableTick<decimal?>>
    {
        public FastRsi(IEnumerable<IOhlcv> inputs, int period) : base(inputs, period)
        {
        }
    }
}

关于 my implementation and reasoning here 还有更多内容.

关于c# - 将 RSI 从 pinescript 转换为 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66084550/

相关文章:

finance - 如何在一个脚本中绘制 MACD 和 EMA(Pine Editor)-Tradingview

pine-script - Pine脚本可以在Api外回调吗?

pine-script - 如何在 Pinescript 中绘制特定时间的最高点和最低点的水平线?

c# - 如何在C#中实现维特比算法来拆分连体词?

c# - 如何通过 HttpWebRequest 传递 API_KEY

c# - 单个 LINQ 查询中的多个求和会触发多个 SQL 查询

c# - WCF 并将代理代码移动到 DLL。是否可以?

finance - 对于金融部门的人员来说,数据存储问题

python - 如何在 Python 中使用 Selenium 获取 h1 标签

用于股票市场的 Java 模式识别 API