feat: add Polymarket agent prompts (analysts, researchers, trader, risk)

- Odds Analyst + Event Analyst (new)
- News/Social Analyst updated for Polymarket tools
- YES/NO/Timing 3-way debate advocates (new)
- Research Manager updated for 3-way evaluation
- Trader + Risk team updated for prediction market context

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
test 2026-03-21 21:17:27 +09:00
parent 39cce0fb9b
commit 2753b6438b
13 changed files with 390 additions and 88 deletions

View File

@ -0,0 +1,50 @@
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from tradingagents.agents.utils.polymarket_tools import get_event_details, get_market_stats, get_leaderboard_signals
def create_event_analyst(llm):
def event_analyst_node(state):
current_date = state["trade_date"]
event_id = state["event_id"]
event_question = state["event_question"]
tools = [get_event_details, get_market_stats, get_leaderboard_signals]
system_message = (
"You are a prediction market event analyst. Analyze the event's resolution criteria, deadline, base probability estimation, and top trader signals. "
"Focus on: resolution conditions and how likely they are to be met, time remaining until resolution, historical patterns from similar events, and what top traders are doing. "
"Use get_event_details to retrieve the event description and resolution criteria. Use get_market_stats to get open interest and trading statistics. Use get_leaderboard_signals to understand what top traders are positioning. "
"Write a detailed analytical report with specific observations. Do not simply say outcomes are uncertain — provide reasoned probability assessments based on the resolution criteria and market data. "
"Append a Markdown table summarizing key findings at the end."
)
prompt = ChatPromptTemplate.from_messages([
(
"system",
"You are a helpful AI assistant, collaborating with other assistants. "
"Use the provided tools to progress towards answering the question. "
"Execute what you can to make progress. "
"You have access to the following tools: {tool_names}.\n{system_message}"
"The current date is {current_date}. The event we are analyzing: {event_question} (Event ID: {event_id})",
),
MessagesPlaceholder(variable_name="messages"),
])
prompt = prompt.partial(
system_message=system_message,
tool_names=", ".join([tool.name for tool in tools]),
current_date=current_date,
event_id=event_id,
event_question=event_question,
)
chain = prompt | llm.bind_tools(tools)
result = chain.invoke(state["messages"])
report = ""
if len(result.tool_calls) == 0:
report = result.content
return {"messages": [result], "event_report": report}
return event_analyst_node

View File

@ -1,23 +1,26 @@
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
import time
import json
from tradingagents.agents.utils.agent_utils import get_news, get_global_news
from tradingagents.dataflows.config import get_config
from tradingagents.agents.utils.polymarket_tools import get_event_news, get_global_news
def create_news_analyst(llm):
def news_analyst_node(state):
current_date = state["trade_date"]
ticker = state["company_of_interest"]
event_id = state["event_id"]
event_question = state["event_question"]
tools = [
get_news,
get_event_news,
get_global_news,
]
system_message = (
"You are a news researcher tasked with analyzing recent news and trends over the past week. Please write a comprehensive report of the current state of the world that is relevant for trading and macroeconomics. Use the available tools: get_news(query, start_date, end_date) for company-specific or targeted news searches, and get_global_news(curr_date, look_back_days, limit) for broader macroeconomic news. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions."
+ """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."""
"You are a news researcher analyzing news relevant to a Polymarket prediction event. "
"Your role is to gather and synthesize recent news and trends that may affect the event outcome. "
"Use get_event_news(query) for event-specific news directly related to the prediction market question, "
"and get_global_news(query) for broader macro news that may influence the outcome. "
"Write a comprehensive report detailing the current state of affairs relevant to the event. "
"Do not simply state the trends are mixed — provide detailed and fine-grained analysis and insights that may help traders make decisions."
" Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."
)
prompt = ChatPromptTemplate.from_messages(
@ -26,12 +29,9 @@ def create_news_analyst(llm):
"system",
"You are a helpful AI assistant, collaborating with other assistants."
" Use the provided tools to progress towards answering the question."
" If you are unable to fully answer, that's OK; another assistant with different tools"
" will help where you left off. Execute what you can to make progress."
" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
" Execute what you can to make progress."
" You have access to the following tools: {tool_names}.\n{system_message}"
"For your reference, the current date is {current_date}. We are looking at the company {ticker}",
"For your reference, the current date is {current_date}. The event we are analyzing: {event_question} (Event ID: {event_id})",
),
MessagesPlaceholder(variable_name="messages"),
]
@ -40,7 +40,8 @@ def create_news_analyst(llm):
prompt = prompt.partial(system_message=system_message)
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
prompt = prompt.partial(current_date=current_date)
prompt = prompt.partial(ticker=ticker)
prompt = prompt.partial(event_id=event_id)
prompt = prompt.partial(event_question=event_question)
chain = prompt | llm.bind_tools(tools)
result = chain.invoke(state["messages"])

