create-prediction-market-agent 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -0
  3. package/index.mjs +338 -0
  4. package/package.json +19 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SimpleFunctions
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # create-prediction-market-agent
2
+
3
+ Scaffold a prediction market agent project powered by [SimpleFunctions](https://simplefunctions.dev).
4
+
5
+ ## Usage
6
+
7
+ ```bash
8
+ npx create-prediction-market-agent my-agent
9
+ ```
10
+
11
+ ## Templates
12
+
13
+ | Template | Language | What you get |
14
+ |----------|----------|-------------|
15
+ | Vanilla TypeScript | TypeScript | Minimal agent using REST API directly |
16
+ | LangChain | Python | LangChain agent with 4 prediction market tools |
17
+ | CrewAI | Python | Multi-agent crew (analyst + risk researcher) |
18
+ | MCP Agent | TypeScript | MCP-connected agent for Claude Code / Cursor |
19
+
20
+ ## What's included
21
+
22
+ Every template comes pre-configured with:
23
+ - SimpleFunctions API integration (no auth needed for public endpoints)
24
+ - World state access (real-time probabilities from 9,706 markets)
25
+ - Market search (Kalshi + Polymarket)
26
+ - Trade ideas (conviction-scored)
27
+ - README with setup instructions
28
+ - `.gitignore`
29
+
30
+ ## SimpleFunctions
31
+
32
+ SimpleFunctions gives AI agents access to calibrated world state from prediction markets. 38 MCP tools, 43 CLI commands, REST API.
33
+
34
+ ```bash
35
+ # MCP — one command
36
+ claude mcp add simplefunctions --url https://simplefunctions.dev/api/mcp/mcp
37
+
38
+ # CLI — 43 commands
39
+ npm i -g @spfunctions/cli && sf agent
40
+
41
+ # REST — instant data
42
+ curl https://simplefunctions.dev/api/agent/world
43
+ ```
44
+
45
+ ## License
46
+
47
+ MIT
48
+
49
+ ---
50
+
51
+ **Part of [SimpleFunctions](https://simplefunctions.dev)** — context flow for prediction markets.
52
+
53
+ - [Awesome Prediction Markets](https://github.com/spfunctions/awesome-prediction-markets) — curated list for developers
54
+ - [CLI](https://github.com/spfunctions/simplefunctions-cli) — 43 commands for prediction market intelligence
55
+ - [Docs](https://simplefunctions.dev/docs) — full documentation
package/index.mjs ADDED
@@ -0,0 +1,338 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { writeFileSync, mkdirSync, existsSync } from 'fs'
4
+ import { join, basename } from 'path'
5
+ import { createInterface } from 'readline'
6
+
7
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
8
+ const ask = (q) => new Promise((r) => rl.question(q, r))
9
+
10
+ const TEMPLATES = {
11
+ typescript: {
12
+ name: 'Vanilla TypeScript',
13
+ files: {
14
+ 'package.json': (name) => JSON.stringify({
15
+ name,
16
+ version: '0.1.0',
17
+ type: 'module',
18
+ scripts: { start: 'npx tsx agent.ts', dev: 'npx tsx --watch agent.ts' },
19
+ dependencies: { '@spfunctions/cli': 'latest' },
20
+ devDependencies: { tsx: 'latest', typescript: 'latest' },
21
+ }, null, 2),
22
+ 'agent.ts': () => `/**
23
+ * Prediction Market Agent — powered by SimpleFunctions
24
+ * Run: npm start
25
+ */
26
+
27
+ const BASE = 'https://simplefunctions.dev'
28
+
29
+ async function main() {
30
+ // 1. Get the world state — what's happening right now
31
+ const world = await fetch(\`\${BASE}/api/agent/world\`).then(r => r.text())
32
+ console.log('=== World State ===')
33
+ console.log(world)
34
+
35
+ // 2. Search for markets on a topic
36
+ const markets = await fetch(\`\${BASE}/api/public/scan?q=oil\`).then(r => r.json())
37
+ console.log('\\n=== Oil Markets ===')
38
+ for (const m of (markets.results || []).slice(0, 5)) {
39
+ console.log(\` \${m.title}: \${m.yesPrice}c (\${m.venue})\`)
40
+ }
41
+
42
+ // 3. Get trade ideas
43
+ const ideas = await fetch(\`\${BASE}/api/public/ideas\`).then(r => r.json())
44
+ const list = Array.isArray(ideas) ? ideas : ideas.ideas || []
45
+ if (list.length) {
46
+ console.log('\\n=== Trade Ideas ===')
47
+ for (const idea of list.slice(0, 3)) {
48
+ console.log(\` [\${idea.conviction?.toUpperCase()}] \${idea.headline}\`)
49
+ }
50
+ }
51
+ }
52
+
53
+ main().catch(console.error)
54
+ `,
55
+ 'tsconfig.json': () => JSON.stringify({
56
+ compilerOptions: { target: 'ES2022', module: 'ESNext', moduleResolution: 'bundler', strict: true, esModuleInterop: true },
57
+ include: ['*.ts'],
58
+ }, null, 2),
59
+ },
60
+ },
61
+ langchain: {
62
+ name: 'LangChain (Python)',
63
+ files: {
64
+ 'requirements.txt': () => `langchain>=0.3
65
+ langchain-openai>=0.3
66
+ requests>=2.31
67
+ `,
68
+ 'agent.py': () => `"""
69
+ Prediction Market Agent — LangChain + SimpleFunctions
70
+ Run: pip install -r requirements.txt && python agent.py
71
+ """
72
+
73
+ import os
74
+ import requests
75
+ from langchain.tools import tool
76
+ from langchain_openai import ChatOpenAI
77
+ from langchain.agents import AgentExecutor, create_openai_tools_agent
78
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
79
+
80
+ BASE = "https://simplefunctions.dev"
81
+
82
+ @tool
83
+ def world_state() -> str:
84
+ """Get real-time world state from prediction markets. ~800 tokens of calibrated probabilities."""
85
+ return requests.get(f"{BASE}/api/agent/world").text
86
+
87
+ @tool
88
+ def scan_markets(query: str) -> str:
89
+ """Search prediction markets (Kalshi + Polymarket) by keyword."""
90
+ r = requests.get(f"{BASE}/api/public/scan", params={"q": query})
91
+ return r.text
92
+
93
+ @tool
94
+ def get_trade_ideas() -> str:
95
+ """Get conviction-scored trade ideas from prediction market data."""
96
+ return requests.get(f"{BASE}/api/public/ideas").text
97
+
98
+ @tool
99
+ def get_market_detail(ticker: str) -> str:
100
+ """Get detailed info for a specific market ticker."""
101
+ return requests.get(f"{BASE}/api/public/market/{ticker}?depth=true").text
102
+
103
+ tools = [world_state, scan_markets, get_trade_ideas, get_market_detail]
104
+
105
+ prompt = ChatPromptTemplate.from_messages([
106
+ ("system", "You are a prediction market analyst. Use your tools to answer questions about world events, probabilities, and trading opportunities. Always cite specific market prices."),
107
+ MessagesPlaceholder("chat_history", optional=True),
108
+ ("human", "{input}"),
109
+ MessagesPlaceholder("agent_scratchpad"),
110
+ ])
111
+
112
+ llm = ChatOpenAI(model="gpt-4o", temperature=0)
113
+ agent = create_openai_tools_agent(llm, tools, prompt)
114
+ executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
115
+
116
+ if __name__ == "__main__":
117
+ result = executor.invoke({"input": "What are the highest-conviction trade ideas right now? Check the world state first."})
118
+ print("\\n" + result["output"])
119
+ `,
120
+ '.env.example': () => `OPENAI_API_KEY=sk-...
121
+ # Optional: SimpleFunctions API key for thesis features
122
+ # SF_API_KEY=sf_live_...
123
+ `,
124
+ },
125
+ },
126
+ crewai: {
127
+ name: 'CrewAI (Python)',
128
+ files: {
129
+ 'requirements.txt': () => `crewai>=0.80
130
+ crewai-tools>=0.14
131
+ requests>=2.31
132
+ `,
133
+ 'crew.py': () => `"""
134
+ Prediction Market Crew — CrewAI + SimpleFunctions
135
+ Run: pip install -r requirements.txt && python crew.py
136
+ """
137
+
138
+ import requests
139
+ from crewai import Agent, Task, Crew
140
+ from crewai_tools import tool
141
+
142
+ BASE = "https://simplefunctions.dev"
143
+
144
+ @tool("World State")
145
+ def world_state() -> str:
146
+ """Get real-time world state from 9,706 prediction markets."""
147
+ return requests.get(f"{BASE}/api/agent/world").text
148
+
149
+ @tool("Scan Markets")
150
+ def scan_markets(query: str) -> str:
151
+ """Search Kalshi + Polymarket by keyword."""
152
+ return requests.get(f"{BASE}/api/public/scan", params={"q": query}).text
153
+
154
+ @tool("Trade Ideas")
155
+ def get_trade_ideas() -> str:
156
+ """Get conviction-scored trade ideas."""
157
+ return requests.get(f"{BASE}/api/public/ideas").text
158
+
159
+ analyst = Agent(
160
+ role="Prediction Market Analyst",
161
+ goal="Identify the highest-conviction trading opportunities from prediction market data",
162
+ backstory="Senior analyst at a macro fund. Uses prediction market probabilities as leading indicators.",
163
+ tools=[world_state, scan_markets, get_trade_ideas],
164
+ verbose=True,
165
+ )
166
+
167
+ researcher = Agent(
168
+ role="Risk Researcher",
169
+ goal="Identify risks and counter-arguments for proposed trades",
170
+ backstory="Former risk manager. Always asks: what could go wrong?",
171
+ tools=[world_state, scan_markets],
172
+ verbose=True,
173
+ )
174
+
175
+ find_edges = Task(
176
+ description="Check the world state, then find the top 3 trade ideas. For each, scan related markets for confirmation.",
177
+ expected_output="3 trade recommendations with market evidence",
178
+ agent=analyst,
179
+ )
180
+
181
+ check_risks = Task(
182
+ description="For each trade recommendation, identify the top risk. Search for markets that would profit if the trade goes wrong.",
183
+ expected_output="Risk assessment for each trade",
184
+ agent=researcher,
185
+ )
186
+
187
+ crew = Crew(agents=[analyst, researcher], tasks=[find_edges, check_risks], verbose=True)
188
+
189
+ if __name__ == "__main__":
190
+ result = crew.kickoff()
191
+ print("\\n=== Final Output ===")
192
+ print(result)
193
+ `,
194
+ '.env.example': () => `OPENAI_API_KEY=sk-...
195
+ `,
196
+ },
197
+ },
198
+ mcp: {
199
+ name: 'MCP Agent (TypeScript)',
200
+ files: {
201
+ 'package.json': (name) => JSON.stringify({
202
+ name,
203
+ version: '0.1.0',
204
+ type: 'module',
205
+ scripts: { start: 'npx tsx agent.ts' },
206
+ devDependencies: { tsx: 'latest', typescript: 'latest' },
207
+ }, null, 2),
208
+ 'agent.ts': () => `/**
209
+ * MCP-connected Prediction Market Agent
210
+ *
211
+ * This agent connects to SimpleFunctions via MCP.
212
+ * For Claude Code: claude mcp add simplefunctions --url https://simplefunctions.dev/api/mcp/mcp
213
+ * For Cursor: add to .cursor/mcp.json
214
+ *
215
+ * This file demonstrates the REST API equivalent for custom agents.
216
+ */
217
+
218
+ const BASE = 'https://simplefunctions.dev'
219
+
220
+ // These match the 38 MCP tools available via SimpleFunctions
221
+ const tools = {
222
+ world: () => fetch(\`\${BASE}/api/agent/world\`).then(r => r.text()),
223
+ delta: (since: string) => fetch(\`\${BASE}/api/agent/world/delta?since=\${since}\`).then(r => r.text()),
224
+ scan: (q: string) => fetch(\`\${BASE}/api/public/scan?q=\${encodeURIComponent(q)}\`).then(r => r.json()),
225
+ ideas: () => fetch(\`\${BASE}/api/public/ideas\`).then(r => r.json()),
226
+ index: () => fetch(\`\${BASE}/api/public/index\`).then(r => r.json()),
227
+ contagion: (window = '6h') => fetch(\`\${BASE}/api/public/contagion?window=\${window}\`).then(r => r.json()),
228
+ market: (ticker: string) => fetch(\`\${BASE}/api/public/market/\${ticker}?depth=true\`).then(r => r.json()),
229
+ }
230
+
231
+ async function main() {
232
+ console.log(await tools.world())
233
+ console.log('\\n=== SF Index ===')
234
+ const idx = await tools.index()
235
+ console.log(\`Uncertainty: \${idx.index?.uncertainty} | Geo Risk: \${idx.index?.geopolitical} | Momentum: \${idx.index?.momentum}\`)
236
+ }
237
+
238
+ main().catch(console.error)
239
+ `,
240
+ '.cursor/mcp.json': () => JSON.stringify({
241
+ mcpServers: {
242
+ simplefunctions: { url: 'https://simplefunctions.dev/api/mcp/mcp' },
243
+ },
244
+ }, null, 2),
245
+ 'tsconfig.json': () => JSON.stringify({
246
+ compilerOptions: { target: 'ES2022', module: 'ESNext', moduleResolution: 'bundler', strict: true, esModuleInterop: true },
247
+ include: ['*.ts'],
248
+ }, null, 2),
249
+ },
250
+ },
251
+ }
252
+
253
+ async function main() {
254
+ console.log()
255
+ console.log(' create-prediction-market-agent')
256
+ console.log(' Scaffold a prediction market agent project powered by SimpleFunctions')
257
+ console.log()
258
+
259
+ const dirArg = process.argv[2]
260
+ const dir = dirArg || await ask(' Project name: ')
261
+ if (!dir) { console.log(' Cancelled.'); process.exit(0) }
262
+
263
+ console.log()
264
+ console.log(' Templates:')
265
+ const keys = Object.keys(TEMPLATES)
266
+ keys.forEach((k, i) => console.log(` ${i + 1}) ${TEMPLATES[k].name}`))
267
+ console.log()
268
+
269
+ const choice = await ask(` Choose template (1-${keys.length}) [1]: `)
270
+ const idx = Math.max(0, Math.min(keys.length - 1, parseInt(choice || '1', 10) - 1))
271
+ const template = TEMPLATES[keys[idx]]
272
+
273
+ const targetDir = join(process.cwd(), dir)
274
+ if (existsSync(targetDir)) {
275
+ console.log(`\n Error: ${dir} already exists.`)
276
+ process.exit(1)
277
+ }
278
+
279
+ mkdirSync(targetDir, { recursive: true })
280
+
281
+ for (const [file, gen] of Object.entries(template.files)) {
282
+ const filePath = join(targetDir, file)
283
+ const fileDir = join(filePath, '..')
284
+ mkdirSync(fileDir, { recursive: true })
285
+ writeFileSync(filePath, gen(basename(dir)))
286
+ }
287
+
288
+ // Always add README
289
+ writeFileSync(join(targetDir, 'README.md'), `# ${basename(dir)}
290
+
291
+ Prediction market agent powered by [SimpleFunctions](https://simplefunctions.dev).
292
+
293
+ ## Setup
294
+
295
+ ${keys[idx] === 'langchain' || keys[idx] === 'crewai'
296
+ ? '```bash\npip install -r requirements.txt\ncp .env.example .env # add your API keys\npython ' + (keys[idx] === 'crewai' ? 'crew' : 'agent') + '.py\n```'
297
+ : '```bash\nnpm install\nnpm start\n```'}
298
+
299
+ ## SimpleFunctions MCP
300
+
301
+ Connect Claude Code or Cursor directly:
302
+
303
+ \`\`\`bash
304
+ claude mcp add simplefunctions --url https://simplefunctions.dev/api/mcp/mcp
305
+ \`\`\`
306
+
307
+ ## Resources
308
+
309
+ - [SimpleFunctions Docs](https://simplefunctions.dev/docs)
310
+ - [Agent Guide](https://simplefunctions.dev/docs/guide)
311
+ - [Awesome Prediction Markets](https://github.com/spfunctions/awesome-prediction-markets)
312
+ `)
313
+
314
+ // Always add .gitignore
315
+ writeFileSync(join(targetDir, '.gitignore'), `node_modules/
316
+ .env
317
+ __pycache__/
318
+ *.pyc
319
+ dist/
320
+ `)
321
+
322
+ console.log()
323
+ console.log(` Created ${basename(dir)}/ with ${template.name} template`)
324
+ console.log()
325
+ console.log(` cd ${dir}`)
326
+ if (keys[idx] === 'langchain' || keys[idx] === 'crewai') {
327
+ console.log(' pip install -r requirements.txt')
328
+ console.log(` python ${keys[idx] === 'crewai' ? 'crew' : 'agent'}.py`)
329
+ } else {
330
+ console.log(' npm install')
331
+ console.log(' npm start')
332
+ }
333
+ console.log()
334
+
335
+ rl.close()
336
+ }
337
+
338
+ main().catch((e) => { console.error(e); process.exit(1) })
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "create-prediction-market-agent",
3
+ "version": "1.0.0",
4
+ "description": "Scaffold a prediction market agent project. LangChain, CrewAI, OpenAI Agents SDK, or vanilla TypeScript. Powered by SimpleFunctions.",
5
+ "bin": {
6
+ "create-prediction-market-agent": "./index.mjs"
7
+ },
8
+ "keywords": [
9
+ "create", "scaffold", "prediction-market", "prediction-market-agent",
10
+ "ai-agent", "langchain", "crewai", "openai-agents", "mcp",
11
+ "kalshi", "polymarket", "trading-bot", "world-state"
12
+ ],
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/spfunctions/create-prediction-market-agent"
17
+ },
18
+ "homepage": "https://simplefunctions.dev"
19
+ }