【问题标题】:Adding a column (EMA) thats result of previous new column value in pandas添加一列(EMA),这是熊猫中先前新列值的结果
【发布时间】:2016-11-24 09:19:02
【问题描述】:

我的原始数据框是这样的:

Date   C
0      a
1      b
2      c 
3      d

这是一个股票数据。 0,1,2,3 是时间,C:Close 是浮点数。

我需要能够将 EMA(指数移动平均)列添加到通过从当前列 C 计算获得的原始数据帧中 以及之前的新列 ('EMA')。

Calculation example on Excel

Cr:http://investexcel.net/how-to-calculate-ema-in-excel/

所以结果应该是这样的

       C   EMA
0      a  start value as ema0
1      b  (ema0*alpha) + (b * (1-alpha)) as ema1
2      c  (ema1*alpha) + (c * (1-alpha)) as ema2
3      d  (ema2*alpha) + (d * (1-alpha)) as ema3 
4      e  (ema3*alpha) + (e * (1-alpha)) as ema4
...    ... ....

起始值将是一个简单的平均值,所以我尝试了以下方法。 创造起始价值的第一个条件 但在计算 EMA 值时,它不适用于第二个条件。

ema_period = 30
myalpha = 2/(ema_period+1)

data['EMA'] = np.where(data['index'] < ema_period,data['C'].rolling(window=ema_period, min_periods=ema_period).mean(), data['C']*myalpha +data['EMA'].shift(1)*(1-myalpha) )

【问题讨论】:

  • C 未用于您的 EMA 值定义。这正常吗?
  • 非常感谢。你是对的,我已经更正了结果表。

标签: python pandas


【解决方案1】:

随附图片中的必需 EWMA:

代码:

ema_period = 12             # change it to ema_period = 30 for your case
myalpha = 2/(ema_period+1)

# concise form : df.expanding(min_periods=12).mean()
df['Expand_Mean'] = df.rolling(window=len(df), min_periods=ema_period).mean()
# obtain the very first index after nulls
idx = df['Expand_Mean'].first_valid_index()
# Make all the subsequent values after this index equal to NaN
df.loc[idx:, 'Expand_Mean'].iloc[1:] = np.NaN
# Let these rows now take the corresponding values in the Close column
df.loc[idx:, 'Expand_Mean'] = df['Expand_Mean'].combine_first(df['Close'])
# Perform EMA by turning off adjustment
df['12 Day EMA'] = df['Expand_Mean'].ewm(alpha=myalpha, adjust=False).mean()
df

获得 EWMA:


DF 构造:

index = ['1/2/2013','1/3/2013','1/4/2013','1/7/2013','1/8/2013','1/9/2013', '1/10/2013','1/11/2013',
         '1/14/2013','1/15/2013','1/16/2013','1/17/2013','1/18/2013','1/22/2013','1/23/2013',
         '1/24/2013','1/25/2013','1/28/2013','1/29/2013','1/30/2013']
data = [42.42, 43.27, 43.66, 43.4, 43.4, 44.27, 45.01, 44.48, 44.34, 
        44.44, 44.08, 44.16, 44.04, 43.74, 44.27, 44.11, 43.93, 44.35,
        45.21,44.92]

df = pd.DataFrame(dict(Close=data), index)
df.index = pd.to_datetime(df.index)

【讨论】:

  • 感谢您的帮助。这可以精确地计算出 excel 的值。
【解决方案2】:

由于您正在处理时间序列,因此建议您采用信号处理方法。使用scipy.signal.lfilter 所提供的here

按如下操作:

df = # Your dataframe
start_value, alpha, weight = # initialize your parameters

# Use a filtering method to generate values
df['EMA'] = lfilter([1-alpha], [1.0, -alpha], df['C'].astype(float))

【讨论】:

  • 但是这里的起始值是C列的第一个值。您可以对其进行调整以将C 列的第一个值更改为“start_value=ema_0”并应用过滤器
猜你喜欢
  • 2014-06-02
  • 2023-01-20
  • 2015-09-19
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 2022-01-26
  • 2016-11-03
  • 2018-07-17
相关资源
最近更新 更多