0

嗨,我有计算给定列表的移动平均线的函数。这是代码:

def calculate(self, alist, days=2):

    averages = []
    signals  = []
    prices   = [float(n) for n in alist[1::2]]
    window   = collections.deque(maxlen=days)

    for price in prices:
        window.append(price)
        averages.append(0.00)
        signals.append("")
        if len(window) == days:
            mavg = sum(window) / days
            averages[-1] = mavg
            if price < mavg:
                signals[-1] = "SELL"
            elif price > mavg:
                signals[-1] = "BUY"

    averages[:] = ("%.2f" % avg for avg in averages)

    return averages, signals

它提供以下输出:

DATE            CLOSING        INDICATOR        SIGNAL
2013-10-01      887.00         0.00                                 
2013-10-02      887.99         0.00                                 
2013-10-03      876.09         0.00                                 
2013-10-04      872.35         0.00                                 
2013-10-07      865.74         877.83           SELL                
2013-10-08      853.67         871.17           SELL

有没有办法可以从打印中删除最初的 0,以便我的输出看起来像:

DATE            CLOSING        INDICATOR        SIGNAL
2013-10-01      887.00                                         
2013-10-02      887.99                                          
2013-10-03      876.09                                          
2013-10-04      872.35                                          
2013-10-07      865.74         877.83           SELL                
2013-10-08      853.67         871.17           SELL 
4

1 回答 1

1

尝试:

def calculate(self, alist, days=2):

    # rest of your functions

    tol=0.01
    averages[:] = ("%.2f" % avg if abs(avg)>=tol else ' '  for avg in averages)

    return averages, signals
于 2013-11-08T22:11:33.617 回答