mirror of
https://github.com/Xe138/AI-Trader.git
synced 2026-04-01 17:17:24 -04:00
This commit migrates the system to database-only position storage, eliminating file-based position.jsonl dependencies and fixing ContextInjector initialization timing issues. Key Changes: 1. ContextInjector Lifecycle Refactor: - Remove ContextInjector creation from BaseAgent.__init__() - Add BaseAgent.set_context() method for post-initialization injection - Update ModelDayExecutor to create ContextInjector with correct trading day date - Ensures ContextInjector receives actual trading date instead of init_date - Includes session_id injection for proper database linking 2. Database Position Functions: - Implement get_today_init_position_from_db() for querying previous positions - Implement add_no_trade_record_to_db() for no-trade day handling - Both functions query SQLite directly (positions + holdings tables) - Handle first trading day case with initial cash return - Include comprehensive error handling and logging 3. System Integration: - Update get_agent_system_prompt() to use database queries - Update _handle_trading_result() to write no-trade records to database - Remove dependencies on position.jsonl file reading/writing - Use deployment_config for automatic prod/dev database resolution Data Flow: - ModelDayExecutor creates runtime config and trading session - Agent initialized without context - ContextInjector created with (signature, date, job_id, session_id) - Context injected via set_context() - System prompt queries database for yesterday's position - Trade tools write directly to database - No-trade handler creates database records Fixes: - ContextInjector no longer receives None values - No FileNotFoundError for missing position.jsonl files - Database is single source of truth for position tracking - Session linking maintained across all position records Design: docs/plans/2025-02-11-database-position-tracking-design.md
102 lines
3.9 KiB
Python
102 lines
3.9 KiB
Python
import os
|
|
from dotenv import load_dotenv
|
|
load_dotenv()
|
|
import json
|
|
from datetime import datetime, timedelta
|
|
from pathlib import Path
|
|
from typing import Dict, List, Optional
|
|
import sys
|
|
import os
|
|
# Add project root directory to Python path
|
|
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
sys.path.insert(0, project_root)
|
|
from tools.price_tools import get_yesterday_date, get_open_prices, get_yesterday_open_and_close_price, get_today_init_position, get_yesterday_profit
|
|
from tools.general_tools import get_config_value
|
|
|
|
all_nasdaq_100_symbols = [
|
|
"NVDA", "MSFT", "AAPL", "GOOG", "GOOGL", "AMZN", "META", "AVGO", "TSLA",
|
|
"NFLX", "PLTR", "COST", "ASML", "AMD", "CSCO", "AZN", "TMUS", "MU", "LIN",
|
|
"PEP", "SHOP", "APP", "INTU", "AMAT", "LRCX", "PDD", "QCOM", "ARM", "INTC",
|
|
"BKNG", "AMGN", "TXN", "ISRG", "GILD", "KLAC", "PANW", "ADBE", "HON",
|
|
"CRWD", "CEG", "ADI", "ADP", "DASH", "CMCSA", "VRTX", "MELI", "SBUX",
|
|
"CDNS", "ORLY", "SNPS", "MSTR", "MDLZ", "ABNB", "MRVL", "CTAS", "TRI",
|
|
"MAR", "MNST", "CSX", "ADSK", "PYPL", "FTNT", "AEP", "WDAY", "REGN", "ROP",
|
|
"NXPI", "DDOG", "AXON", "ROST", "IDXX", "EA", "PCAR", "FAST", "EXC", "TTWO",
|
|
"XEL", "ZS", "PAYX", "WBD", "BKR", "CPRT", "CCEP", "FANG", "TEAM", "CHTR",
|
|
"KDP", "MCHP", "GEHC", "VRSK", "CTSH", "CSGP", "KHC", "ODFL", "DXCM", "TTD",
|
|
"ON", "BIIB", "LULU", "CDW", "GFS"
|
|
]
|
|
|
|
STOP_SIGNAL = "<FINISH_SIGNAL>"
|
|
|
|
agent_system_prompt = """
|
|
You are a stock fundamental analysis trading assistant.
|
|
|
|
Your goals are:
|
|
- Think and reason by calling available tools.
|
|
- You need to think about the prices of various stocks and their returns.
|
|
- Your long-term goal is to maximize returns through this portfolio.
|
|
- Before making decisions, gather as much information as possible through search tools to aid decision-making.
|
|
|
|
Thinking standards:
|
|
- Clearly show key intermediate steps:
|
|
- Read input of yesterday's positions and today's prices
|
|
- Update valuation and adjust weights for each target (if strategy requires)
|
|
|
|
Notes:
|
|
- You don't need to request user permission during operations, you can execute directly
|
|
- You must execute operations by calling tools, directly output operations will not be accepted
|
|
|
|
Here is the information you need:
|
|
|
|
Today's date:
|
|
{date}
|
|
|
|
Yesterday's closing positions (numbers after stock codes represent how many shares you hold, numbers after CASH represent your available cash):
|
|
{positions}
|
|
|
|
Yesterday's closing prices:
|
|
{yesterday_close_price}
|
|
|
|
Today's buying prices:
|
|
{today_buy_price}
|
|
|
|
When you think your task is complete, output
|
|
{STOP_SIGNAL}
|
|
"""
|
|
|
|
def get_agent_system_prompt(today_date: str, signature: str) -> str:
|
|
print(f"signature: {signature}")
|
|
print(f"today_date: {today_date}")
|
|
|
|
# Get job_id from runtime config
|
|
job_id = get_config_value("JOB_ID")
|
|
if not job_id:
|
|
raise ValueError("JOB_ID not found in runtime config")
|
|
|
|
# Query database for yesterday's position
|
|
from tools.price_tools import get_today_init_position_from_db
|
|
today_init_position = get_today_init_position_from_db(today_date, signature, job_id)
|
|
|
|
# Get yesterday's buy and sell prices
|
|
yesterday_buy_prices, yesterday_sell_prices = get_yesterday_open_and_close_price(today_date, all_nasdaq_100_symbols)
|
|
today_buy_price = get_open_prices(today_date, all_nasdaq_100_symbols)
|
|
yesterday_profit = get_yesterday_profit(today_date, yesterday_buy_prices, yesterday_sell_prices, today_init_position)
|
|
|
|
return agent_system_prompt.format(
|
|
date=today_date,
|
|
positions=today_init_position,
|
|
STOP_SIGNAL=STOP_SIGNAL,
|
|
yesterday_close_price=yesterday_sell_prices,
|
|
today_buy_price=today_buy_price,
|
|
yesterday_profit=yesterday_profit
|
|
)
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
today_date = get_config_value("TODAY_DATE")
|
|
signature = get_config_value("SIGNATURE")
|
|
if signature is None:
|
|
raise ValueError("SIGNATURE environment variable is not set")
|
|
print(get_agent_system_prompt(today_date, signature)) |