Pinescript关联(source_a,source_b,长度)->与python

问题描述 投票:0回答:1

我需要将pine关联函数转换为python的帮助,我已经转换了stdev和swma函数,但这对我来说有点令人困惑。

我也找到了这种解释,但不太了解如何实现:

在python中,尝试将pandas.rolling(window).corr一起使用,其中window为相关系数周期pandas允许您计算任何使用rolling()进行滚动统计。相关系数来自松树的计算公式为:sma(y*x,length) - sma(y,length)*sma(x,length)除以stdev(length*y,length)*stdev(length*x,length)其中stdev基于天真的算法。

此功能的松散文档:

> Correlation coefficient. Describes the degree to which two series tend
> to deviate from their sma values. correlation(source_a, source_b,
> length) → series[float] RETURNS Correlation coefficient.

ARGUMENTS

[source_a(系列)源系列。

[source_b(系列)目标系列。

[length(整数)长度(后杠的数量)。

python data-analysis pine-script algorithmic-trading
1个回答
0
投票

使用熊猫确实是最好的选择,TA-Lib也具有CORREL功能。为了让您更好地了解如何在pine中实现correlation函数,这里是一个使用numpy的python代码,请注意,这不是有效的解决方案。

import numpy as np
from matplotlib import pyplot as plt

def sma(src,m):
    coef = np.ones(m)/m
    return np.convolve(src,coef,mode="valid")

def stdev(src,m):
    a = sma(src*src,m)
    b = np.power(sma(src,m),2)
    return np.sqrt(a-b)

def correlation(x,y,m):
    cov = sma(x*y,m) - sma(x,m)*sma(y,m)
    den = stdev(x,m)*stdev(y,m)
    return cov/den

ts = np.random.normal(size=500).cumsum()
n = np.linspace(0,1,len(ts))
cor = correlation(ts,n,14)

plt.subplot(2,1,1)
plt.plot(ts)
plt.subplot(2,1,2)
plt.plot(cor)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.