DAY 24
0
AI & Data

【Day24-序列】時間序列型資料的基本處理——以0050股票價格為例：尋找峰值、移動平均、曲線擬合

今日範例-0050股價資料

``````import twstock
stock = twstock.Stock("0050")
price = np.array(stock.price)
date = stock.date
plt.plot(date,price)
plt.xticks(rotation = 30)
plt.title("0050")
``````

序列資料處理技巧

尋找峰值

``````# 尋找峰值
from scipy.signal import argrelextrema
max_index = argrelextrema(price, np.greater)[0]
peak = price[max_index]
print(f"peak:{peak}")
``````
``````peak:[141.   142.55 141.95 141.6  140.5  140.   137.05 135.35]
``````
``````# 繪圖峰值
plt.plot(date,price)
plt.xticks(rotation = 30)
for index in max_index:
plt.scatter(date[index],price[index],c="r")
plt.show()
``````

移動平均

``````# 計算移動平均
series_price = pd.Series(price)
series_price_ma3 = series_price.rolling(3).mean()
series_price_ma5 = series_price.rolling(5).mean()
``````
``````# 移動平均繪圖比較
p1 = plt.plot(date,series_price)
p2 = plt.plot(date,series_price_ma3)
p3 = plt.plot(date,series_price_ma5,c="r")
plt.legend(['origin', '3 day MA', "5 day MA"])
plt.xticks(rotation = 30)
plt.title("0050")
``````

曲線擬合

``````# 取出np類型的資料
y = np.array(series_price_ma5)[4:]
x = np.array(range(len(y)))
# 用polyfit去擬合曲線
parameter=np.polyfit(x,y,10) # 以一個10次方程去擬合
parameter_fn=np.poly1d(parameter)
plt.plot(parameter_fn(x),c="r",linestyle="--")
plt.plot(x,y)
``````