View File

@ -0,0 +1,50 @@
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from tradingagents.agents.utils.polymarket_tools import get_market_data, get_price_history, get_orderbook
def create_odds_analyst(llm):
def odds_analyst_node(state):
current_date = state["trade_date"]
event_id = state["event_id"]
event_question = state["event_question"]
tools = [get_market_data, get_price_history, get_orderbook]
system_message = (
"You are a prediction market odds analyst. Your role is to analyze the current market odds, price history, and orderbook depth for a Polymarket event. "
"Focus on: price trends and momentum, orderbook asymmetry (bid vs ask depth), volume patterns and liquidity, spread analysis, and smart money flow indicators. "
"Use get_market_data to fetch current event prices and metadata. Use get_price_history with the token_id from market data to analyze price trends. Use get_orderbook to examine bid/ask depth. "
"Write a detailed analytical report with specific numbers and trends. Do not simply say trends are mixed — provide actionable insights about whether the current market price fairly reflects the probability. "
"Append a Markdown table summarizing key metrics at the end."
)
prompt = ChatPromptTemplate.from_messages([
(
"system",
"You are a helpful AI assistant, collaborating with other assistants. "
"Use the provided tools to progress towards answering the question. "
"Execute what you can to make progress. "
"You have access to the following tools: {tool_names}.\n{system_message}"
"The current date is {current_date}. The event we are analyzing: {event_question} (Event ID: {event_id})",
),
MessagesPlaceholder(variable_name="messages"),
])
prompt = prompt.partial(
system_message=system_message,
tool_names=", ".join([tool.name for tool in tools]),
current_date=current_date,
event_id=event_id,
event_question=event_question,
)
chain = prompt | llm.bind_tools(tools)
result = chain.invoke(state["messages"])
report = ""
if len(result.tool_calls) == 0:
report = result.content
return {"messages": [result], "odds_report": report}
return odds_analyst_node

View File

@ -1,23 +1,26 @@
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
import time
import json
from tradingagents.agents.utils.agent_utils import get_news
from tradingagents.dataflows.config import get_config
from tradingagents.agents.utils.polymarket_tools import get_social_sentiment, get_whale_activity
def create_social_media_analyst(llm):
def social_media_analyst_node(state):
current_date = state["trade_date"]
ticker = state["company_of_interest"]
company_name = state["company_of_interest"]
event_id = state["event_id"]
event_question = state["event_question"]
tools = [
get_news,
get_social_sentiment,
get_whale_activity,
]
system_message = (
"You are a social media and company specific news researcher/analyst tasked with analyzing social media posts, recent company news, and public sentiment for a specific company over the past week. You will be given a company's name your objective is to write a comprehensive long report detailing your analysis, insights, and implications for traders and investors on this company's current state after looking at social media and what people are saying about that company, analyzing sentiment data of what people feel each day about the company, and looking at recent company news. Use the get_news(query, start_date, end_date) tool to search for company-specific news and social media discussions. Try to look at all sources possible from social media to sentiment to news. Do not simply state the trends are mixed, provide detailed and finegrained analysis and insights that may help traders make decisions."
+ """ Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read.""",
"You are a social sentiment analyst for prediction markets. "
"Analyze social media opinion and whale/top trader positions for the event. "
"Use get_social_sentiment(query) to gather Twitter and Reddit discussions related to the prediction market event. "
"Use get_whale_activity(market_id) to identify what large holders are doing with their positions. "
"Write a comprehensive report on public sentiment and large trader behavior. "
"Do not simply state the trends are mixed — provide detailed and fine-grained analysis and insights that may help traders make decisions."
" Make sure to append a Markdown table at the end of the report to organize key points in the report, organized and easy to read."
)
prompt = ChatPromptTemplate.from_messages(
@ -26,12 +29,9 @@ def create_social_media_analyst(llm):
"system",
"You are a helpful AI assistant, collaborating with other assistants."
" Use the provided tools to progress towards answering the question."
" If you are unable to fully answer, that's OK; another assistant with different tools"
" will help where you left off. Execute what you can to make progress."
" If you or any other assistant has the FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** or deliverable,"
" prefix your response with FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL** so the team knows to stop."
" Execute what you can to make progress."
" You have access to the following tools: {tool_names}.\n{system_message}"
"For your reference, the current date is {current_date}. The current company we want to analyze is {ticker}",
"For your reference, the current date is {current_date}. The event we are analyzing: {event_question} (Event ID: {event_id})",
),
MessagesPlaceholder(variable_name="messages"),
]
@ -40,7 +40,8 @@ def create_social_media_analyst(llm):
prompt = prompt.partial(system_message=system_message)
prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
prompt = prompt.partial(current_date=current_date)
prompt = prompt.partial(ticker=ticker)
prompt = prompt.partial(event_id=event_id)
prompt = prompt.partial(event_question=event_question)
chain = prompt | llm.bind_tools(tools)

