python数据处理——获得A股市场交易的月初周初日期

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37876745/article/details/89497393

不废话直接上代码:

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

    
    return cal_dates         

首先从tushare拿到的数据是这样的:,时间就是从1990年往后

这个函数返回的数据是这样的:

如果想要用月初的数据的话就是:

cal_dates[cal_dates['isMonthStart']==1] 

猜你喜欢

转载自blog.csdn.net/m0_37876745/article/details/89497393