Bond CF for loop and if else loop

跟風遠走 提交于 2021-02-11 07:32:54

问题


I am trying to add the last cash flow back into the par value using a if/else loop, but I can't seem to do it. How do I assign an int to a specific item in the range? I am trying to make it so if the index > 10, it will add the par value back in.

par = 1000
coupon_rate = 3
T = 5
freq = 2


def cf_calculator(par, r, T, freq):
    for i in range(T * freq):
        if (T) < (T * freq):
            coupon = (r/100) * par/freq
            print(coupon)
        else: 
            coupon = (r/100) * par/freq + par
            print(coupon)



print(cf_calculator(1000,3,5,2))

I know my if loop is wrong. Is there a better way?


回答1:


I assume this is what you are meaning to do:

par = 1000
coupon_rate = 3
T = 5
freq = 2


def cf_calculator(par, r, T, freq):
    for i in range(0,(T * freq)+1):
        if (i) < (T * freq):
            coupon = (r/100) * par/freq
            print(coupon)
        else: 
            coupon = (r/100) * par/freq + par
            print(coupon)



print(cf_calculator(1000,3,5,2))

Output:

15.0
15.0
15.0
15.0
15.0
15.0
15.0
15.0
15.0
15.0
1015.0
None

Now, according to the name of the function, you just need to discount each cash flow with its corresponding discount rate. Afterwards, you can add all of your discounted cash flows together in order to obtain the present value of the bond (which you probably want the function to return).

Additionally, I would rewrite the code a bit to make it more readable:

par = 1000
coupon_rate = 3
T = 5
freq = 2


def cf_calculator(par, r, T, freq):
    for i in range(0,(T * freq)+1):
        if i < (T * freq):
            coupon = ((r/100) * par) / freq
            print(coupon)
        else: 
            coupon = (((r/100) * par) / freq) + par
            print(coupon)

print(cf_calculator(par,coupon_rate,T,freq))


来源:https://stackoverflow.com/questions/57510308/bond-cf-for-loop-and-if-else-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!