量化交易之One Piece篇 - 期货tick数据合成bar并返回bar_data数组

本文介绍了一个名为BarGenerate的类,用于从CSV文件中读取金融时间序列数据,按指定间隔(如1分钟)转换为K线BarData对象,以便进行进一步的数据分析或机器学习应用。
摘要由CSDN通过智能技术生成
import datetime

from tqz_extern.pandas_operator import pandas
from op_futures.op_objects.bar_data import BarData

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']
        )
        self.bars = []


    @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

        self.__bar_df['interval_secs'] = interval_secs
        self.__bar_df['price_tick'] = self.__tick_df['PriceTick'].unique()[0]
        self.__bar_df['volume_multiple'] = self.__tick_df['VolumeMultiple'].unique()[0]
        return self

    def df_value(self):
        return self.__bar_df

    def bars_value(self) -> [BarData]:

        [self.bars.append(BarData(
            date_time=str(row['date_time']),
            open_price=float(row['open_price']), high_price=float(row['high_price']), low_price=float(row['low_price']), close_price=float(row['close_price']),
            volume=float(row['volume']), open_interest=float(row['open_interest']),
            interval_secs=float(row['interval_secs']),
            price_tick=float(row['price_tick']), volume_multiple=float(row['volume_multiple'])
        )) for index, row in self.__bar_df.iterrows()]

        return self.bars


if __name__ == '__main__':
    # bar_df = BarGenerate(csv_path='../op_machine_learning/rb2401.csv').make_bar_dataframe(interval_secs=60).df_value()
    bars_list = BarGenerate(csv_path='../op_machine_learning/rb2401.csv').make_bar_dataframe(interval_secs=60).bars_value()
    print('bars_list: ' + str(bars_list))

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值