View File

@ -1,34 +1,40 @@
import time
import json
def create_research_manager(llm, memory):
def research_manager_node(state) -> dict:
history = state["investment_debate_state"].get("history", "")
market_research_report = state["market_report"]
odds_report = state["odds_report"]
sentiment_report = state["sentiment_report"]
news_report = state["news_report"]
fundamentals_report = state["fundamentals_report"]
event_report = state["event_report"]
investment_debate_state = state["investment_debate_state"]
curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}"
curr_situation = f"{odds_report}\n\n{sentiment_report}\n\n{news_report}\n\n{event_report}"
past_memories = memory.get_memories(curr_situation, n_matches=2)
past_memory_str = ""
for i, rec in enumerate(past_memories, 1):
past_memory_str += rec["recommendation"] + "\n\n"
prompt = f"""As the portfolio manager and debate facilitator, your role is to critically evaluate this round of debate and make a definitive decision: align with the bear analyst, the bull analyst, or choose Hold only if it is strongly justified based on the arguments presented.
prompt = f"""As the research manager and debate judge, your role is to critically evaluate this 3-way debate between the YES Advocate, NO Advocate, and Timing Advocate, and make a definitive decision: YES, NO, or SKIP.
Summarize the key points from both sides concisely, focusing on the most compelling evidence or reasoning. Your recommendationBuy, Sell, or Holdmust be clear and actionable. Avoid defaulting to Hold simply because both sides have valid points; commit to a stance grounded in the debate's strongest arguments.
Summarize the key points from all three sides concisely, focusing on the most compelling evidence or reasoning. Your recommendation must be clear and actionable:
- YES: Bet that the event will occur (buy YES shares).
- NO: Bet that the event will not occur (buy NO shares).
- SKIP: There is no meaningful edge at current prices pass on this market entirely.
Avoid defaulting to SKIP simply because all sides have valid points; commit to a stance grounded in the debate's strongest arguments and the actual market edge.
Additionally, develop a detailed investment plan for the trader. This should include:
Your Recommendation: A decisive stance supported by the most convincing arguments.
Your Recommendation: A decisive stance (YES / NO / SKIP) supported by the most convincing arguments.
Confidence Level: High / Medium / Low reflecting your certainty in the recommendation.
Estimated True Probability: Your best estimate of the actual probability of the YES outcome (e.g., "We estimate ~65% true probability vs. 50% implied by current odds").
Rationale: An explanation of why these arguments lead to your conclusion.
Strategic Actions: Concrete steps for implementing the recommendation.
Take into account your past mistakes on similar situations. Use these insights to refine your decision-making and ensure you are learning and improving. Present your analysis conversationally, as if speaking naturally, without special formatting.
Strategic Actions: Concrete steps for implementing the recommendation (entry price targets, position sizing, exit conditions).
Take into account past mistakes on similar situations. Use these insights to refine your decision-making and ensure you are learning and improving. Present your analysis conversationally, as if speaking naturally, without special formatting.
Here are your past reflections on mistakes:
\"{past_memory_str}\"
@ -36,14 +42,19 @@ Here are your past reflections on mistakes:
Here is the debate:
Debate History:
{history}"""
response = llm.invoke(prompt)
new_investment_debate_state = {
"judge_decision": response.content,
"history": investment_debate_state.get("history", ""),
"bear_history": investment_debate_state.get("bear_history", ""),
"bull_history": investment_debate_state.get("bull_history", ""),
"current_response": response.content,
"yes_history": investment_debate_state.get("yes_history", ""),
"no_history": investment_debate_state.get("no_history", ""),
"timing_history": investment_debate_state.get("timing_history", ""),
"current_yes_response": investment_debate_state.get("current_yes_response", ""),
"current_no_response": investment_debate_state.get("current_no_response", ""),
"current_timing_response": investment_debate_state.get("current_timing_response", ""),
"latest_speaker": "Research Manager",
"count": investment_debate_state["count"],
}

View File

@ -1,42 +1,40 @@
import time
import json
def create_risk_manager(llm, memory):
def risk_manager_node(state) -> dict:
company_name = state["company_of_interest"]
event_id = state["event_id"]
history = state["risk_debate_state"]["history"]
risk_debate_state = state["risk_debate_state"]
market_research_report = state["market_report"]
odds_report = state["odds_report"]
news_report = state["news_report"]
fundamentals_report = state["fundamentals_report"]
event_report = state["event_report"]
sentiment_report = state["sentiment_report"]
trader_plan = state["investment_plan"]
curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}"
curr_situation = f"{odds_report}\n\n{sentiment_report}\n\n{news_report}\n\n{event_report}"
past_memories = memory.get_memories(curr_situation, n_matches=2)
past_memory_str = ""
for i, rec in enumerate(past_memories, 1):
past_memory_str += rec["recommendation"] + "\n\n"
prompt = f"""As the Risk Management Judge and Debate Facilitator, your goal is to evaluate the debate between three risk analysts—Aggressive, Neutral, and Conservative—and determine the best course of action for the trader. Your decision must result in a clear recommendation: Buy, Sell, or Hold. Choose Hold only if strongly justified by specific arguments, not as a fallback when all sides seem valid. Strive for clarity and decisiveness.
prompt = f"""As the Risk Management Judge and Debate Facilitator, your goal is to evaluate the debate between three risk analysts—Aggressive, Neutral, and Conservative—and determine the best course of action for the prediction market trader. Your decision must result in a clear recommendation: YES (bet on event occurring), NO (bet against event occurring), or SKIP (no bet). Choose SKIP only if strongly justified by specific arguments, not as a fallback when all sides seem valid. Strive for clarity and decisiveness.
Guidelines for Decision-Making:
1. **Summarize Key Arguments**: Extract the strongest points from each analyst, focusing on relevance to the context.
1. **Summarize Key Arguments**: Extract the strongest points from each analyst, focusing on relevance to the prediction market context.
2. **Provide Rationale**: Support your recommendation with direct quotes and counterarguments from the debate.
3. **Refine the Trader's Plan**: Start with the trader's original plan, **{trader_plan}**, and adjust it based on the analysts' insights.
4. **Learn from Past Mistakes**: Use lessons from **{past_memory_str}** to address prior misjudgments and improve the decision you are making now to make sure you don't make a wrong BUY/SELL/HOLD call that loses money.
4. **Learn from Past Mistakes**: Use lessons from **{past_memory_str}** to address prior misjudgments and improve the decision you are making now to make sure you don't make a wrong YES/NO/SKIP call that loses money.
Deliverables:
- A clear and actionable recommendation: Buy, Sell, or Hold.
- A clear and actionable recommendation: YES, NO, or SKIP.
- Detailed reasoning anchored in the debate and past reflections.
---
**Analysts Debate History:**
**Analysts Debate History:**
{history}
---
@ -60,7 +58,7 @@ Focus on actionable insights and continuous improvement. Build on past lessons,
return {
"risk_debate_state": new_risk_debate_state,
"final_trade_decision": response.content,
"final_decision": response.content,
}
return risk_manager_node

View File

@ -0,0 +1,64 @@
def create_no_advocate(llm, memory):
def no_node(state) -> dict:
investment_debate_state = state["investment_debate_state"]
history = investment_debate_state.get("history", "")
no_history = investment_debate_state.get("no_history", "")
event_question = state["event_question"]
current_yes_response = investment_debate_state.get("current_yes_response", "")
current_timing_response = investment_debate_state.get("current_timing_response", "")
odds_report = state["odds_report"]
sentiment_report = state["sentiment_report"]
news_report = state["news_report"]
event_report = state["event_report"]
curr_situation = f"{odds_report}\n\n{sentiment_report}\n\n{news_report}\n\n{event_report}"
past_memories = memory.get_memories(curr_situation, n_matches=2)
past_memory_str = ""
for rec in past_memories:
past_memory_str += rec["recommendation"] + "\n\n"
prompt = f"""You are the NO Advocate for the prediction market question: "{event_question}"
Your task is to build a strong, evidence-based case that this event will NOT occur (NO outcome). Leverage the provided research and data to support your position and counter opposing arguments.
Key points to focus on:
- Evidence Supporting NO: Highlight data, news, and trends that decrease the probability of the event occurring.
- Counterarguments: Directly address and rebut the YES Advocate's optimism and the Timing Advocate's hesitations.
- Market Mispricing: If the current odds overvalue YES (i.e., the market is too optimistic), explain why using specific evidence.
- Engagement: Present your argument conversationally, engaging directly with opposing points rather than just listing facts.
Resources:
Odds & Market Analysis: {odds_report}
Social Sentiment: {sentiment_report}
News Analysis: {news_report}
Event Analysis: {event_report}
Debate History: {history}
Last YES argument: {current_yes_response}
Last Timing argument: {current_timing_response}
Lessons from past predictions: {past_memory_str}
Build a compelling NO case. Address past mistakes and learn from them."""
response = llm.invoke(prompt)
argument = f"NO Advocate: {response.content}"
new_state = {
"history": history + "\n" + argument,
"yes_history": investment_debate_state.get("yes_history", ""),
"no_history": no_history + "\n" + argument,
"timing_history": investment_debate_state.get("timing_history", ""),
"current_yes_response": investment_debate_state.get("current_yes_response", ""),
"current_no_response": argument,
"current_timing_response": investment_debate_state.get("current_timing_response", ""),
"latest_speaker": "NO Advocate",
"judge_decision": investment_debate_state.get("judge_decision", ""),
"count": investment_debate_state["count"] + 1,
}
return {"investment_debate_state": new_state}
return no_node

View File

@ -0,0 +1,66 @@
def create_timing_advocate(llm, memory):
def timing_node(state) -> dict:
investment_debate_state = state["investment_debate_state"]
history = investment_debate_state.get("history", "")
timing_history = investment_debate_state.get("timing_history", "")
event_question = state["event_question"]
current_yes_response = investment_debate_state.get("current_yes_response", "")
current_no_response = investment_debate_state.get("current_no_response", "")
odds_report = state["odds_report"]
sentiment_report = state["sentiment_report"]
news_report = state["news_report"]
event_report = state["event_report"]
curr_situation = f"{odds_report}\n\n{sentiment_report}\n\n{news_report}\n\n{event_report}"
past_memories = memory.get_memories(curr_situation, n_matches=2)
past_memory_str = ""
for rec in past_memories:
past_memory_str += rec["recommendation"] + "\n\n"
prompt = f"""You are the Timing Advocate for the prediction market question: "{event_question}"
Your role is distinct from the YES and NO advocates. Even if the outcome might lean YES or NO, your job is to analyze whether the CURRENT market price accurately reflects the true probability and whether there is actionable edge RIGHT NOW.
Key points to focus on:
- Edge vs. Current Odds: Is there actually a mispricing? Compare the implied probability from current odds against your estimated true probability. Only recommend action if there is a meaningful edge.
- Time Decay and Deadline Proximity: How much time remains until resolution? Does the time horizon justify entering a position now, or is there opportunity cost from tying up capital?
- Market Efficiency: Has the market already priced in the likely outcome based on recent news and events? If so, the opportunity may have passed.
- Liquidity Traps: Can you actually execute at current prices, or is the market thin and spread too wide to make entry worthwhile?
- Wait for Better Odds: Would waiting for a market overreaction a temporary price swing yield a better entry point with higher expected value?
- SKIP Recommendation: If the current market offers no meaningful edge, recommend SKIP and explain why patience is the right strategy here.
Resources:
Odds & Market Analysis: {odds_report}
Social Sentiment: {sentiment_report}
News Analysis: {news_report}
Event Analysis: {event_report}
Debate History: {history}
Last YES argument: {current_yes_response}
Last NO argument: {current_no_response}
Lessons from past predictions: {past_memory_str}
Provide a rigorous timing and value analysis. Address past mistakes and learn from them."""
response = llm.invoke(prompt)
argument = f"Timing Advocate: {response.content}"
new_state = {
"history": history + "\n" + argument,
"yes_history": investment_debate_state.get("yes_history", ""),
"no_history": investment_debate_state.get("no_history", ""),
"timing_history": timing_history + "\n" + argument,
"current_yes_response": investment_debate_state.get("current_yes_response", ""),
"current_no_response": investment_debate_state.get("current_no_response", ""),
"current_timing_response": argument,
"latest_speaker": "Timing Advocate",
"judge_decision": investment_debate_state.get("judge_decision", ""),
"count": investment_debate_state["count"] + 1,
}
return {"investment_debate_state": new_state}
return timing_node

View File

@ -0,0 +1,64 @@
def create_yes_advocate(llm, memory):
def yes_node(state) -> dict:
investment_debate_state = state["investment_debate_state"]
history = investment_debate_state.get("history", "")
yes_history = investment_debate_state.get("yes_history", "")
event_question = state["event_question"]
current_no_response = investment_debate_state.get("current_no_response", "")
current_timing_response = investment_debate_state.get("current_timing_response", "")
odds_report = state["odds_report"]
sentiment_report = state["sentiment_report"]
news_report = state["news_report"]
event_report = state["event_report"]
curr_situation = f"{odds_report}\n\n{sentiment_report}\n\n{news_report}\n\n{event_report}"
past_memories = memory.get_memories(curr_situation, n_matches=2)
past_memory_str = ""
for rec in past_memories:
past_memory_str += rec["recommendation"] + "\n\n"
prompt = f"""You are the YES Advocate for the prediction market question: "{event_question}"
Your task is to build a strong, evidence-based case that this event WILL occur (YES outcome). Leverage the provided research and data to support your position and counter opposing arguments.
Key points to focus on:
- Evidence Supporting YES: Highlight data, news, and trends that increase the probability of YES.
- Counterarguments: Directly address and rebut the NO Advocate's concerns and the Timing Advocate's hesitations.
- Market Mispricing: If the current odds undervalue YES, explain why using specific evidence.
- Engagement: Present your argument conversationally, engaging directly with opposing points rather than just listing facts.
Resources:
Odds & Market Analysis: {odds_report}
Social Sentiment: {sentiment_report}
News Analysis: {news_report}
Event Analysis: {event_report}
Debate History: {history}
Last NO argument: {current_no_response}
Last Timing argument: {current_timing_response}
Lessons from past predictions: {past_memory_str}
Build a compelling YES case. Address past mistakes and learn from them."""
response = llm.invoke(prompt)
argument = f"YES Advocate: {response.content}"
new_state = {
"history": history + "\n" + argument,
"yes_history": yes_history + "\n" + argument,
"no_history": investment_debate_state.get("no_history", ""),
"timing_history": investment_debate_state.get("timing_history", ""),
"current_yes_response": argument,
"current_no_response": investment_debate_state.get("current_no_response", ""),
"current_timing_response": investment_debate_state.get("current_timing_response", ""),
"latest_speaker": "YES Advocate",
"judge_decision": investment_debate_state.get("judge_decision", ""),
"count": investment_debate_state["count"] + 1,
}
return {"investment_debate_state": new_state}
return yes_node

View File

@ -1,5 +1,3 @@
import time
import json
def create_aggressive_debator(llm):
@ -11,23 +9,23 @@ def create_aggressive_debator(llm):
current_conservative_response = risk_debate_state.get("current_conservative_response", "")
current_neutral_response = risk_debate_state.get("current_neutral_response", "")
market_research_report = state["market_report"]
odds_report = state["odds_report"]
sentiment_report = state["sentiment_report"]
news_report = state["news_report"]
fundamentals_report = state["fundamentals_report"]
event_report = state["event_report"]
trader_decision = state["trader_investment_plan"]
trader_decision = state["trader_plan"]
prompt = f"""As the Aggressive Risk Analyst, your role is to actively champion high-reward, high-risk opportunities, emphasizing bold strategies and competitive advantages. When evaluating the trader's decision or plan, focus intently on the potential upside, growth potential, and innovative benefits—even when these come with elevated risk. Use the provided market data and sentiment analysis to strengthen your arguments and challenge the opposing views. Specifically, respond directly to each point made by the conservative and neutral analysts, countering with data-driven rebuttals and persuasive reasoning. Highlight where their caution might miss critical opportunities or where their assumptions may be overly conservative. Here is the trader's decision:
prompt = f"""As the Aggressive Risk Analyst, your role is to actively champion high-reward, high-risk opportunities, emphasizing bold strategies and competitive advantages. When evaluating the trader's prediction market decision or plan, focus intently on the potential upside, probability edge, and innovative benefits—even when these come with elevated risk. Use the provided odds data and sentiment analysis to strengthen your arguments and challenge the opposing views. Specifically, respond directly to each point made by the conservative and neutral analysts, countering with data-driven rebuttals and persuasive reasoning. Highlight where their caution might miss critical opportunities or where their assumptions may be overly conservative. Here is the trader's decision:
{trader_decision}
Your task is to create a compelling case for the trader's decision by questioning and critiquing the conservative and neutral stances to demonstrate why your high-reward perspective offers the best path forward. Incorporate insights from the following sources into your arguments:
Market Research Report: {market_research_report}
Odds Analysis: {odds_report}
Social Media Sentiment Report: {sentiment_report}
Latest World Affairs Report: {news_report}
Company Fundamentals Report: {fundamentals_report}
Event Analysis: {event_report}
Here is the current conversation history: {history} Here are the last arguments from the conservative analyst: {current_conservative_response} Here are the last arguments from the neutral analyst: {current_neutral_response}. If there are no responses from the other viewpoints, do not hallucinate and just present your point.
Engage actively by addressing any specific concerns raised, refuting the weaknesses in their logic, and asserting the benefits of risk-taking to outpace market norms. Maintain a focus on debating and persuading, not just presenting data. Challenge each counterpoint to underscore why a high-risk approach is optimal. Output conversationally as if you are speaking without any special formatting."""

