Mic*_*ael 18 python python-3.x pandas
这是我的Pandas数据框:
prices = pandas.DataFrame([1035.23, 1032.47, 1011.78, 1010.59, 1016.03, 1007.95,
1022.75, 1021.52, 1026.11, 1027.04, 1030.58, 1030.42,
1036.24, 1015.00, 1015.20])
Run Code Online (Sandbox Code Playgroud)
这是我的daily_return
功能:
def daily_return(prices):
return prices[:-1] / prices[1:] - 1
Run Code Online (Sandbox Code Playgroud)
这是来自此功能的输出:
0 NaN
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
13 0
14 NaN
Run Code Online (Sandbox Code Playgroud)
为什么我有这个输出?
YaO*_*OzI 53
为什么不使用默认pct_change
提供的非常方便的方法pandas
:
import pandas as pd
prices = pandas.DataFrame([1035.23, 1032.47, 1011.78, 1010.59, 1016.03, 1007.95,
1022.75, 1021.52, 1026.11, 1027.04, 1030.58, 1030.42,
1036.24, 1015.00, 1015.20])
daily_return = prices.pct_change(1) # 1 for ONE DAY lookback
monthly_return = prices.pct_change(21) # 21 for ONE MONTH lookback
annual_return = prices.pct_change(252) # 252 for ONE YEAR lookback
Run Code Online (Sandbox Code Playgroud)
原文 prices
:
print(prices)
0
0 1035.23
1 1032.47
2 1011.78
3 1010.59
4 1016.03
5 1007.95
6 1022.75
7 1021.52
8 1026.11
9 1027.04
10 1030.58
11 1030.42
12 1036.24
13 1015.00
14 1015.20
Run Code Online (Sandbox Code Playgroud)
每日回报为prices.pct_change(1)
:
print(prices.pct_change(1))
0
0 NaN
1 -0.002666
2 -0.020039
3 -0.001176
4 0.005383
5 -0.007953
6 0.014683
7 -0.001203
8 0.004493
9 0.000906
10 0.003447
11 -0.000155
12 0.005648
13 -0.020497
14 0.000197
Run Code Online (Sandbox Code Playgroud)
HYR*_*YRY 22
因为操作将在索引上进行对齐,所以您可以将其中一个DataFrame转换为数组:
prices[:-1].values / prices[1:] - 1
Run Code Online (Sandbox Code Playgroud)
要么
prices[:-1] / prices[1:].values - 1
Run Code Online (Sandbox Code Playgroud)
取决于你想要的结果索引.
或使用shift()
方法:
prices.shift(1) / prices - 1
Run Code Online (Sandbox Code Playgroud)
和:
prices / prices.shift(1) - 1
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41640 次 |
最近记录: |