基于pandas的一些金融常用基本操作
一、数据结构
1. 序列 Series
序列一般只有两列,一列是索引 index,一列是数据。
# 手动输入方式创建
return_series1 = pd.Series([0.003731, -0.001838, -0.003087, -0.024112], index=['中国石油', '工商银行', '上汽集团', '宝钢股份'])
# 通过数组生成序列
return_array = np.array([[0.003731, 0.021066, -0.004854, 0.006098, -0.00606],
[-0.001838, 0.001842, -0.016544, -0.003738, 0.003752],
[-0.003087, -0.000344, -0.033391, 0.007123, 0.004597],
[-0.024112, 0.011704, -0.029563, -0.01457, 0.016129]])
return_series2 = pd.Series(return_array[:,0], index=['中国石油', '工商银行', '上汽集团', '宝钢股份'])
2. 数据框 DataFrame
数据框的创建
date = ['2018-09-03', '2018-09-04', '2018-09-05', '2018-09-06', '2018-09-07']
stock = ['中国石油', '工商银行', '上汽集团', '宝钢股份']
return_dataframe = pd.DataFrame(data=return_array.T, index=date, columns=stock)
数据框导出成excel或csv等格式
如果导出csv格式有乱码,可以加上encoding=‘utf_8_sig’