#第一题,判断是否活跃
import pandas as pd
dic = {"序号":[1,2,3,4,5,6],
"股票名称":["天士力","天下秀","广誉远","西藏药业","康缘药业","济川药业"],
"日个股交易股数":[9877307,1837300,2485059,4815515,6221107,6357894]}
df = pd.DataFrame(dic) #从字典变成表格
for i in range(df.shape[0]):
if df.loc[i,日个股交易股数] < 2000000:
df.loc[i,"交易情况"] = "不活跃"
elif df.loc[i,日个股交易股数] < 6000000:
df.loc[i, "交易情况"] = "一般"
else:
df.loc[i, "交易情况"] = "活跃"
# for i in range(df.shape[0]): #也可以把if写在一行
# df.loc[i,"交易情况"] = "不活跃" if df.iloc[i, 2] < 2000000 else "一般" if df.iloc[i,2] < 6000000 else "活跃"
#第二题,回报率和波动率排序以及评分
import pandas as pd
dic = {"序号":[1,2,3,4,5],
"股票名称":["华北制药","中西药业","宝信软件","海欣股份","通化东宝"],
"回报率":[0.0171,0.0190,0.0076,0.0034,0.0045],
"波动率":[0.0284,0.0279,0.0292,0.0299,0.0297]}
df = pd.DataFrame(dic) #从字典变成表格
df["回报率排序"] = df["回报率"].rank(method="dense",ascending=False)
df["波动率排序"] = df["波动率"].rank(method="dense",ascending=True)
df["两因素总分"] = df["回报率排序"] + df["波动率排序"]
#第三题,计算债券价格
import pandas as pd
dic = {"债券到期期限":[1,2,3,4,5],
"利率":[0.060,0.080,0.090,0.095,0.095]}
df = pd.DataFrame(dic) #从字典变成表格
for i in range(df.shape[0]):
df.loc[i, "债券价格"] = 100 / ((1+df.loc[i, "利率"])**(df.loc[i, "债券到期期限"]))
#第四题,求年金现值的函数
def PVA(A,i,n):
return A*(1-(1+i)**(-n))/i
#第五题,生成等额本息还款表
import pandas as pd
l = list(range(121)) #创建0-120的列表
dic = {"期数":l,"偿还本金":l,"偿还利息":l,"月供金额":l,"剩余本金":3100000} #先确定格式并用刚刚的列表占位
df = pd.DataFrame(dic) #从字典变成表格
df["月供金额"] = 3100000*0.06/12*(1+0.06/12)**(10*12)/((1+0.06/12)**(10*12)-1)
df.loc[0,"月供金额"] = 0 #第0期没有月供
for i in range(1,df.shape[0]):
df.loc[i,"偿还利息"] = df.loc[i-1,"剩余本金"]*0.06/12
df.loc[i,"偿还本金"] = df.loc[i,"月供金额"] - df.loc[i,"偿还利息"]
df.loc[i,"剩余本金"] = df.loc[i-1,"剩余本金"] - df.loc[i,"偿还本金"]
#第六题,投资组合构建与筛选,5只股票有(5^2-5)/2=10种组合
import pandas as pd
dic = {"序号":[1,2,3,4,5],
"股票名称":["亚宝药业","鲁抗药业","浙大网新","鹏博士","华北制药"],
"回报率":[0.0527,0.0175,0.0217,0.0165,0.0170],
"波动率":[0.0233,0.0183,0.0276,0.0283,0.0284]}
df = pd.DataFrame(dic)
Ndf = pd.DataFrame() #创建空表
temp = 0
for i in range(df.shape[0]):
for j in range(i+1,df.shape[0]):
Ndf.loc[temp,"股票组合"] = df.loc[i,"股票名称"]+"+"+df.loc[j,"股票名称"]
Ndf.loc[temp,"组合回报率"] = df.loc[i,"回报率"]/2 + df.loc[j,"回报率"]/2
Ndf.loc[temp,"组合波动率"] = df.loc[i,"波动率"]/2 + df.loc[j,"波动率"]/2
temp += 1
Ndf["组合回报率排序"] = Ndf["组合回报率"].rank(method="dense",ascending=False)
Ndf["组合波动率排序"] = Ndf["组合波动率"].rank(method="dense",ascending=True)
Ndf["组合总分"] = Ndf["组合回报率排序"] + Ndf["组合波动率排序"]