python 金融分析学习

import tushare as ts

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

from scipy import stats

import statsmodels.api as sm

#资产定价模型   Ri=Rf+beta*(Rm-Rf)

sh=ts.get_hist_data('sh').sort_index()

pf=ts.get_hist_data('600000').sort_index()

sh['re']=np.log(sh['close']/sh['close'].shift(1))#计算上证指数的收益率

pf['re']=np.log(pf['close']/pf['close'].shift(1))#计算浦发银行的收益率

sh=sh.dropna()

pf=pf.dropna()#去掉缺失值

#由于数据行数不相等,做如下操作

shre=pd.DataFrame(sh['re'])

pfre=pd.DataFrame(pf['re'])

data=pd.merge(shre,pfre,left_index=Ture,right_index=True)

data.columns=['shre','pfre']

#利用线性回归求解beta值,并同时检验显著性水平

beta,alpha,r_value,p_value,std_err=stats.linregress(data['pfre'],data['shre'])

print(beta,alpha,r_value,p_value,std_err)

#APT 套利定价理论

import statsmodels.api as sm #导入最小二乘法求解各个因子的β值

results=sm.OLS(data['shre'],data['pfre']).fit()

print(results.summary())

#PuLP 线性优化

pip install PuLP

import pulp

x=pulp.LpVariable('x',lowBound=0)

y=pulp.LpVariable('y',lowBound=0)

problem=pulp.LpProblem("A simple maximization objective",pulp.LpMaximize)

problem+=3*x+2*y

problem+=2*x+y<=100

problem+=x+y<=80

problem+=x<=40

problem.solve()

for i in problem.variables()

    print(i.name,'=',variable.varValue)

猜你喜欢

转载自www.cnblogs.com/thechain/p/9276994.html