我试图计算用户股票市场交易的价格收益。你知道吗
我有2个数据帧:
第一个有购买数据。这叫做“购买”。下面是示例。你知道吗
Acceptance_Date Symbol Username Volume
01-Jan-2017 FB John 423
01-Jan-2017 FB Lucy 58
01-Jan-2017 FB Jeff 49,548
第二个是股市数据。这就是所谓的“市场”。下面是示例。你知道吗
Symbol Date Open Close
FB 1-Jan-16 80.00 81.00
FB 1-Apr-16 90.00 91.00
FB 1-Jul-16 100.00 101.00
FB 1-Jan-17 110.00 110.00
我要计算每次购买的1、3、6和12个月绩效。你知道吗
因此,逻辑应该是:如果用户在2016年1月1日购买,那么2016年4月1日的股票增值是多少?你知道吗
输出应该是更新的购买数据帧,如下所示:
Acceptance_Date Symbol Username Volume one_month two_month
01-Jan-2017 FB John 423 x% x%
01-Jan-2017 FB Lucy 58 x% x%
01-Jan-2017 FB Jeff 49,548 x% x%
我觉得我正在以一种极其低效的方式进行着。我可以在2分钟内在Excel中完成这个任务,但我正努力用Python/Pandas(我是新手)来处理它。你知道吗
这是我试过的代码,感觉就像砸石头砸钥匙。请帮帮我!你知道吗
#create a df to combine purchase data and market data
purchase_df = pd.merge(market[['Symbol', 'Date', 'Close']],
buys[['Symbol', 'Acceptance_Date']],
left_on=['Symbol', 'Date'], right_on=['Symbol', 'Acceptance_Date'])
#create a new column "one_month" and add the purchase date plus one month
one_month = pd.to_datetime(buys['Acceptance_Date'], format='%Y-%m-%d').dt.date + relativedelta(months =+ 1)
buys['one_month'] = one_month
#merge purchase_df with the one_month price data
month_forward = pd.merge(market[['Symbol', 'Date', 'Close']],
buys[['Symbol', 'one_month']],
left_on=['Symbol', 'Date'], right_on=['Symbol', 'one_month'])
#calculate the gain
one_month_gain = (month_forward.close - purchase_df.close) / purchase_df.close
#repeat again for months 3, 6 and 12 then merge
我最终找到了最简单的答案:
我会这么做:
首先透视市场表,以符号作为索引,日期作为列:
其次,定义一个函数来获取返回:
现在应用此函数逐行购买:
相关问题 更多 >
编程相关推荐