EMA計算(pandas之emw函數(shù)使用及設(shè)置) pandas 指數(shù)加權(quán)滑動(ewm)在股市及其他金融領(lǐng)域中,經(jīng)常需要進行指數(shù)加權(quán)平均計算,這個指標可以較好反應指數(shù)變動的趨勢。在python 中用pandas的ewm函數(shù)可以很方便進行計算,但在使用過程中總對不上數(shù)據(jù),經(jīng)過反復實驗,終于有了一些頭緒。 在股市及其他金融領(lǐng)域中,經(jīng)常需要進行指數(shù)加權(quán)平均計算,這個指標可以較好反應指數(shù)變動的趨勢。 先看看指數(shù)移動平均值EMA的定義: 再看看這個函數(shù)的說明 參數(shù)說明 span : 類型:浮點數(shù);可選參數(shù);定義有關(guān)時間窗口的衰減參數(shù)(這個定義好了一點,但依然不好理解,簡單的說也是用來定義α的一種方式, α=2/(span+1), for span≥1.) halflife : 類型:浮點數(shù);可選參數(shù);定義半生命周期的的衰減參數(shù),太專業(yè)了,一般用的不太多,其實就是 α=1?exp(log(0.5)/halflife),for halflife>0.(公式復雜,本文不討論了) alpha : 類型:浮點數(shù);可選參數(shù);這個簡單粗暴,就是直接定義平滑因子 α, 0<α≤1. min_periods : 類型:整數(shù),默認為0,表示窗口期取數(shù)的最小數(shù)量(翻譯很拗口,有沒有更好的?原文如下:Minimum number of observations in window required to have a value (otherwise result is NA). )。 adjust : 類型:布爾, 默認為 True。決定調(diào)整因子開始期間的計算方式,英文原文不容易翻譯。 ignore_na : 類型 布爾, 默認 False,是否在加權(quán)計算中忽略Nan的值 axis : 類型 取值0 或1,分別代表是行還是列,默認為 0 返回值 為DataFrame,計算的結(jié)果 注意點: 用下面兩個式子比較直接(x表示時間序列如每日股價,y表示均值): 當 adjust=True (3)ignore_na 參數(shù)是用來表明如何處理空缺的值(Nan),當它是默認值False時,權(quán)重基于絕對位置,即不忽略Nan的值,只是不理而已,例如 the weights of x and y used in calculating the final weighted average of [x, None, y] are (1-alpha)**2 and 1 (if adjust is True), and (1-alpha)**2 and alpha (if adjust is False). (reproducing pre-0.15.0 behavior), weights are based on relative positions. For example, the weights of x and y used in calculating the final weighted average of [x, None, y] are 1-alpha and 1 (if adjust is True), and 1-alpha and alpha (if adjust is False). 看了上面的文字,依然會讓人覺得很繞,不如看幾個范例,就會比較清晰。 范例: 那么用ewm函數(shù),對應的可以用com,span,alpha參數(shù),adjust=False # #一個人至少有一個夢想,有一個理由去堅強import numpy as np import pandas as pddf=pd.DataFrame({'x':[1,2,3,4,5,6,7,8,9]}) df['y1']=df['x'].ewm(com=2,adjust=False).mean() df['y2']=df['x'].ewm(span=5,adjust=False).mean() df['y3']=df['x'].ewm(alpha=1/3.0,adjust=False).mean()print(df) 運行結(jié)果: |
|