量化交易之One Piece篇 - 读取tick.csv文件后自定义周期合成bar数据

本文介绍了一个名为BarGenerate的类,用于从CSV文件中读取金融时间序列数据,按给定秒数间隔生成包含开盘价、最高价、最低价、收盘价、成交量和持仓量的K线DataFrame。
摘要由CSDN通过智能技术生成
import datetime

# import pandas
from tqz_extern.pandas_operator import pandas

class BarGenerate:

    def __init__(self, csv_path: str):
        self.__tick_df = pandas.read_csv(csv_path)

        self.__bar_df = pandas.DataFrame(
            columns=['date_time', 'open_price', 'high_price', 'low_price', 'close_price', 'volume', 'open_interest']
        )

    @staticmethod
    def timestamp_to_datetime(timestamp) -> str:
        ret_dt = datetime.datetime.fromtimestamp(timestamp / 1000)
        ret_dt = ret_dt - datetime.timedelta(hours=8)

        return f'{ret_dt.date()} {ret_dt.time()}'


    def make_bar_dataframe(self, interval_secs: int):
        first_timestamp = self.__tick_df.iloc[0]['Timestamp']
        last_timestamp = self.__tick_df.iloc[-1]['Timestamp']

        interval = interval_secs * 1000  # 1 min
        while True:
            next_start_timestamp = first_timestamp + interval
            if first_timestamp > last_timestamp:
                # print('bar_df: ' + str(self.bar_df))
                break

            cur_snap_df = self.__tick_df[(self.__tick_df['Timestamp'] >= first_timestamp) & (self.__tick_df['Timestamp'] < next_start_timestamp)]
            if len(cur_snap_df) > 0:
                new_row = {
                    'date_time': self.timestamp_to_datetime(timestamp=next_start_timestamp),
                    'open_price': cur_snap_df.iloc[0]['LastPrice'],
                    'high_price': cur_snap_df['LastPrice'].max(),
                    'low_price': cur_snap_df['LastPrice'].min(),
                    'close_price': cur_snap_df.iloc[-1]['LastPrice'],
                    'volume': str(cur_snap_df.iloc[-1]['Volume'] - cur_snap_df.iloc[0]['Volume']),
                    'open_interest': str(cur_snap_df.iloc[-1]['OpenInterest'] - cur_snap_df.iloc[0]['OpenInterest'])
                }

                self.__bar_df.loc[len(self.__bar_df)] = new_row

            first_timestamp = next_start_timestamp

        return self

    def value(self):
        return self.__bar_df


if __name__ == '__main__':
    bar_df = BarGenerate(csv_path='rb2401.csv').make_bar_dataframe(interval_secs=60).value()
    print('bar_df: ' + str(bar_df))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值