import pandas as pd
import numpy as np
import config.sys_config as config
import hs_udata as hs
import time
"""
获取 沪深证券交易所 指定范围的交易日期集合
"""
def get_trade_dates(start_date, end_date=' '):
# 开始时间
if not start_date or not start_date.rfind('-'):
start_date = ' '
start_year = int(start_date.split('-')[0], base=10)
# 结束时间
end_year = int(time.strftime("%Y", time.localtime()), base=10)
if end_date == ' ' or not start_date.rfind('-'):
end_date = ' '
else:
end_year = int(end_date.split('-')[0], base=10)
# 获取交易日期集合
trade_date_df = pd.DataFrame()
while True:
if start_year > end_year:
break
if trade_date_df.size <= 0:
trade_date_df = hs.trading_calendar(secu_market='83',
if_trading_day='1',
start_date=start_date)
else:
trade_date_df = trade_date_df.append(hs.trading_calendar(secu_market='83',
if_trading_day='1',
start_date=start_date), ignore_index=True)
start_year = start_year + 1
start_date = str(start_year) + start_date[4:]
# 去除重复交易日
trade_date_df = trade_date_df.drop_duplicates()
print(trade_date_df.head())
return trade_date_df
# 获取股票日数据: 交易日期 股票行情,公司等信息
def get_stock_day_data(secu_code, trade_date):
# 获取数据:产品代码,交易日期,开盘价,最高价,最低价,收盘价,成交数量,成交额,涨跌幅,换手率,涨跌停状态,交易状态
stock_fields = "prod_code,trading_date,open_price,high_price,low_price,close_price,business_amount,business_balance,px_change_rate,turnover_ratio,up_down_status,turnover_status"
stock_data = hs.stock_quote_daily(en_prod_code=secu_code,
trading_date=trade_date,
adjust_way=2,
fields=stock_fields)
print(stock_data.head())
return stock_data
# 执行程序
def execute_procedure(stock_code_list, trade_date, mode='new'):
for stock_code in stock_code_list:
res_data = get_stock_day_data(stock_code, trade_date)
res_data['close_price'].replace('', np.nan, inplace=True)
res_data.dropna(subset=['close_price'], inplace=True)
if mode == 'new':
res_data.to_csv("temp/" + stock_code + ".csv", mode='w', index=False, encoding="utf-8")
else:
res_data.to_csv("temp/" + stock_code + ".csv", mode='a', index=False, header=False, encoding="utf-8")
"""
程序执行入口
"""
if __name__ == '__main__':
# 需要查询的产品code信息,000001.SH 上证指数
prod_code_list = ['000001.SH']
hs.set_token(config.HsData().get_token())
trade_dates_df = get_trade_dates(start_date='2010-01-01') # 获取交易时间集合
# 执行程序采集数据
mode = 'new'
count = 0
for trade_date in trade_dates_df['trading_date']:
print("执行日期:", trade_date)
if count > 0:
mode = 'add'
execute_procedure(prod_code_list, trade_date, mode)
count = count + 1
评论