View File

@ -1,6 +1,4 @@
from langchain_core.messages import AIMessage
import time
import json
def create_conservative_debator(llm):
@ -12,23 +10,23 @@ def create_conservative_debator(llm):
current_aggressive_response = risk_debate_state.get("current_aggressive_response", "")
current_neutral_response = risk_debate_state.get("current_neutral_response", "")
market_research_report = state["market_report"]
odds_report = state["odds_report"]
sentiment_report = state["sentiment_report"]
news_report = state["news_report"]
fundamentals_report = state["fundamentals_report"]
event_report = state["event_report"]
trader_decision = state["trader_investment_plan"]
trader_decision = state["trader_plan"]
prompt = f"""As the Conservative Risk Analyst, your primary objective is to protect assets, minimize volatility, and ensure steady, reliable growth. You prioritize stability, security, and risk mitigation, carefully assessing potential losses, economic downturns, and market volatility. When evaluating the trader's decision or plan, critically examine high-risk elements, pointing out where the decision may expose the firm to undue risk and where more cautious alternatives could secure long-term gains. Here is the trader's decision:
prompt = f"""As the Conservative Risk Analyst, your primary objective is to protect assets, minimize volatility, and ensure steady, reliable outcomes. You prioritize stability, security, and risk mitigation, carefully assessing potential losses, adverse outcomes, and market volatility. When evaluating the trader's prediction market decision or plan, critically examine high-risk elements, pointing out where the decision may expose the firm to undue risk and where more cautious alternatives could secure long-term gains. Here is the trader's decision:
{trader_decision}
Your task is to actively counter the arguments of the Aggressive and Neutral Analysts, highlighting where their views may overlook potential threats or fail to prioritize sustainability. Respond directly to their points, drawing from the following data sources to build a convincing case for a low-risk approach adjustment to the trader's decision:
Market Research Report: {market_research_report}
Odds Analysis: {odds_report}
Social Media Sentiment Report: {sentiment_report}
Latest World Affairs Report: {news_report}
Company Fundamentals Report: {fundamentals_report}
Event Analysis: {event_report}
Here is the current conversation history: {history} Here is the last response from the aggressive analyst: {current_aggressive_response} Here is the last response from the neutral analyst: {current_neutral_response}. If there are no responses from the other viewpoints, do not hallucinate and just present your point.
Engage by questioning their optimism and emphasizing the potential downsides they may have overlooked. Address each of their counterpoints to showcase why a conservative stance is ultimately the safest path for the firm's assets. Focus on debating and critiquing their arguments to demonstrate the strength of a low-risk strategy over their approaches. Output conversationally as if you are speaking without any special formatting."""

