gpt4 book ai didi

python - 如何循环具有多个输入的函数?

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:23 25 4
gpt4 key购买 nike

我正在尝试从函数(下面的代码)收集我的研究返回。不幸的是,我只能让它遍历所有日期,但不能遍历所有索引值。我尝试过的:

for i in index_c.iloc[:,1:]:
for dt in MICH_CONSUMER_SENTIMENT['Date']:
c=get_cum_returns(index_c,i,dt,6,5,'MXUS Index')
cum_ret['index_return'].append(c[0])
cum_ret['bench_return'].append(c[1])
cum_ret['abnormal_return'].append(c[2])
cum_ret['date'].append(dt)

我可以让一个 for 循环工作:for dt in MICH_CONSUMER_SENTIMENT['Date']:...,以便它附加字典“cum_ret”中一个索引的所有日期值。但是,如果我尝试循环日期和索引名称,则会收到以下错误,并且它仅在字典中附加部分数据:

error

我怎样才能解决这个问题,以便所有值都被附加到字典中?有没有其他方法来解决这个问题?我确信有,只是我对 Python 还很陌生。

功能

def get_cum_returns(prices, sid, date, days_before, days_after, 
benchmark_sid):
"""
Calculates cumulative and abnormal returns for the sid & benchmark

Parameters
----------
prices : pd.DataFrame
Pricing history DataFrame obtained from `get_pricing`. Index should
be the datetime index and sids should be columns.
sid : int or zipline.assets._assets.Equity object
Security that returns are being calculated for.
date : datetime object
Date that will be used as t=0 for cumulative return calcuations. All
returns will be calculated around this date.
days_before, days_after : int
Days before/after to be used to calculate returns for.
benchmark : int or zipline.assets._assets.Equity object

Returns
-------
sid_returns : pd.Series
Cumulative returns time series from days_before ~ days_after from date
for sid
benchmark_returns : pd.Series
Cumulative returns time series for benchmark sid
abnormal_returns : pd.Series
Abnormal cumulative returns time series for sid compared against
benchmark
"""
prices=index_c
date=dt
days_before, days_after=6,5
sid=i
benchmark_sid='MXUS Index'
day_zero_index = prices.index.searchsorted(date)
#print 'day_zero_index', day_zero_index
starting_index = max(day_zero_index - days_before, 0)
ending_index = min(day_zero_index + days_after + 1, len(prices.index) - 1)

if starting_index < 0 or ending_index >= len(prices.index):
assert False #is this possible
return None

if sid == benchmark_sid:
temp_price = prices.iloc[starting_index:ending_index,:].loc[:,[sid]]
else:
temp_price = prices.iloc[starting_index:ending_index,:].loc[:,[sid,
benchmark_sid]]

beta = calc_beta(sid, benchmark_sid, temp_price)
if beta is None:
#print 'beta is None'
return

daily_ret = temp_price.pct_change().fillna(0)

daily_ret['abnormal_returns'] = daily_ret[sid] -
beta*daily_ret[benchmark_sid]

cum_returns = (daily_ret + 1).cumprod() - 1

try:
# If there's not enough data for event study,
# return None
cum_returns.index = range(starting_index - day_zero_index,
ending_index - day_zero_index)
except e:
print ('exception', e)
return None

sid_returns = cum_returns[sid] - cum_returns[sid].iloc[0]
bench_returns = cum_returns[benchmark_sid] -
cum_returns[benchmark_sid].iloc[0]
abnormal_returns = cum_returns['abnormal_returns'] -
cum_returns['abnormal_returns'].iloc[0]

return sid_returns, bench_returns, abnormal_returns

非常感谢所有帮助。

问候,贾卡

最佳答案

错误消息告诉您问题所在:

'NoneType' object is not subscriptable

您的函数有时可能会返回None,即:如果捕获到异常。但是您的循环不会检查 c 是否为 None,并尝试为其添加下标,即:假装它是一个列表。

关于python - 如何循环具有多个输入的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53961417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com