量化交易之One Piece篇 - onepiece_rsh - 设置交易小节时间收盘前的偏移(去掉夜盘)


from tqz_extern.json_operator import TQZJsonOperator
import os
from datetime import datetime, timedelta

class MakeConfig:

    DAY: str = 'day'
    NIGHT: str = 'night'

    close_times: list = ["1500", "1515"]

    @classmethod
    def reset_trading_time_json(cls, source_trading_time_json: str, target_trading_time_json: str, offset_close_minutes: int = 0, add_night_session: bool = False):
        assert os.path.exists(path=source_trading_time_json), f'Bad path: {source_trading_time_json} not exist.'

        content = TQZJsonOperator.tqz_load_jsonfile(jsonfile=source_trading_time_json)

        target_content: {str, dict} = {}
        for instrument, data in content.items():
            target_content[instrument] = {cls.DAY: [], cls.NIGHT: []}
            for session in data[cls.DAY]:
                session_item = []
                for session_time in session:
                    session_start_end = f'{session_time.split(":")[0]}{session_time.split(":")[1]}'

                    if session_start_end in cls.close_times:
                        new_time_obj = datetime.strptime(session_start_end, "%H%M") - timedelta(minutes=offset_close_minutes)

                        session_item.append(int(new_time_obj.strftime("%H%M")))
                    else:
                        session_item.append(int(session_start_end))

                target_content[instrument][cls.DAY].append(session_item)

            if add_night_session:
                for session in data[cls.NIGHT]:
                    session_item = []
                    for session_time in session:
                        session_start_end = f'{session_time.split(":")[0]}{session_time.split(":")[1]}'
                        session_item.append(int(session_start_end))
                    target_content[instrument][cls.NIGHT].append(session_item)

        TQZJsonOperator.tqz_write_jsonfile(content=target_content, target_jsonfile=target_trading_time_json)


if __name__ == '__main__':
    MakeConfig.reset_trading_time_json(
        source_trading_time_json='source_trading_time.json',
        target_trading_time_json='trading_time.json',
        offset_close_minutes=5
    )