A financial news analyst needs more than a request to “summarize the market.” Prompt engineering turns the request into an explicit contract: what evidence the model may use, what analysis it should perform, and what output the application can inspect. In a retrieval-augmented generation (RAG) pipeline, the prompt is the final instruction to the model, not a substitute for data preparation or retrieval. section 11.4.2 section 2.3.1
For a repeatable news signal, construct the prompt in steps:
- Provide 30-day headlines for trend context and detailed recent articles for specific signals. section 11.4.2
- Assign an evidence-based analyst role and restrict conclusions to the supplied context. section 11.4.2
- Specify a JSON-only output with fields such as sentiment_score, supply_risk, policy_tone, conviction, and key_events; require reasoning so scores can be traced to evidence. section 11.4.2
- Validate the response before downstream use. A JSON-only instruction is not API-level JSON mode. section 11.4.2
Listing 11.11 Building the two-step context and structured prompt
# Step 1: Build trend context from 30-day headlines
trend_headlines = []
for i in range(min(30, len(results_trend['ids'][0]))):
meta = results_trend['metadatas'][0][i]
trend_headlines.append(f"- {meta['published_dt'][:10]}: {meta['title']}")
trend_context = "\n".join(trend_headlines)
# Step 2: Build detailed context from 3-day content-rich articles
detail_docs = []
for i in range(len(results_recent['ids'][0])):
meta = results_recent['metadatas'][0][i]
doc = results_recent['documents'][0][i]
detail_docs.append(f"[{meta['published_dt'][:10]} | {meta['source']}]\n{doc}\n")
detail_context = "\n".join(detail_docs)
# Structured prompt with both contexts
prompt = f"""You are a quantitative analyst analyzing uranium sector news.
Based ONLY on the context below, provide a structured assessment.
TREND CONTEXT (30-day headlines for momentum):
{trend_context}
DETAILED ANALYSIS (last 3 days with full content):
{detail_context}
First, review the 30-day headlines to understand the dominant narrative trends.
Then, analyze the detailed recent articles to extract specific signals.
OUTPUT (JSON only):
{{
"sentiment_score": <-100 to +100, overall market sentiment>,
"supply_risk": <0 to 10, likelihood of supply disruption>,
"policy_tone": <-10 to +10, regulatory environment>,
"conviction": <0 to 10, signal strength>,
"key_events": ["event1", "event2"],
"reasoning": "brief explanation"
}}
"""
# Call LLM
response = client.chat.completions.create(
model="gpt-5-mini",
messages=[{"role": "user", "content": prompt}]
)
print("="*80)
print("LLM SIGNAL EXTRACTION")
print("="*80)
print(response.choices[0].message.content)
The listing assembles separate trend and detail contexts before placing them in a structured analyst prompt. It makes the boundary between retrieved evidence and instructions inspectable. section 11.4.2
The same technique serves different financial jobs. A personalized investment-post digest uses a prompt to guide a premium information product; subscription conversion and average revenue per user matter alongside output quality. Its illustrative Python call validates the input, but a production service would need a fuller backend, likely including RAG. section 2.3.1
Listing 2.1 Conceptual snippet for Alpha Digest summarization
import openai
from typing import List, Dict, Optional
# Best practice: Initialize the client. The API key is loaded automatically
# from the OPENAI_API_KEY environment variable.
client = openai.OpenAI()
def generate_alpha_digest(posts: List[str], user_profile: Dict) -> Optional[str]:
"""
Generates a personalized summary of investment posts using the Responses API.
Includes basic input validation and error handling for robustness.
"""
# 1. Input Validation: Ensure there are posts to analyze.
if not posts:
return "No posts provided for analysis."
# Safely read the user's name, with a neutral fallback if it is missing.
user_name = user_profile.get("name", "the user")
# Format the posts for the prompt, taking up to 3 for this example.
posts_text = "\n".join([f'- "{post}"' for post in posts[:3]])
prompt_content = f"""
You are an expert financial analyst. Based on the following posts from investors
that {user_name} follows, please provide a concise 'Alpha Digest'.
Extract the key investment thesis, any mentioned price targets, and the overall sentiment.
Posts:
{posts_text}
Your Premium Digest:
"""
try:
# 2. Modern API Call: Use the Responses API.
response = client.responses.create(
model="gpt-4o-mini", # A current, cost-effective model
input=prompt_content,
max_output_tokens=200,
temperature=0.2,
)
return response.output_text.strip()
# 3. Error Handling: Catch OpenAI API errors specifically.
except openai.APIError as e:
# In a real application, you would log this error.
print(f"An OpenAI API error occurred: {e}")
return "Analysis is temporarily unavailable."
# --- Example Usage ---
sample_posts = [
"I'm still bullish on $TECHCO. Their recent acquisition in the AI space is a game-changer. PT $150.",
"Seeing a lot of institutional buying in $ENERGIZE. The move to green energy is a long-term tailwind. Accumulating.",
"Warning on $RETAILCORP. Supply chain issues are worsening, and their margins will get squeezed. I'm staying away.",
]
user = {"name": "Jane Doe"}
digest = generate_alpha_digest(sample_posts, user)
print(digest)
The conceptual digest snippet shows how posts and a user profile enter a prompt-driven call, while explicitly leaving production retrieval and data processing outside the example. section 2.3.1
Fraud-investigation assistance
A contextual prompt can combine a user’s question with retrieved investigation guidelines and case notes, then ask for key risk factors. Retrieval quality, access permissions, input and output guardrails, and checks against source documents remain separate operational responsibilities. Monitoring results can drive prompt refinement; human oversight and guardrails reduce risk without eliminating it. section 7.4.3 section 11.5





































