从TuShare读取开市日历然后计算保存交易日历

来源:互联网 发布:易语言下载文件源码 编辑:程序博客网 时间:2024/04/27 22:21

TuShare提供的日历提供了自交易所开始交易以来每一天是否开市的信息, 但是没有提供其他在回测中可能用到的日历信息(例如某一天是否是一个月的首个交易日或最后一个交易日), 本文从TuShare读取开市日历然后计算自己的交易日历并保存的本地。 这样其他程序可以读取自己的交易日历从而避免不必要的重复计算。

import numpy as np  import pandas as pd  import tushare as ts  import datetime  import time  import tushare as ts  import os  import matplotlib  import matplotlib.pyplot as plt  def gen_save_exchange_calendar():    #从TuShare读取开市日历,然后自己计算week/month/querter/year sart/end 属性    #然后保存在本地以供以后使用    cal_dates = ts.trade_cal()    cal_dates['isWeekStart'] = 0    cal_dates['isWeekEnd'] = 0    cal_dates['isMonthStart'] = 0    cal_dates['isMonthEnd'] = 0    cal_dates['isQuarterStart'] = 0    cal_dates['isQuarterEnd'] = 0    cal_dates['isYearStart'] = 0    cal_dates['isYearEnd'] = 0    previous_i = -1    previous_open_week = -1    previous_open_month = -1    previous_open_year = -1    for i in cal_dates.index:        str_date = cal_dates.loc[i]['calendarDate']        isOpen = cal_dates.loc[i]['isOpen']        if not isOpen:            continue        date = datetime.datetime.strptime(str_date, '%Y-%m-%d').date()        #设置isWeekStart和isWeekEnd        current_open_week = date.isocalendar()[1]        if current_open_week != previous_open_week:            cal_dates.ix[i, 'isWeekStart'] = 1            if previous_open_week != -1:                cal_dates.ix[previous_i, 'isWeekEnd'] = 1                    #设置isMonthStart和isMonthEnd        current_open_month = date.month        if current_open_month != previous_open_month:            cal_dates.ix[i, 'isMonthStart'] = 1            if previous_open_month != -1:                cal_dates.ix[previous_i, 'isMonthEnd'] = 1            #顺便根据月份设置isQuarterStart和isQuarterEnd            if current_open_month in [1, 4, 7, 10]:                cal_dates.ix[i, 'isQuarterStart'] = 1                 if previous_open_month != -1:                    cal_dates.ix[previous_i, 'isQuarterEnd'] = 1            #有个特殊情况是交易所开始第一天应为QuarterStart            if previous_open_month == -1:                cal_dates.ix[i, 'isQuarterStart'] = 1                        #设置isYearStart和isYearEnd        current_open_year = date.year        if current_open_year != previous_open_year:            cal_dates.ix[i, 'isYearStart'] = 1            if previous_open_year != -1:                cal_dates.ix[previous_i, 'isYearEnd'] = 1                    previous_i = i        previous_open_week = current_open_week        previous_open_month = current_open_month        previous_open_year = current_open_year            #保存到本地文件中    file_name = 'D:\\python_study\\stock_hist_data\\exchange_calendar.h5'    hdf5_file=pd.HDFStore(file_name, 'w',complevel=4, complib='blosc')    hdf5_file['data']=cal_dates     hdf5_file.close()          gen_save_exchange_calendar()


原创粉丝点击