读取股票价格数据后,np.array格式和DataFrame格式用不同的方法。
如果是np.array格式,比如价格为price
from numpy import *from pandas import *# 假如价格波动是4,7,10,4price = array([4,7,10,4])# 如果要计算对数收益率,就加一行代码:price = log(price)b = diff(price)c = b/price[:-1]print("b = ",b)print("c = ",c)
输出结果为:
b = [ 3 3 -6]c = [0.75, 0.42857142857142855, -0.6]
如果是DataFrame格式,价格不变
from numpy import *from pandas import *price = array([4,7,10,4])A = DataFrame(price)B = A.pct_change()print("B = ",B)
输出结果为:
B =0 NaN1 0.7500002 0.4285713 -0.600000