将linreg函数从pinescript转换为Python?

2024-04-16 13:40:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将TradingView指示器转换为Python(也使用pandas存储其结果)

这是我想转换为python指示符的指示符公共代码:

https://www.tradingview.com/script/sU9molfV/

我一直在创建pine脚本linereg默认函数

这是我遇到问题的pinescript指示器的片段:

lrc = linreg(src, length, 0)
lrc1 = linreg(src,length,1)
lrs = (lrc-lrc1)
TSF = linreg(src, length, 0)+lrs

这是它的文件:

Linear regression curve. A line that best fits the prices specified over a user-defined time period. It is calculated using the least squares method. The result of this function is calculated using the formula: linreg = intercept + slope * (length - 1 - offset), where length is the y argument, offset is the z argument, intercept and slope are the values calculated with the least squares method on source series (x argument). linreg(source, length, offset) → series[float]

资料来源:

https://www.tradingview.com/pine-script-reference/#fun_linreg

我找到了这段mql4代码,并尝试一步一步地遵循它来转换它,最后在Python中创建一个函数linreg,以便进一步使用它来构建pine脚本指示符:

https://www.mql5.com/en/code/8016

这是我到目前为止的代码:

# calculate linear regression:
# https://www.mql5.com/en/code/8016
barsToCount = 14
# sumy+=Close[i];
df['sumy'] = df['Close'].rolling(window=barsToCount).mean()

# sumxy+=Close[i]*i;
tmp = []
sumxy_lst = []
for window in df['Close'].rolling(window=barsToCount):
    for index in range(len(window)):
        tmp.append(window[index] * index)
    sumxy_lst.append(sum(tmp))
    del tmp[:]
df.loc[:,'sumxy'] = sumxy_lst
# sumx+=i;
sumx = 0
for i in range(barsToCount):
    sumx += i
# sumx2+=i*i;
sumx2 = 0
for i in range(barsToCount):
    sumx2 += i * i
# c=sumx2*barsToCount-sumx*sumx;
c = sumx2*barsToCount - sumx*sumx
# Line equation:
# b=(sumxy*barsToCount-sumx*sumy)/c;
df['b'] = ((df['sumxy']*barsToCount)-(sumx*df['sumy']))/c
# a=(sumy-sumx*b)/barsToCount;
df['a'] = (df['sumy']-sumx*df['b'])/barsToCount
# Linear regression line in buffer:
df['LR_line'] = 0.0
for x in range(barsToCount):
    # LR_line[x]=a+b*x;
    df['LR_line'].iloc[x] = df['a'].iloc[x] + df['b'].iloc[x] * x
    # print(x, df['a'].iloc[x], df['b'].iloc[x], df['b'].iloc[x]*x)
print(df.tail(50))
print(list(df))

它不起作用

你知道如何在python中创建类似的pine脚本linereg函数吗

提前谢谢你


Tags: theinhttpsdfforlinewindowlength
1条回答
网友
1楼 · 发布于 2024-04-16 13:40:13

我使用talib计算收盘价的斜率和截距,然后意识到talib也提供了完整的计算。结果看起来与TradingView相同(只是目测)

在jupyterlab中执行了以下操作:

import pandas as pd
import numpy as np
import talib as tl
from pandas_datareader import data
%run "../../plt_setup.py"

asset = data.DataReader('^AXJO', 'yahoo', start='1/1/2015')

n = 270
(asset
 .assign(linreg = tl.LINEARREG(asset.Close, n))
 [['Close', 'linreg']]
 .dropna()
 .loc['2019-01-01':]
 .plot()
);

相关问题 更多 >