基于Python简单移动平均类

2024-10-01 07:14:13 发布

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

好的,我正在写一个类,它将计算价格列表上的简单移动平均值。它计算每N个数字的平均价格,不计算前N-1天。这就是我所拥有的:

class Simplemovingaverage():
    def __init__(self, Nday, list_of_prices):
        self._Nday = Nday
        self._list_of_prices = list_of_prices

    def calculate(self):
        for i in range(len(self._list_of_prices)):
            if i < self._Nday:
                average = 0
            elif i == self._Nday:
                average = sum(self._list_of_prices[:self._Nday])/self._Nday
            else:
                average = sum(self._list_of_prices[i-self._Nday:i])/self._Nday
            print(average)

我在shell 'x = Simplemovingaverage(3, [1,2,3,4,5,6,7,8,9,10])'上创建一个class对象,然后通过“x.calculate”执行calculate方法,得到的输出是:

^{pr2}$

所以从我的数字列表来看,它只能计算到7,8,9,9,最后一个数字应该是9,因为这是8,9,10的平均值,而且因为N是3,所以应该只有3个0。这是我要查找的输出:

0
0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0

Tags: ofself列表def价格数字listclass
3条回答

好的,这里是清理:

class Simplemovingaverage():
    def __init__(self, navg, items):
        self.navg = navg
        self.items = items

    def calculate(self):
        av = []
        for i in range(len(self.items)):
            if i+1 < self.navg:
                av.append(0)
            else:
                av.append(sum(self.items[i+1-self.navg:i+1])/self.navg)
        return av

首先,您需要在任何地方使用i+1,因为range给出的是{},而不是{}(也可以使用range(1, n+1))。在

其次,您不需要使用特殊情况i+1==self.navg:m与{}相同)。在

第三,返回一个列表比打印结果更有意义(尽管我喜欢另一个应答者使用yield使其成为生成器的想法!)在

第四,没有真正的理由隐藏数字和列表,所以我删除了下划线(python不是java或c++!)。在

最后,这比某个“天数”内平均的“价格列表”更一般,因此为了更一般性,我重新命名了参数。在

def sma_calc(prices_list, window_size):
    return sum(prices_list[-window_size:]) / window_size
from __future__ import division
from itertools import islice, tee

def moving_average(n, iterable):
    # leading 0s
    for i in range(1, n):
        yield 0.

    # actual averages
    head, tail = tee(iterable)
    sum_ = float(sum(islice(head, n)))
    while True:
        yield sum_ / n
        sum_ += next(head) - next(tail)

当运行为

^{pr2}$

退货

[0.0, 0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

(以N-1开头的0,意味着输出列表与输入列表具有相同的基数,我认为这正是您真正想要的)。在

相关问题 更多 >