我需要将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
(整数)长度(后杠的数量)。
使用熊猫确实是最好的选择,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()