在滚动bas上涂抹polyfit

2024-03-28 12:12:31 发布

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

我在polyfit上找到了一篇很有用的文章: http://www.emilkhatib.com/analyzing-trends-in-data-with-pandas/

import numpy as np
coefficients, residuals, _, _, _ = np.polyfit(range(len(selected.index)),selected,1,full=True)
mse = residuals[0]/(len(selected.index))
nrmse = np.sqrt(mse)/(selected.max() - selected.min())
print('Slope ' + str(coefficients[0]))
print('NRMSE: ' + str(nrmse))

我想在这个基础上使用。。在

^{pr2}$

但我不能让它工作:)

我明白了 索引器错误:索引0超出了大小为0的轴0的界限,而不是正确的结果:)

有人知道吗?谢谢!e

****编辑1****

抱歉,我没有贴一个具体的例子。。。 通过在df中转换numpy数组,我设法使函数正常工作。 但不知何故残差是空的

import quandl
import MySQLdb
import pandas as pd
import numpy as np
import sys
import matplotlib.pyplot as plt

def test(input_list, i):

    if sum(~np.isnan(x) for x in input_list) < 2:
        return np.NaN

    abc  = pd.DataFrame(input_list)

    coefficients, residuals, _, _, _ = np.polyfit(range(len(abc)),abc[0],1,full=True)

    #residuals is empty... why?
    a = coefficients[0]*len(abc) + coefficients[1]

    return a

df = quandl.get("WIKI/GOOGL")
df = df.ix[:, ['High', 'Low', 'Close']]


#reseit index for calc
#base1['DateTime'] = base1.index 
#base1.index = range(len(base1))

df['close_pred'] = df['Close'].rolling(window=15, min_periods=2, center=False).apply(lambda x: test(x, 0))

print(df.head(30).to_string())

Tags: importnumpydfindexlenasnprange
1条回答
网友
1楼 · 发布于 2024-03-28 12:12:31

残差为空,仅用于第一次迭代-查看少量修改的代码和答案

def test(data):

    if sum(~np.isnan(x) for x in data) < 2:
        return np.NaN

    df = pd.DataFrame(data)
    coefficients, residuals, _, _, _ = np.polyfit(range(len(data)),df[0],1,full=True)

    #if residuals.size == 0:
    #    residuals = [0] 

    print(coefficients[-2], residuals, data)

    return coefficients[-2]

然后回答

^{pr2}$

下面的简单代码修复它

if residuals.size == 0:
        residuals = [0] 

相关问题 更多 >