Python simple moving average class based -


OK, so I'm writing a class that will calculate the simple running average on the list of prices. It calculates the average N-day calculation with the first N-1 day that is what I have:

  class SimplemovingAverage (): def __init __ (self, nday, list_of_prices ): Self._Nday = Nday self._list_of_prices = list_of_prices Def def (self): Category (lane (self._list_of_prices)): If i & lt; Self._Nday: average = 0 alif I == self. _ Day: average = sum (self._l_l_l_production [: self ._d day]) / self ._ if other: average = sum (self. _l__st_prosus [i-self._Nday: i]) / itself ._day print (average) / Code>  

I tested it by creating a square object on the shell 'x = SimplemovingAverage (3, [1,2,3,4, 5,6,7,8,9,10 ] ' and then the output I received was calculated by' x.calculate 'method:

  0 0 2.0 3.0 4.0 5.0 6.0 7.0 8.0  < / Pre> 

then it can be calculated from the list of numbers to 7,8,9, the last number Class 9 must be because it 8 9 average of 10 and it should be N only 3 minus 3 post. This is the output I'm looking for:

  0,0 3.0 3.0 5.0 6.0 7.0 8.0 9.0  

OK, here's a clean up:

  class SimplemovingAverage (): def __init __ (self, shipping, item): Self. Navg = navg self.items = item df calculation (self): av = [] for category (lane (self.items)): if i + 1 & lt; Self.navg: av.append (0) Other: av.append (zodiac (images themselves [i + 1-self.navg: i + 1]) / self.navg Return  

i + 1 everywhere, because category returns 0 ... navg-1 instead of 1 ... navg (you can also do category (1, n + 1) .)

Second, you do not need a special case I + 1 == self. Navg (: m is same 0: m ).

Third, it

Fourth, there is no real reason, a list instead of printing the result To make more sense to return (though I like the idea of ​​the other respondent to use the yield to like it). To hide the number and the list, I used to underscore (Python is not Java or C ++!).

Finally, this is more common than "list of values" is the number of "days", so I have more parameters Has changed its name.


Comments

Popular posts from this blog

eclipse plugin - Run java code error: Workspace is closed -

ios - How do I use CFArrayRef in Swift? -

scala - Play Framework - how to bind form to a session field -