用Python来计算基金收益和平均年化收益率
Python •
Python编程语言对专业程序员和非IT从业人员都用处很大,比如很多搞金融的人都在用它做量化投资,也可以用来处理大量的Excel文档。Python容易入门,所以特别适合学生和非IT从业人员。
本人曾经工作上用过Python,后来没有使用了。即使工作中用不到了,但也大有用处。业余时间我也在了解基金投资,我是指数基金的拥趸,所以会需要回测指数的平均年化收益率,或者根据年化收益率预估未来多少年内的投资收益。
下面的Python代码就可以轻松计算基金收益和平均年化收益率,当然除了指数基金,主动型基金和股票也是可以的。很多网站上都有这类计算器可以直接使用,但是我写这段代码的意义是给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 == 1:
# 本金
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}")例如,如果从国证指数网站http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399296 上可以查看到创成长指数399296的基日是2012-12-31,基点1000,现在的点数是7488,从基日到现在8年多一点点,就算8年吧。计算出来的年化收益率是28.616%,这是非常漂亮的数字,跑赢了大部分主动型基金经理。

