尝试使用类输出列表

时间:2013-11-01 21:28:23

标签: python class

我正在尝试获取价格的移动平均线,但我在Moving_Average课程中遇到属性错误:

'Moving_Average' object has no attribute 'days'

这就是我所拥有的:

class Moving_Average:

    def calculation(self, alist:list,days:int):
        m = self.days
        prices = alist[1::2]
        average = [0]* len(prices)
        signal = ['']* len(prices)
        for m in range(0,len(prices)-days+1):
            average[m+2] = sum(prices[m:m+days])/days
            if prices[m+2] < average[m+2]:
                signal[m+2]='SELL'
            elif prices[m+2] > average[m+2] and prices[m+1] < average[m+1]:
                signal[m+2]='BUY'
            else:
                signal[m+2] =''
        return average,signal

def print_report(symbol:str,strategy:str):
        print('SYMBOL: ', symbol)
        print('STRATEGY: ', strategy)
        print('Date            Closing        Strategy        Signal')


def user():
    strategy = '''
    Which of the following strategy would you like to use?
    * Simple Moving Average [S]
    * Directional Indicator[D]

    Please enter your choice: '''

    if signal_strategy in 'Ss':
        days = input('Please enter the number of days for the average')
        days = int(days)
        strategy = 'Simple Moving Average {}-days'.format(str(days))
        m = Moving_Average()
        ma = m.calculation(gg, days)
        print(ma)

gg是一个包含日期和价格的列表。

[2013-10-01,60,2013-10-02,60]

输出看起来像:

 Date       Price      Average      Signal
2013-10-01   60.0                       
2013-10-02   60.0       60.00         BUY

1 个答案:

答案 0 :(得分:1)

您正在引用days,它是calculation函数的参数,而不是类的实例变量。您只需使用self.days

即可使用m = days来访问它