【问题标题】:Write for loop to perform a calculation on a specific amount of rows from existing dataframe column and append that calculation into a new column编写 for 循环以对现有数据框列中的特定行数执行计算,并将该计算附加到新列中
【发布时间】:2019-09-20 18:01:49
【问题描述】:

我正在尝试根据历史股票数据计算 10 年的远期回报。我有一个数据框:

    import blpapi
    options = blpapi.SessionOptions()
    options.setServerHost('localhost')
    options.setServerPort(8194)
    session = blpapi.Session(options)
    session.start()
    from tia.bbg import LocalTerminal
    import tia.bbg.datamgr as dm


    # data manager
    mgr = dm.BbgDataManager()

    # Bloomberg variables
    px = 'PX_LAST'

    # start and end date
    start_dt = '1952-01-01'
    end_dt = date.today()

    # tickers
    mve_tick = 'NCBEILQ027S' # Fred
    gdp_tick = 'GDP' # Fred
    sp_tick = mgr['SPX INDEX'] # Bloomberg

    # get data
    mve = fred.get_series(mve_tick, observation_start = start_dt, 
    observation_end = end_dt)
    gdp = fred.get_series(gdp_tick, observation_start = start_dt, 
    observation_end = end_dt)
    sp = sp_tick.get_historical(px, start_dt, end_dt)

    # create data frames
    mve_df = pd.DataFrame(mve)
    mve_df.index.name = 'Date'
    mve_df.columns = ['MVE']
    gdp_df = pd.DataFrame(gdp) * 1000
    gdp_df.index.name = 'Date'
    gdp_df.columns = ['GDP']
    gdp_col = gdp_df['GDP']
    sp_df = pd.DataFrame(sp)
    sp_df.index.name = 'Date'
    sp_df.columns = ['Price']

    # convert S&P to quarterly return
    sp_df = sp_df.resample('3MS').first()
    sp_df_col = sp_df['Price']

    # merge data frames
    df = mve_df.join([gdp_col, sp_df_col])
    df.reset_index(inplace = True)
    df['Q Return'] = df['Price'].pct_change()

我想根据“Q Return”列上的计算添加一个新列。

我想将 col 'Q Return' 中前 40 个数据点的值相乘,然后将该 sumproduct 提高到 (4/40),并将其作为我新附加列中的第一个值。然后下一个值将是列 'Q return' 的第 1-41 行的 sumproduct,然后将其提高到相同的指数,依此类推。

我写了这个函数来执行计算:

    def fwdreturn(returns, t):
        outp = 1
        for i in range(t, t + 40):
            outp = outp * i
        return outp'
    df['10 Year Fwd Return'] = [fwdreturn(df['Q Return'], t) for t in df['Q Return']] # this is where error is occuring
    print(df)

我得到的错误是“浮点”对象不能被解释为整数。

有没有更好的方法来解决这个问题?

【问题讨论】:

  • 感谢您的反馈 - 我进行了编辑以使其看起来更好......

标签: python dataframe for-loop


【解决方案1】:

我不太清楚您要完成什么,但该错误正在发生,因为您将列中的每个值作为t 传递给您的函数,然后尝试使用该浮点值作为range的参数(必须是整数)

如果您尝试将列中的每个值乘以列中接下来的 40 个值,可能是这样的:

def fwdreturn(returns, start_index):
    outp = 1
    for i in range(0, 40):
        outp = outp * returns[start_index + i]
    return outp
df['10 Year Fwd Return'] = [fwdreturn(df['Q Return'].to_list(), idx) for idx in range(0, df['Q Return'].size)]
print(df)

但是,当您达到要乘以的后续值少于 40 个的地步时,这将遇到一个巨大的问题。你必须弄清楚你想要的结果是什么。

【讨论】:

  • 感谢您的回复-所以我已将代码更改为类似于您回答的内容,现在我收到 KeyError: 269 (269 是 df 中的行数) .. 当我运行你的代码也一样,我得到同样的错误......
  • 是的,这正是我在上面提到的。它已经到了没有 40 个后续值可以相乘并出错的地步。在这种情况下,您会期望什么行为?只需将接下来的 39 相乘即可?
  • 所以我不需要这些数据 - 因为我只是想显示标准普尔 500 指数的历史 10 年远期回报......所以如何编写代码,所以一旦达到目的,就没有剩下 40 行它只是说 NaN 或类似的东西?
【解决方案2】:

我用这个修复了它:

    def fwdreturn(returns, t):
        outp = 1
        for i in range(t, t + 40):
            try:
                outp = outp * df['Q Return'][i]
            except KeyError:
                    return np.nan
        return outp

    df['10 Year Fwd Return'] = [fwdreturn(df['Q Return'], t) for t in df.index]


    print(df)

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2012-06-22
    • 2019-09-17
    • 1970-01-01
    相关资源
    最近更新 更多