Skip to content

Commit 230063b

Browse files
committed
feat: inject winning algorithm code as few-shot examples across sessions
The PromptRefiner now queries the best-performing code for each agent's file (main.py, Alpha.py, Universe.py, Risk.py) from the SQLite learning database and injects it as a reference example into the prompt. This means iteration 1 of a new session starts with the best code from all previous sessions, not from scratch. https://claude.ai/code/session_01G7z6nZKeChXhvrkz1bRvJf
1 parent a40b94f commit 230063b

2 files changed

Lines changed: 116 additions & 3 deletions

File tree

quantcoder/autonomous/database.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,60 @@ def get_top_strategies(self, limit: int = 10) -> List[Dict]:
289289
strategies.append(strategy)
290290
return strategies
291291

292+
def get_best_code_for_file(
293+
self,
294+
filename: str,
295+
category: Optional[str] = None,
296+
limit: int = 1,
297+
) -> List[Dict]:
298+
"""
299+
Get the best-performing code for a specific file (e.g., main.py, Alpha.py).
300+
301+
Returns strategies that contain the requested file, ordered by Sharpe.
302+
Each result includes 'code' (the file content) and strategy metadata.
303+
"""
304+
cursor = self.conn.cursor()
305+
306+
if category:
307+
cursor.execute("""
308+
SELECT name, category, sharpe_ratio, max_drawdown, code_files
309+
FROM generated_strategies
310+
WHERE success = 1 AND sharpe_ratio IS NOT NULL AND category = ?
311+
ORDER BY sharpe_ratio DESC
312+
LIMIT ?
313+
""", (category, limit * 3))
314+
else:
315+
cursor.execute("""
316+
SELECT name, category, sharpe_ratio, max_drawdown, code_files
317+
FROM generated_strategies
318+
WHERE success = 1 AND sharpe_ratio IS NOT NULL
319+
ORDER BY sharpe_ratio DESC
320+
LIMIT ?
321+
""", (limit * 3,))
322+
323+
results = []
324+
for row in cursor.fetchall():
325+
d = dict(row)
326+
files = json.loads(d['code_files'])
327+
# Match filename case-insensitively
328+
code = None
329+
for fname, content in files.items():
330+
if fname.lower() == filename.lower():
331+
code = content
332+
break
333+
if code:
334+
results.append({
335+
'name': d['name'],
336+
'category': d['category'],
337+
'sharpe': d['sharpe_ratio'],
338+
'drawdown': d['max_drawdown'],
339+
'code': code,
340+
})
341+
if len(results) >= limit:
342+
break
343+
344+
return results
345+
292346
def get_library_stats(self) -> Dict:
293347
"""Get overall library statistics."""
294348
cursor = self.conn.cursor()

quantcoder/autonomous/prompt_refiner.py

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,24 @@ class PromptRefiner:
1010
def __init__(self, db: LearningDatabase):
1111
self.db = db
1212

13+
# Map agent types to the files they generate
14+
AGENT_FILE_MAP = {
15+
'strategy': 'main.py',
16+
'alpha': 'Alpha.py',
17+
'universe': 'Universe.py',
18+
'risk': 'Risk.py',
19+
'coordinator': 'main.py',
20+
}
21+
1322
def inject_learnings(
1423
self,
1524
base_prompt: str,
1625
strategy_type: str = None,
1726
max_errors: int = 5,
18-
max_successes: int = 5
27+
max_successes: int = 5,
28+
agent_type: str = None,
1929
) -> str:
20-
"""Enhance base prompt with learned error patterns and success strategies."""
30+
"""Enhance base prompt with learned error patterns, success strategies, and winning code."""
2131
# Get common errors to avoid
2232
common_errors = self.db.get_common_error_types(limit=max_errors)
2333

@@ -50,6 +60,14 @@ def inject_learnings(
5060
perf_section = self._build_performance_section(perf_stats, strategy_type)
5161
enhancements.append(perf_section)
5262

63+
# Best code example for this agent's file
64+
code_section = self._build_code_example_section(
65+
agent_type=agent_type,
66+
strategy_type=strategy_type,
67+
)
68+
if code_section:
69+
enhancements.append(code_section)
70+
5371
# Combine everything
5472
if enhancements:
5573
enhanced_prompt = f"""{base_prompt}
@@ -153,6 +171,46 @@ def _find_fix_for_error(
153171

154172
return generic_fixes.get(error_type, 'Review code carefully')
155173

174+
def _build_code_example_section(
175+
self,
176+
agent_type: str = None,
177+
strategy_type: str = None,
178+
max_lines: int = 150,
179+
) -> str:
180+
"""Build a section with the best-performing code as a reference example."""
181+
if agent_type is None:
182+
return ""
183+
184+
filename = self.AGENT_FILE_MAP.get(agent_type)
185+
if not filename:
186+
return ""
187+
188+
examples = self.db.get_best_code_for_file(
189+
filename=filename,
190+
category=strategy_type,
191+
limit=1,
192+
)
193+
194+
if not examples:
195+
return ""
196+
197+
best = examples[0]
198+
code = best['code']
199+
200+
# Truncate very long code to keep the prompt manageable
201+
lines = code.splitlines()
202+
if len(lines) > max_lines:
203+
code = "\n".join(lines[:max_lines]) + f"\n# ... ({len(lines) - max_lines} more lines)"
204+
205+
section = (
206+
f"CODE REFERENCE - Best {filename} from previous runs "
207+
f"(Sharpe {best['sharpe']:.2f}, {best['category']}):\n"
208+
f"Use this as a structural reference. Adapt the logic to the new strategy.\n\n"
209+
f"```python\n{code}\n```\n"
210+
)
211+
212+
return section
213+
156214
def _extract_common_patterns(self, strategies: List[Dict]) -> List[Dict]:
157215
"""Extract common patterns from successful strategies."""
158216
patterns = []
@@ -241,7 +299,8 @@ def get_enhanced_prompts_for_agents(
241299
for agent_type, base_prompt in base_prompts.items():
242300
enhanced[agent_type] = self.inject_learnings(
243301
base_prompt,
244-
strategy_type=strategy_type
302+
strategy_type=strategy_type,
303+
agent_type=agent_type,
245304
)
246305

247306
return enhanced

0 commit comments

Comments
 (0)