在Python中使用两个单独的日期框计算每月价格收益

2024-05-26 22:55:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算用户股票市场交易的价格收益。你知道吗

我有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

Tags: 数据dfclosedatadatefbonmerge
2条回答

我最终找到了最简单的答案:

#shift the data up one cell
new_market['one_m_close'] = new_market['close'].shift(-22)
new_market['one_m_date'] = new_market['date'].shift(-22)

#calculate the gain
new_market['one_m_change'] = (new_market.one_m_close - new_market.close) / new_market.close

#then merge DataFrames with pd.merge

我会这么做:

首先透视市场表,以符号作为索引,日期作为列:

# assuming you are using close-to-close returns
market_pivot = market.pivot_table(index='Symbol', columns='Date', values='Close')

其次,定义一个函数来获取返回:

def get_return(ser, li_duration):
    """
    ser : pandas series, represents a row from purchase_df
    li_duration : list of int for holding periods
    """
    # do some list comprehension here to convert li_duration to end dates
    ldt_dates = [...]
    date = ser['Acceptance_Date']
    symbol = ser['Symbol']
    begin_price = market_pivot.loc[symbol, date]
    end_price = market_pivot.loc[symbol, ldt_dates]
    # calculate returns and replace the indices
    return_ser = end_price / begin_price - 1
    return_ser.index = [<desired column labels here>]
    # append the returns to purchase information
    return ser.append(return_ser)

现在应用此函数逐行购买:

df_result = purchase_df.apply(get_return, li_duration=[1, 3, 6, 12])

Disclaimer: didn't actually run the code, just to show thought process

相关问题 更多 >

    热门问题