I’m trying to extract tick trade data, it begins 4:00:00 (pre market) but ends just before 16:00.
I can’t understand why it includes after hours trades?
Can anyone help me?
My code is below.
def collect_and_store_data(symbol, target_date, client, conn):
ny_tz = pytz.timezone(‘America/New_York’)
start_of_day_naive = datetime(target_date.year, target_date.month, target_date.day)
base_dt = ny_tz.localize(start_of_day_naive)
total_inserted_count = 0
cursor = conn.cursor()
try:
for i in range(96):
start_dt_aware = base_dt + timedelta(minutes=i * 15)
end_dt_aware = base_dt + timedelta(minutes=(i + 1) * 15) - timedelta(microseconds=1)
request_params = StockTradesRequest(
symbol_or_symbols=symbol,
start=start_dt_aware,
end=end_dt_aware
)
trades_response = client.get_stock_trades(request_params)
if symbol in trades_response.data and trades_response.data[symbol]:
trade_list = trades_response.data[symbol]
trade_data_to_insert = [
(t.timestamp, t.symbol, t.price, t.size, t.exchange, t.conditions, t.tape)
for t in trade_list
]
sql = """
INSERT INTO trades (time, symbol, price, size, exchange, conditions, tape)
VALUES %s ON CONFLICT DO NOTHING;
"""
execute_values(cursor, sql, trade_data_to_insert)
inserted_count = len(trade_data_to_insert)
total_inserted_count += inserted_count
print(f" {inserted_count}trades counted")
else:
print(f" no data ")
conn.commit()
print(f" :+1: 合計 {total_inserted_count} trades commited")
except Exception as e:
print(f"\n :x: {symbol} error occurred roll back: {e}", file=sys.stderr)
conn.rollback()
finally:
cursor.close()