gpt4 book ai didi

python - 将 linreg 函数从 pinescript 转换为 Python?

转载 作者:行者123 更新时间:2023-12-04 12:02:02 51 4
gpt4 key购买 nike

我正在尝试将 TradingView 指标转换为 Python(也使用 Pandas 来存储其结果)。
这是我想转换为 python 指标的指标公共(public)代码:
https://www.tradingview.com/script/sU9molfV/
我被困在创建那个松树脚本 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 specifiedover a user-defined time period. It is calculated using the leastsquares method. The result of this function is calculated using theformula: linreg = intercept + slope * (length - 1 - offset), wherelength is the y argument, offset is the z argument, intercept andslope are the values calculated with the least squares method onsource 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))
它不起作用。
任何想法如何创建一个类似的松树脚本 linereg 函数到python中,好吗?
先感谢您!

最佳答案

我使用 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()
);

关于python - 将 linreg 函数从 pinescript 转换为 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67719509/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com