具有两个以上参数的最小二乘优化

时间:2018-04-18 16:36:31

标签: python optimization scipy least-squares

我有一个三列的数据框,一个是债券到期时间,息票价值和市场要求价值,而所有债券没有相同的时间间隔和优惠券一年两次支付,我试图适应第四度多项式符合市场利率。虽然债券的实际价值在询问栏中 我试过这个,它可以随时帮忙:

#tzvika and brothers
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import leastsq as lsq
df=pd.read_csv('bonds2.csv')
#today=pd.datetime.today()
today=pd.to_datetime('2018-03-28')
def rate(alpha,time):
    power=4-np.arange(5)
    return (alpha*time**power).sum()

#caluclate the present value of
def value_of_flow(alpha,maturity,coupon):
    '''if today>pd.to_datetime(maturity):
        #raise Exception('The bond is off date.')
        return -1'''
    today=pd.to_datetime('2018-03-23')
    maturity=pd.to_datetime(maturity)
    coupon_paying_dates=pd.date_range('{}/{}/{}'.format(today.year-1,maturity.month,maturity.day),maturity,freq='12SM-15')
    coupon_paying_dates=coupon_paying_dates[coupon_paying_dates>today]
    day_interval=(coupon_paying_dates-today).days/365

    pv=0
    r_t=0
    period=0
    for period in day_interval:
        r_t=rate(alpha,period)
        pv+=coupon*0.5*np.exp(-r_t*period)

    #get the rate in the last period to calculate present value of face value
    r_t=rate(alphas,day_interval[-1])
    pv+=1*np.exp(-r_t*day_interval[-1])
    return pv
def Errorfun(alpha,maturity,coupon,asked):
    return value_of_flow(alpha,maturity,coupon)-asked
today=pd.to_datetime('2018-03-23')
alphas=np.array([0.0,0.0,0.0,0.0,0.0])
alphas_value,success=lsq(Errorfun,alphas,args=(df.Maturity,df.Coupon,df.Asked))

我一直收到这个错误:

AttributeError: 'Series' object has no attribute 'month'

如果我在成熟度列上运行其他代码,则运行顺利

0 个答案:

没有答案