python - 我如何使用 Apply() 函数来解决这个问题?
问题描述
我有一个df,带有随机的投资组合,它们如下所示
>>> random_portafolios AAPL weight MSFT weight XOM weight JNJ weight JPM weight AMZN weight GE weight FB weight T weight 0 0.188478 0.068795 0.141632 0.147974 0.178185 0.040370 0.020516 0.047275 0.166774 1 0.236818 0.008540 0.082680 0.088380 0.453573 0.021001 0.014043 0.089811 0.005155 2 0.179750 0.071711 0.050107 0.089424 0.080108 0.106136 0.155139 0.073487 0.194138 3 0.214392 0.015681 0.034284 0.276342 0.118263 0.002101 0.057484 0.000317 0.281137 4 0.301469 0.099750 0.046454 0.093279 0.020095 0.073545 0.178752 0.146486 0.040168 5 0.132916 0.006199 0.305137 0.032262 0.090356 0.169671 0.205602 0.003686 0.054172
随机投资组合具有不同的权重
我也有这些行动的一年回报
>>> StockReturns.head() AAPL MSFT XOM TWTR JPM AMZN GE FB T Date 2017-01-04 -0.001164 -0.004356 -0.011069 0.025547 0.001838 0.004657 0.000355 0.015660 -0.005874 2017-01-05 0.005108 0.000000 -0.014883 0.013642 -0.009174 0.030732 -0.005674 0.016682 -0.002686 2017-01-06 0.011146 0.008582 -0.000499 0.004681 0.000123 0.019912 0.002853 0.022707 -0.019930 2017-01-09 0.009171 -0.003170 -0.016490 0.019220 0.000741 0.001168 -0.004979 0.012074 -0.012641 2017-01-10 0.001049 -0.000335 -0.012829 -0.007429 0.002837 -0.001280 -0.002859 -0.004404 0.000278
现在我想在该df中添加两列“Returns”和“Volatility”。收益和波动率必须对每一行的值起作用,并且对存在的每一行都起作用。
他尝试使用 Apply() 函数
def complex_computation():
WeightedReturns = StockReturns.mul(arr, axis=1)
ReturnsDaily= WeightedReturns.sum(axis=1)
mean_retorns_daily = np.mean(ReturnsDaily)
Returns = ((1+mean_retorns_daily)**252)
cov_mat =StockReturns.cov()
cov_mat_annual = cov_mat*252
Volatility= np.sqrt(np.dot(arr.T, np.dot(cov_mat_annual, arr)))
return Returns, Volatility
我正在寻找的是该结果出现在与其对应的行中(在本例中为第 0 行),并对我拥有的以下行执行相同操作。蟒蛇def complex_computation():
说name 'Returns' is not defined
后
def func(row):
random_portafolios['Volatility'].append(Volatility)
Returns, Volatility = complex_computation(row.values)
return pd.Series({'NewColumn1': Retturns,
'NewColumn2': Volatility})
和
def run_apply(random_portafolios):
df_result = random_portafolios.apply(func, axis=1)
return df_result
我怎样才能正确运行我的代码?
帮我!
解决方案
推荐阅读
- node.js - 没有为猫鼬函数 findOneAndUpdate 定义响应?
- vb.net - 输入新行时如何检查和更新现有记录日期,否则添加新行
- vue.js - VueJS 使用插槽扩展组件
- spring-boot - 打开“/actuator/mappings”时获取“Whitelabel 错误页面”
- unity3d - 将更改应用到 Prefab Unity
- apache-flink - 当使用保存点取消 flink bucketingsink 作业时,文件保留为 .pending
- reactjs - 反应路由器页眉和页脚显示,但刷新时不显示页面内容
- c# - Crud Mongodb With ASP.NET error 400 bad request
- java - 无法在我的测试中注入 Bean(@Spy 注入 bean 的子项)
- audio - FFMPEG 1 音频 + 1 静止图像 + 多次图像帧