所用数据如下
代码文件如下:
具体代码如下:
import pandas as pd
import numpy as np
#生成每月最后一天的时间序列数据
s1=pd.date_range('2021-1-31', freq='M',periods=12)
#准备好我们想要得到的报表格式
want=pd.DataFrame(np.zeros((9,12)),index=["M0","M1","M2","M3","M4","M5","M6","M7","M7+"],columns=s1)
#导入计划放款数据
data=pd.read_excel("C:\\Users\\Administrator\\Downloads\\1606266760_885079.xlsx",skiprows=1,usecols=[4,5,6,7],nrows=12)
#保存当月每期放款的情况
han={}
#从第一个时间2021年1月开始计算每个月的M0-M7 M7+(M8)9种状态对应的金额
j=0
#i表示want数据的第几列
for i in range(want.shape[1]):
#初始化当月每个阶段的金额为0,_0表示当月
M0_0=0
M1_0=0
M2_0=0
M3_0=0
M4_0=0
M5_0=0
M6_0=0
M7_0=0
M8_0=0
print(i,M0_0,M1_0,M2_0,M3_0,M4_0,M5_0,M6_0,M7_0,M8_0,sep=" ")
#调取上个月每个阶段的金额 ,_1表示上一个月
if i==0:
M0_1=0
M1_1=0
M2_1=0
M3_1=0
M4_1=0
M5_1=0
M6_1=0
M7_1=0
M8_1=0
else:
M0_1=want.iloc[0,i-1]
M1_1=want.iloc[1,i-1]
M2_1=want.iloc[2,i-1]
M3_1=want.iloc[3,i-1]
M4_1=want.iloc[4,i-1]
M5_1=want.iloc[5,i-1]
M6_1=want.iloc[6,i-1]
M7_1=want.iloc[7,i-1]
M8_1=want.iloc[8,i-1]
print(i,M0_0,M1_0,M2_0,M3_0,M4_0,M5_0,M6_0,M7_0,M8_0,sep=" ")
#当月放款额状态定为M0
len1=len(han.keys())
#如果当前已有前期放款记录,则对其剩余期数进行调整。如果没有则不用管,比如2020年1月份计算的时候,就不用管。
if len1>0:
for m in han.keys():
if han[m][2]>0:
han[m][2]=han[m][2]-1
else:
han[m][2]=0
#将当期新放款情况记录到库中,剩余未到期数等于放款期数,因为放款当月不用还款。
reportt=data[data["放款月"]==want.columns[i]].loc[:,["放款金额","期数"]]
for n in reportt.index:
han[n]=[reportt.loc[n,"放款金额"],reportt.loc[n,"期数"],reportt.loc[n,"期数"]]
print("*******************",i)
print(han)
M1_0=M0_1*0.0641
M2_0=M1_1*0.78
M3_0=M2_1*0.89
M4_0=M3_1*0.946
M5_0=M4_1*0.97
M6_0=M5_1*0.99
M7_0=M6_1*0.99
M8_0=M7_1*1
M0_0=M1_0*(1-0.78)+M2_0*(1-0.89)+M3_0*(1-0.946)+M4_0*(1-0.97)+M5_0*(1-0.99)+M6_0*(1-0.99)+M7_0*(1-1)+M8_0*(1-1)
for m in han.keys():
M0_0=M0_0+han[m][0]*(han[m][2]/han[m][1])
for k in [0,1,2,3,4,5,6,7,8]:
want.iloc[k,i]=eval("M"+str(k)+"_0")
#查看一下结果
want.iloc[:,:3]

#给数据框want增加一行汇总行
want.loc["汇总",:]=want.sum(axis=0)

