[英]How could I use the definition of Moving Average, write Python code (using for loops) to calculate an n-period moving average list, called ma?
MAn(t) = (Pt + Pt-1 + ... + Pt-(n-1)) / n
價格:(列出)用於獲取移動平均線的價格數據
n : (int) 定義移動平均滯后的數字(例如 252)
ma :(列出)長度為 N 的移動平均數據,其中前 (n-1) 個值為 None
def ma(n):
i=0
ma=[]
if i < n - 1:
ma.append("None" * (n-1-i))
while i < len(prices) - n + 1:
nn = prices[i:i+n]
n_average = sum(nn)/n
ma.append(n_average)
i=i+1
import numpy as np
def moving_average(x, n, centered=True):
# prepare input
x = np.array(x, dtype=np.float64)
L = len(x)
assert L >= n
# prepare output variable
result = np.zeros_like(x)
result[:n-1] = np.nan
# moving average:
result[n-1:] = sum([x[n-i-1:L-i] for i in range(n)]) / n
if centered:
result = np.hstack((result[n//2:], result[:n//2]))
return result
if __name__ == "__main__":
print(moving_average([1, 2, 3], 1))
print(moving_average([1, 2, 3], 2))
print(moving_average([1, 2, 3], 3))
try:
print(moving_average([1, 2, 3], 4))
except AssertionError:
print("Rightly failed...")
來自我的數據倉庫:https ://github.com/ChaoticRoman/numpy_scipy_matplotlib_workshop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.