61/main.ipynb
2024-10-15 11:39:00 +00:00

214 lines
7.5 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": 12,
"id": "e706cfb0-2234-4c4c-95d8-d1968f656aa0",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"import pandas as pd\n",
"from tms_data_interface import SQLQueryInterface\n",
"\n",
"query = \"\"\"\n",
"WITH \n",
"-- Capture all orders and trades within the spoofing time window\n",
"trade_window AS (\n",
" SELECT\n",
" t.trade_id,\n",
" t.trader_id,\n",
" t.date_time AS trade_time,\n",
" t.trade_side,\n",
" t.trade_volume,\n",
" o.trader_id AS order_trader_id,\n",
" o.date_time AS order_time,\n",
" o.order_volume,\n",
" o.order_status,\n",
" o.order_price,\n",
" o.side AS order_side\n",
" FROM \n",
" {trade_10m_v3} t\n",
" LEFT JOIN \n",
" order_10m o ON o.date_time BETWEEN t.date_time - INTERVAL '{spoofing_time_window_s}' SECOND \n",
" AND t.date_time\n",
" WHERE \n",
" o.side = '{spoofing_side}'\n",
"),\n",
"\n",
"-- Calculate net order volume for the specific trader\n",
"net_order_volume_cte AS (\n",
" SELECT \n",
" trader_id,\n",
" trade_id,\n",
" trade_time,\n",
" SUM(CASE \n",
" WHEN order_status = 'new' THEN order_volume \n",
" WHEN order_status = 'cancelled' THEN -order_volume \n",
" WHEN order_status = 'fulfilled' THEN -order_volume \n",
" ELSE 0 \n",
" END) AS net_order_volume,\n",
" COUNT(*) AS num_orders\n",
" FROM trade_window\n",
" WHERE order_trader_id = trader_id -- Filter by the trader who executed the trade\n",
" GROUP BY trader_id, trade_id, trade_time\n",
"),\n",
"\n",
"-- Calculate total net order volume for all traders (i.e., for spoofing side orders)\n",
"net_order_volume_all_cte AS (\n",
" SELECT \n",
" trade_id,\n",
" SUM(CASE \n",
" WHEN order_status = 'new' THEN order_volume \n",
" WHEN order_status = 'cancelled' THEN -order_volume \n",
" WHEN order_status = 'fulfilled' THEN -order_volume \n",
" ELSE 0 \n",
" END) AS net_order_volume_all\n",
" FROM trade_window\n",
" GROUP BY trade_id\n",
"),\n",
"\n",
"-- Calculate total trade volume on the opposite side (e.g., sell if spoofing is on buy)\n",
"opposite_trade_volume_cte AS (\n",
" SELECT \n",
" t.trader_id,\n",
" t.trade_id,\n",
" SUM(t.trade_volume) AS total_trade_volume\n",
" FROM {trade_10m_v3} t\n",
" WHERE \n",
" t.date_time BETWEEN t.date_time - INTERVAL '{trade_time_window_s}' SECOND\n",
" AND t.date_time\n",
" AND t.trade_side = CASE WHEN '{spoofing_side}' = 'buy' THEN 'sell' ELSE 'buy' END\n",
" GROUP BY t.trader_id, t.trade_id\n",
")\n",
"\n",
"-- Final result with calculated spoofing indicators\n",
"SELECT\n",
" n.trade_id,\n",
" n.trader_id,\n",
" n.trade_time,\n",
" n.num_orders,\n",
" n.net_order_volume,\n",
" CASE \n",
" WHEN o.total_trade_volume > 0 THEN n.net_order_volume / o.total_trade_volume\n",
" ELSE NULL\n",
" END AS order_trade_ratio,\n",
" CASE \n",
" WHEN a.net_order_volume_all > 0 THEN n.net_order_volume / a.net_order_volume_all\n",
" ELSE NULL\n",
" END AS volume_percentage\n",
"FROM \n",
" net_order_volume_cte n\n",
"LEFT JOIN \n",
" opposite_trade_volume_cte o ON n.trade_id = o.trade_id\n",
"LEFT JOIN \n",
" net_order_volume_all_cte a ON n.trade_id = a.trade_id\n",
"WHERE \n",
" n.net_order_volume > 0 -- Only consider positive net order volumes (potential spoofing);\n",
" limit 100\n",
"\"\"\"\n",
"\n",
"class Scenario:\n",
" seq = SQLQueryInterface(schema=\"trade_schema\")\n",
"\n",
" def logic(self, **params):\n",
" spoofing_time_window = params.get('spoofing_time_window', 300000) # default to 300,000 ms (5 minutes)\n",
" spoofing_side = params.get('spoofing_side', 'buy')\n",
" use_volume_for_order_trade_ratio = params.get('use_volume_for_order_trade_ratio', True)\n",
" trade_time_window = params.get('trade_time_window', 300000)\n",
" ignore_trade_after_spoofing = params.get('ignore_trade_after_spoofing', True)\n",
" ignore_price_improvement = params.get('ignore_price_improvement', True)\n",
"\n",
" # Convert time windows from milliseconds to seconds\n",
" spoofing_time_window_s = int(spoofing_time_window / 1000)\n",
" trade_time_window_s = int(trade_time_window / 1000)\n",
"\n",
" query_start_time = datetime.now()\n",
" print(\"Query start time:\", query_start_time)\n",
"\n",
" # Execute the query with the parameters passed from `params`\n",
" row_list = self.seq.execute_raw(query.format(\n",
" trade_10m_v3=\"trade_10m_v3\", # Replace with actual table name\n",
" spoofing_time_window_s=spoofing_time_window_s,\n",
" trade_time_window_s=trade_time_window_s,\n",
" spoofing_side=spoofing_side\n",
" ))\n",
"\n",
" # Define columns for the resulting DataFrame\n",
" cols = [\n",
" 'trade_id', 'focal_id', 'trade_time', 'num_orders', \n",
" 'net_order_volume', 'order_trade_ratio', 'volume_percentage'\n",
" ]\n",
"\n",
" # Create a DataFrame from the query result\n",
" final_scenario_df = pd.DataFrame(row_list, columns=cols)\n",
"\n",
"\n",
" # Adding additional columns\n",
" final_scenario_df['segment'] = 'Default'\n",
" final_scenario_df['sar_flag'] = 'N'\n",
" final_scenario_df['risk'] = 'Low Risk'\n",
"\n",
" return final_scenario_df"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b5c4307f-bc35-47e2-b680-fd1df2168d6c",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Query start time: 2024-10-15 09:25:10.320161\n"
]
}
],
"source": [
"scenario = Scenario()\n",
"scenario.logic(spoofing_time_window = 300000,\n",
" spoofing_side = 'buy',\n",
" use_volume_for_order_trade_ratio = True,\n",
" trade_time_window = 300000,\n",
" ignore_trade_after_spoofing = True,\n",
" ignore_price_improvement = True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "36b1b24a-aeca-4d22-a2b3-6e04aca31695",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}