wangxishi
2020-11-25
前面说反了
这个是把含缺失值的行的行号(行索引)找出来。先计算每行有多少个非缺失值,如果全部都是非缺失值,则非缺失值个数为13(一个y 12个x),如果非缺失值个数少于13则需要删掉这一行
wangxishi
2020-11-24
完整代码如下
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 11:01:18 2020
@author: Administrator
"""
#导入库
import pandas as pd
import numpy as np
#导入数据
data=pd.read_excel("D:\\360安全浏览器下载\\线性回归1119.xlsx")
#让时间显示为正确格式
#excel中以1900年1月1日为基准线记录时间
#python中以1970年1月1日为基准线记录时间
#进行时间转化的时候需要将从excel中导来的数值减去25539,再用pd.timestamp将其转换
data["时间"]=data["时间"].map(lambda x:x-25569)
data["时间"]=data["时间"].map(lambda x:pd.Timestamp(x,unit="D"))
data["年份"]=data["时间"].dt.year
#准备训练集(2018年及以前的数据)和测试集数据(2019年数据)
xnamelist=["沪深300",
"stock5","stock12",
"中国货币供应量M2(亿元)",
"M2_12",
"居民消费价格指数(上月=100)",
"居住类居民消费价格指数(上月=100)",
"新建商品住宅销售价格指数(上月=100)",
"二手住宅销售价格指数(上月=100)",
"银行间同业拆借加权平均利率_当期%",
"rate",
"美元兑人民币平均汇率_当期(人民币/美元)"
]
YX_2018=data[data["年份"]<=2018].loc[:,["Y"]+xnamelist]
#查看2018年及以前有多少行数据,可以看到有96行数据,你的变量x个数为12个
YX_2018.shape
#sklearn这个库建模和一般的统计学软件建模相比,sklearn这个库有不少缺点。
#其中一个缺点就是在做线性回归估计的时候要求传入的x和y不能有缺失值,
#因为系统不会自动筛选非缺失值进行建模和系数估计
#而是直接硬生生的给你抛出一个错误提示
#这就需要我们在进行建模前,人为进行缺失值处理。
#这里我们将含有缺失值的行直接从训练数据中删除。
YX_2018.notnull().sum(axis=0)
YX_2018.drop(labels = YX_2018.index[YX_2018.notnull().sum(axis=1)<13],axis=0,inplace=True)
#删除有缺失值的行之后,只剩下84行数据
YX_2019=data[data["年份"]==2019].loc[:,["Y"]+xnamelist]
#查看2019年有多少行数据,可以看到有12行数据,但是变量y有两个月的数据缺失
YX_2019.notnull().sum(axis=0)
#我们只对未缺失的行进行测试
YX_2019.drop(labels = YX_2019.index[YX_2019.notnull().sum(axis=1)<13],axis=0,inplace=True)
#导入线性回归类
from sklearn.linear_model import LinearRegression
#开始建模估计回归系数
#实例化一个回归模型
regmodel = LinearRegression()
#给模型传入测试集数据x和y
regmodel.fit(YX_2018.iloc[:,1:],YX_2018.iloc[:,0])#线性回归训练
#如果你想用sklearn库查看回归系数,可以用下面的命令
regmodel.intercept_ #常数项
regmodel.coef_ #斜率系数
#接下来我们只能直接进行预测,
Y_pred2018 = regmodel.predict(YX_2018.iloc[:,1:])#对测试集数据,用predict函数预测
Y_pred2019 = regmodel.predict(YX_2019.iloc[:,1:])#对测试集数据,用predict函数预测
#将预测值和实际值放在一起进行画图比较
import matplotlib.pyplot as plt
fig,axes=plt.subplots(2,1,figsize=(10,5))
#设定横轴刻度线标签值
xticklabels2018=data["时间"].loc[list(YX_2018.iloc[:,0].index)]
xticklabels2019=data["时间"].loc[list(YX_2019.iloc[:,0].index)]
axes[0].plot(xticklabels2018,YX_2018.iloc[:,0],'red', linewidth=2.5,label="real data2018")
axes[0].plot(xticklabels2018,Y_pred2018,'green',label="predict data2018")
axes[0].legend(loc = 'upper right') #添加图例
axes[1].plot(xticklabels2019,YX_2019.iloc[:,0],'red', linewidth=2.5,label="real data2019")
axes[1].plot(xticklabels2019,Y_pred2019,'green',label="predict data2019")
axes[1].legend(loc = 'upper right') #添加图例
wangxishi
2020-11-24
Y_pred2018 = regmodel.predict(YX_2018.iloc[:,1:])#对测试集数据,用predict函数预测
Y_pred2019 = regmodel.predict(YX_2019.iloc[:,1:])#对测试集数据,用predict函数预测
#将预测值和实际值放在一起进行画图比较
import matplotlib.pyplot as plt
fig,axes=plt.subplots(2,1,figsize=(10,5))
#设定横轴刻度线标签值
xticklabels2018=data["时间"].loc[list(YX_2018.iloc[:,0].index)]
xticklabels2019=data["时间"].loc[list(YX_2019.iloc[:,0].index)]
axes[0].plot(xticklabels2018,YX_2018.iloc[:,0],'red', linewidth=2.5,label="real data2018")
axes[0].plot(xticklabels2018,Y_pred2018,'green',label="predict data2018")
axes[0].legend(loc = 'upper right') #添加图例
axes[1].plot(xticklabels2019,YX_2019.iloc[:,0],'red', linewidth=2.5,label="real data2019")
axes[1].plot(xticklabels2019,Y_pred2019,'green',label="predict data2019")
axes[1].legend(loc = 'upper right') #添加图例

wangxishi
2020-11-24