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))
量化交易之One Piece篇 - 期货tick数据合成bar并返回bar_data数组
最新推荐文章于 2024-08-16 18:55:06 发布
本文介绍了一个名为BarGenerate的类,用于从CSV文件中读取金融时间序列数据,按指定间隔(如1分钟)转换为K线BarData对象,以便进行进一步的数据分析或机器学习应用。
摘要由CSDN通过智能技术生成