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))
量化交易之One Piece篇 - 读取tick.csv文件后自定义周期合成bar数据
于 2024-02-27 00:07:30 首次发布
本文介绍了一个名为BarGenerate的类,用于从CSV文件中读取金融时间序列数据,按给定秒数间隔生成包含开盘价、最高价、最低价、收盘价、成交量和持仓量的K线DataFrame。
摘要由CSDN通过智能技术生成