2015-04-21-金融和经济数据应用(1)-数据规整化方面的话题

--
cd L:\czz
import pandas as pd
import numpy as np
from pandas import DataFrame,Series
-----------------------------------------------------------------------------------------
-----(一)、数据规整化方面的话题
-----1.时间序列以及截面对齐
prices=pd.read_csv(r'ch11\prices1.csv',index_col='Dt')
prices
volume=pd.read_csv(r'ch11\volume1.csv',index_col='Dt')
volume


#自动数据对齐
prices*volume
vwap=(prices*volume).sum()/volume.sum()
vwap
vwap.dropna()
#手动数据对齐
prices.align(volume,join='inner')
#通过一组索引可能不同的Series构建一个DataFrame
s1=Series(range(3),index=['a','b','c'])
s2=Series(range(4),index=['d','b','c','e'])
s3=Series(range(3),index=['f','a','c'])s
DataFrame({'one':s1,'two':s2,'three':s3})
#显示定义结果的索引
DataFrame({'one':s1,'two':s2,'three':s3},index=list('face'))


-----2.频率不同的时间序列的运算
ts1=Series(np.random.randn(3),index=pd.date_range('2012-6-13',periods=3,freq='W-WED'))
#重采样到工作日
ts1.resample('B')
#填充空值
ts1.resample('B',fill_method='ffill')


#各时间点更一般化
dates=pd.DatetimeIndex(['2012-6-12','2012-6-17','2012-6-18','2012-6-21','2012-6-22','2012-6-29'])
ts2=Series(np.random.randn(6),index=dates)
ts2
ts1.reindex(ts2.index,method='ffill')
ts2+ts1.reindex(ts2.index,method='ffill')


#使用Period
gdp=Series([1.78,1.94,2.08,2.01,2.15,2.31,2.46],
index=pd.period_range('1984Q2',periods=7,freq='Q-SEP'))
infl=Series([0.025,0.045,0.037,0.04],
index=pd.period_range('1982',periods=4,freq='A-DEC')
)
gdp
infl
infl_q=infl.asfreq('Q-SEP',how='end')
infl_q
infl_q.reindex(gdp.index,method='ffill')


-----3.时间和"最当前"数据选取
#生成一个交易日内的日期范围和时间序列
rng=pd.date_range('2012-06-01 09:30','2012-06-01 15:59',freq='T')
#生成5天的时间点
rng=rng.append([rng+pd.offsets.BDay(i) for i in range(1,4)])
ts=Series(np.arange(len(rng),dtype=float),index=rng)
ts


from datetime import time
ts[time(10,0)]    
ts.at_time(time(10,0))    
ts.between_time(time(10,0),time(10,1))


#将该时间序列的大部分内容随即设置为NA
indexer=np.sort(np.random.permutation(len(ts))[700:])
irr_ts=ts.copy()
irr_ts[indexer]=np.nan
irr_ts['2012-06-06 09:50':'2012-06-06 11:00']
#得到之前最近的有效值
selection=pd.date_range('2012-06-01 10:00',periods=4,freq='B')
irr_ts.asof(selection)


-----4.拼接多个数据源
#在一个特定的时间上,从一个数据源切换到另一个数据源
data1=DataFrame(np.ones((6,3),dtype=float),columns=['a','b','c'],index=pd.date_range('6/12/2012',periods=6))
data2=DataFrame(np.ones((6,3),dtype=float)*2,columns=['a','b','c'],index=pd.date_range('6/13/2012',periods=6))
spliced=pd.concat([data1.ix[:'2012-6-14'],data2.ix['2012-06-15':]])


#缺失某一列
data2=DataFrame(np.ones((6,4),dtype=float)*2,columns=['a','b','c','d'],index=pd.date_range('6/13/2012',periods=6))
spliced=pd.concat([data1.ix[:'2012-6-14'],data2.ix['2012-06-15':]])
spliced
##引入合并之前的数据
spliced_filled=spliced.combine_first(data2)
spliced_filled
#DataFrame的update方法,只填充空值
spliced.update(data2,overwrite=False)
spliced
#利用DataFrame的索引机制
cp_spliced=spliced.copy()
cp_spliced[['a','c']]=data1[['a','c']]
cp_spliced


-----5.收益指数和累计收益
import pandas.io.data as web
price=web.get_data_yahoo('AAPL','2011-01-01')['Adj Close']
price[-5:]


price['2011-10-03']/price['2011-3-01']-1


#利用cumprod计算出一个简单的收益指数
returns=price.pct_change()
ret_index=(1+returns).cumprod() #???净值???
ret_index[0]=1#将第一个值设置为1
ret_index


##计算指定时期内的累计收益
m_returns=ret_index.resample('BM',how='last').pct_change()
m_returns['2012']


##通过重采样聚合也能算出
m_rets=(1+returns).resample('M',how='prod',kind='period')-1
m_rets['2012']


#如果知道股息的派发日和支付率,就可以将他们计入到每日总收益中
returns[dividend_dates]+=dividend_pcts







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值