掘金成分股的原始数据格式
constituents trade_date
{'SHSE.600527': 0.009999999776482582, 'SHSE.600461': 0.019999999552965164,···} 2017-07-31 00:00:00
{'SHSE.603966': 0.009999999776482582, 'SHSE.603960': 0.009999999776482582,···} 2017-08-31 00:00:00
···
我想要的数据格式
stockcode
2016-01-29 SZSE.300002
2016-01-29 SZSE.300003
2016-01-29 SZSE.000568
2016-01-29 SZSE.000623
2016-01-29 SHSE.600398
...
2020-11-30 SHSE.600297
2020-11-30 SHSE.600352
2020-11-30 SHSE.600299
2020-11-30 SHSE.600406
2020-11-30 SHSE.600362
[17700 rows x 1 columns]
弄了好一会,记录一下,方便下次用到
stock300 = get_history_constituents(index='SHSE.000300', start_date='2016-01-01', end_date='2020-12-01')#[0]['constituents']
df300=pd.DataFrame(stock300)
df_300=df300.constituents.apply(lambda x:list(x.keys()))#.iloc[:,1]
df_300.index=df300.trade_date
#列表展开 然后每个列表再做成df,
list300=df_300.values.flatten()
indexs=list(map(lambda x:x.date(),df_300.index))
#时间索引为成分股数量的长度
listdf_300=list(map(lambda x,y:pd.DataFrame(x,index=[y]*len(x),columns=['stockcode']),list300,indexs))
#list嵌套df的合并
df_=reduce(lambda x,y:pd.concat([x,y]),listdf_300)
print(df_)
df_.to_csv('stock300.csv')#,index=False
更新下,其实只需要两个函数就可以更方便实现
def using_repeat(x):
return pd.DataFrame({"stockcode" :np.repeat(x.stockcode,len(trade_days)),
'classname':np.repeat(x.classname,len(trade_days)),
"tradedate" :trade_days})
numpy包还是用的不够熟练。。