我的tushare ID:471789
# 获取多只股票财务数据,进行主成分分析以及K-均值聚类分析
import pandas as pd
import numpy as np
import tushare as ts
pro = ts.pro_api(token') # 输入token
zong=pd.DataFrame()
for t in ['600519.SH','600809.SH','688169.SH','600887.SH','002709.SZ','300750.SZ','603799.SH','688599.SH','002594.SZ','300015.SH',
'002475.SZ','300014.SZ','603486.SH','600309.SH','605117.SH','600436.SH','600238.SH','603259.SH','002142.SZ','603288.SH']:
df = pro.query('fina_indicator', ts_code=t,fields='ts_code,end_date,eps,roe,roic,profit_to_gr,gc_of_gr,ar_turn,debt_to_eqt,assets_turn',period='20210930')
df=df.head(1)
zong=zong.append(df)
zong.to_excel('20只股票分析数据.xlsx')
# 主成分分析过程
import pandas as pd
# 读取财务数据数据
data=pd.read_excel('20只股票分析数据.xlsx')
# 去掉nan值
data=data.dropna()
# 截取需要分析的数据列
data2=data.iloc[:,3:]
# 数据规范化处理
from sklearn.preprocessing import StandardScaler
X=data2.iloc[:,2:]
scaler=StandardScaler()
scaler.fit(X)
X=scaler.transform(X)
# 主成分分析
from sklearn.decomposition import PCA
pca=PCA(n_components=0.95)
Y=pca.fit_transform(X)
tzxl=pca.components_
gxl=pca.explained_variance_ratio_
import numpy as np
# 预定义综合得分数组F
F=np.zeros((len(Y)))
for i in range(len(gxl)):
f=Y[:,i]*gxl[i] # 第i个主成分与第i个成分贡献率乘积
F=F+f # 数组累积求和
dm=list(data['ts_code'].values)
fs1=pd.Series(F,index=dm)
Fscore=fs1.sort_values(ascending=False)
Fscore.to_excel('选股排名.xlsx')
# K均值聚类分析
from sklearn.cluster import KMeans
model=KMeans(n_clusters=4,random_state=0,max_iter=500)
model.fit(Y)
c=model.labels_
center=model.cluster_centers_
center=pd.DataFrame(center)
center.columns=('Y1','Y2','Y3')
fs=pd.Series(c,index=data['ts_code'])
fs=fs.sort_values()