View File

@ -1,5 +1,3 @@
import time
import json
def create_neutral_debator(llm):
@ -11,23 +9,23 @@ def create_neutral_debator(llm):
current_aggressive_response = risk_debate_state.get("current_aggressive_response", "")
current_conservative_response = risk_debate_state.get("current_conservative_response", "")
market_research_report = state["market_report"]
odds_report = state["odds_report"]
sentiment_report = state["sentiment_report"]
news_report = state["news_report"]
fundamentals_report = state["fundamentals_report"]
event_report = state["event_report"]
trader_decision = state["trader_investment_plan"]
trader_decision = state["trader_plan"]
prompt = f"""As the Neutral Risk Analyst, your role is to provide a balanced perspective, weighing both the potential benefits and risks of the trader's decision or plan. You prioritize a well-rounded approach, evaluating the upsides and downsides while factoring in broader market trends, potential economic shifts, and diversification strategies.Here is the trader's decision:
prompt = f"""As the Neutral Risk Analyst, your role is to provide a balanced perspective, weighing both the potential benefits and risks of the trader's prediction market decision or plan. You prioritize a well-rounded approach, evaluating the upsides and downsides while factoring in broader market trends, potential outcome shifts, and diversification strategies. Here is the trader's decision:
{trader_decision}
Your task is to challenge both the Aggressive and Conservative Analysts, pointing out where each perspective may be overly optimistic or overly cautious. Use insights from the following data sources to support a moderate, sustainable strategy to adjust the trader's decision:
Market Research Report: {market_research_report}
Odds Analysis: {odds_report}
Social Media Sentiment Report: {sentiment_report}
Latest World Affairs Report: {news_report}
Company Fundamentals Report: {fundamentals_report}
Event Analysis: {event_report}
Here is the current conversation history: {history} Here is the last response from the aggressive analyst: {current_aggressive_response} Here is the last response from the conservative analyst: {current_conservative_response}. If there are no responses from the other viewpoints, do not hallucinate and just present your point.
Engage actively by analyzing both sides critically, addressing weaknesses in the aggressive and conservative arguments to advocate for a more balanced approach. Challenge each of their points to illustrate why a moderate risk strategy might offer the best of both worlds, providing growth potential while safeguarding against extreme volatility. Focus on debating rather than simply presenting data, aiming to show that a balanced view can lead to the most reliable outcomes. Output conversationally as if you are speaking without any special formatting."""

View File

@ -1,36 +1,39 @@
import functools
import time
import json
def create_trader(llm, memory):
def trader_node(state, name):
company_name = state["company_of_interest"]
event_id = state["event_id"]
event_question = state["event_question"]
investment_plan = state["investment_plan"]
market_research_report = state["market_report"]
odds_report = state["odds_report"]
sentiment_report = state["sentiment_report"]
news_report = state["news_report"]
fundamentals_report = state["fundamentals_report"]
event_report = state["event_report"]
curr_situation = f"{market_research_report}\n\n{sentiment_report}\n\n{news_report}\n\n{fundamentals_report}"
curr_situation = f"{odds_report}\n\n{sentiment_report}\n\n{news_report}\n\n{event_report}"
past_memories = memory.get_memories(curr_situation, n_matches=2)
past_memory_str = ""
if past_memories:
for i, rec in enumerate(past_memories, 1):
for rec in past_memories:
past_memory_str += rec["recommendation"] + "\n\n"
else:
past_memory_str = "No past memories found."
context = {
"role": "user",
"content": f"Based on a comprehensive analysis by a team of analysts, here is an investment plan tailored for {company_name}. This plan incorporates insights from current technical market trends, macroeconomic indicators, and social media sentiment. Use this plan as a foundation for evaluating your next trading decision.\n\nProposed Investment Plan: {investment_plan}\n\nLeverage these insights to make an informed and strategic decision.",
"content": f"Based on a comprehensive analysis by a team of analysts, here is a prediction plan for the event: '{event_question}' (Event ID: {event_id}). This plan incorporates insights from market odds, news, social sentiment, and event analysis. Use this plan to formulate your betting decision.\n\nProposed Plan: {investment_plan}\n\nLeverage these insights to make an informed and strategic prediction.",
}
messages = [
{
"role": "system",
"content": f"""You are a trading agent analyzing market data to make investment decisions. Based on your analysis, provide a specific recommendation to buy, sell, or hold. End with a firm decision and always conclude your response with 'FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL**' to confirm your recommendation. Do not forget to utilize lessons from past decisions to learn from your mistakes. Here is some reflections from similar situatiosn you traded in and the lessons learned: {past_memory_str}""",
"content": f"""You are a prediction market trader analyzing event data to make betting decisions on Polymarket. Based on your analysis, provide a specific recommendation: YES (bet on event occurring), NO (bet against event occurring), or SKIP (no bet).
Consider the edge (difference between your estimated probability and market price), position sizing, and risk management. End with a firm decision and always conclude your response with 'FINAL PREDICTION: **YES/NO/SKIP** | Confidence: X.X | Edge: X.X' to confirm your recommendation.
Utilize lessons from past decisions to learn from mistakes: {past_memory_str}""",
},
context,
]
@ -39,7 +42,7 @@ def create_trader(llm, memory):
return {
"messages": [result],
"trader_investment_plan": result.content,
"trader_plan": result.content,
"sender": name,
}