注意事项:需要安装Wind金融客户端并且用windPy权限
代码如下:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
from WindPy import *
# 设置属性防止中文乱码
mpl.rcParams['font.family'] = 'SimHei' # 设置字体为黑体
mpl.rcParams['axes.unicode_minus'] = False # 设置在中文字体是能够正常显示负号(“-”)
mpl.rcParams["font.size"] = 10 # 设置字体大小
# 2.windPy激活
if (w.isconnected()):
print('WindPy处于活跃状态')
else:
w.start()
print('WindPy已启动成功')
#step1.从wind获取股票3月份收盘价分别为平安银行,万科A,白云机场 中信银行 光大银行
stocks = ['000001.SZ', '000002.SZ', '600004.SH','601998.SH','601818.SH']
result_data=w.wsd(stocks, "close", "2023-01-01", "2023-12-31", "")
#step2.将Wind的数据结果集,转为数据帧,实际应用中以下代码可以进行优化
all_result_list = []
for index in range(len(result_data.Times)):
result_list = []
result_list.append(result_data.Times[index])#日期
result_list.append(result_data.Data[0][index])#000001.SZ 收盘价
result_list.append(result_data.Data[1][index])#000002.SZ 收盘价
result_list.append(result_data.Data[2][index])#600004.SH 收盘价
result_list.append(result_data.Data[3][index])#601998.SH 收盘价
result_list.append(result_data.Data[4][index])#601818.SH 收盘价
all_result_list.append(result_list)
cols_name=['STATIS_DATE','000001SZ','000002SZ','600004SH','601998SH','601818SH']
stock_df=pd.DataFrame(all_result_list,columns=cols_name).set_index('STATIS_DATE')
#画图
fig, ax = plt.subplots()#定义画布
ax.plot(stock_df.index,stock_df['000001SZ'],label='平安银行')#绘制收盘价曲线图
ax.plot(stock_df.index,stock_df['000002SZ'],label='万科A')
pa_mean= np.mean(stock_df['000001SZ'])#计算平安银行平均值
wk_mean = np.mean(stock_df['000002SZ'])#计算万科平均值
ax.set_xlabel('Date-日期')
ax.set_ylabel('Adjusted closing price-调整后收盘价')
[ax.axhline(y=i, color = j) for i,j in zip([pa_mean,wk_mean],['blue','orange']) ]#绘制水平参考线
fig.text(0.15,0.62,'The average price of 万科')
fig.text(0.67,0.22,'The average price of 平安')
ax.legend(loc='upper left')
plt.show()
标签:index,Python,list,df,result,收盘价,data,Wind,stock From: https://blog.51cto.com/u_17037683/12107930