电脑上按Ctrl + D,下次访问更方便
服务分类

用Python来分析计算基金、指数的年化收益率

最近研究证券指数,经常要计算长期年化收益率,所以写了段Python代码,用于计算指数的年化收益率做对比。

代码如下:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# 声明字符串数组并初始化
choose_types = ['1.根据本金、最终金额和年数计算年化收益率', '2.根据年化收益率计算收益(不包括本金)']
# 字符串数组的输出
for i in range(2):
    print('%s  ' % choose_types[i], end='')
choice = input('请输入选择:')
choice = int(choice)
if choice == 1:
    # 本金
    principal = input('请输入本金:')
    principal = float(principal)
    # 最终值
    final_amount = input('请输入最终金额:')
    final_amount = float(final_amount)
    # 年数
    number_of_years = input('请输入年数:')
    number_of_years = float(number_of_years)
    # 计算年化
    annual_return1 = ((final_amount / principal) ** (1 / number_of_years) - 1) * 100
    # 另一种方法:pow() 方法返回 xy(x 的 y 次方) 的值
    # annual_return2 = (pow(final_amount/principal, 1 / number_of_years) - 1) * 100
    print(f"计算得到的年化收益率为:{annual_return1}%")
elif choice == 2:
    # 本金
    principal = input('请输入本金:')
    principal = float(principal)
    # 最终值
    interest_rate = input('请输入年利率:')
    interest_rate = float(interest_rate)
    # 年数
    number_of_years = input('请输入年数:')
    number_of_years = float(number_of_years)
    # 计算收益
    interest1 = principal * (1 + interest_rate) ** number_of_years
    # 另一种方法
    # interest2 = principal * pow(1 + interest_rate, number_of_years)
    print(f"计算得到的利息收益为:{interest1}")

发表回复

登录后才能评论
联系我们

联系我们

微信客服:

fuwu360微信客服

工作时间:周一至周五,9:30-18:30,节假日休息

返回顶部