我想创建一个股票投资组合估值的时间序列,通过汇总该投资组合中单个股票持有量的时间序列估值数据。我的问题是,在某些特定的日期,可能没有一个给定的股票持有估值,因此,在该日期加总将产生错误的结果。在
我想出的解决方案是排除某一特定持股的估值(实际价格)数据不存在的日期,然后在我有完整数据的这些日期进行汇总。我使用的程序如下:
# Get the individual holding valuation data
valuation = get_valuation(portfolio = portfolio, df = True)
# Then next few lines retrieve the dates for which I have complete price data for the
# assets that comprise this portflio
# First get a list of the assets that this portfolio contains (or has contained).
unique_assets = valuation['asset'].unique().tolist()
# Then I get the price data for these assets
ats = get_ats(assets = unique_assets, df = True )[['data_date','close_price']]
# I mark those dates for which I have a 'close_price' for each asset:
ats = ats.groupby('data_date')['close_price'].agg({'data_complete':lambda x: len(x) == len(unique_assets)} ).reset_index()
# And extract the corresponding valid dates.
valid_dates = ats['data_date'][ats['data_complete']]
# Filter the valuation data for those dates for which I have complete data:
valuation = valuation[valuation['data_date'].apply(lambda x: x in valid_dates.values)]
# Group by date, and sum the individual hodling valuations by date, to get the Portfolio valuation
portfolio_valuation = valuation[['data_date','valuation']].groupby('data_date').agg(lambda df: sum(df['valuation'])).reset_index()
我的问题有两个方面:
1)上述方法感觉相当复杂,我相信Pandas有更好的方法来实现我的解决方案。有什么建议吗?在
2)我使用的方法不理想。最好的方法是,对于那些我们没有估值数据的日期(对于给定的持股),我们应该使用该持股的最新估值。假设我在计算2012年6月21日投资组合的估值,并有GOOG在2012年6月21日的估值数据,而APPL的估值数据仅在2012年6月20日。那么2012年6月21日投资组合的估值仍应为这两次估值的总和。在大熊猫身上有没有一种有效的方法?我想避免重复数据。在
似乎再取样和/或fillna的结合会让你得到你想要的东西(意识到这来得有点晚了!)。在
像你现在这样去抓取你的数据。你把这些东西拿回来的时候有一些空隙。看看这个:
所以现在你有了这些数据,其中有很多空白,但是你想要的是这些每日分辨率数据。在
就这么做吧:
^{pr2}$这将用一堆丢失数据的nan填充数据帧。当你对它们进行聚合时,只需使用函数(例如。,南森np, np平均值)无视南斯!在
对你得到的数据的确切格式还是有点不清楚。希望有帮助。在
相关问题 更多 >
编程相关推荐