我试着用熊猫数据从股票的日价格中计算每月的股票收益。
数据:
permno date prc
Firm A 1995-01-02 30
Firm A 1995-01-03 30.3
...
Firm B 1996-01-03 10.1
到目前为止,我尝试的是:
df = DATA
#date columns are consisted with datestamps
df.loc[:, 'month'] = df.loc[:, 'date'].apply(lambda x : x.strftime('%Y%m'))
# **<code1>** choose first date from that month for each permno
df_ = df.sort_values('date').groupby(['permno', 'month']).first().reset_index()
# **<code2>** caclulate monthly_return by getting pct_change()
df_['monthly_return'] = df_.sort_values('month').groupby('permno').prc.pct_change()
不过,我刚发现有些证券有一段时间没有交换。
这导致了两个问题:
有什么简单的方法来处理这类数据的周期跳跃吗?
发布于 2018-09-28 08:17:33
我认为最方便的方法是放弃可能产生误导性回报的值。
首先,创建一个以天数为索引的示例数据系列:
periods = 10000
my_index = pd.date_range('2016-07-01', periods=periods, freq='D')
data = np.random.randint(100,1000,periods)
ts = pd.Series(data=data, index=my_index, name='Daily Returns')
print(ts.head())
示例系列如下:问题1:
2016-07-01 348
2016-07-02 794
2016-07-03 650
2016-07-04 365
2016-07-05 291
Freq: D, Name: Monthly Returns, dtype: int64
在开始时分配一个nan值,
ts.iloc[0]=np.nan
然后重新整理系列。‘BMS代表第一个营业日。“回填()”从前瞻偏倚中避开。
ts=ts.resample('BMS').backfill().pct_change().dropna()
在结果序列中,没有观测到第一个月和第二个月,因为没有数据来计算回报。
2016-09-01 0.257343
2016-10-03 -0.296997
2016-11-01 0.433544
2016-12-01 -0.552980
2017-01-02 -0.390123
Freq: BMS, Name: Monthly Returns, dtype: float64
问题2:插入更多nan并执行相同的操作:
ts.iloc[500:9000]=np.nan
ts=ts.resample('BMS').backfill().pct_change().dropna()
它将跳过nan月及其相关的回报。
https://stackoverflow.com/questions/52550650
复制相似问题