case-market_kelly_bet.web.val.run
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { z } from "npm:zod";
const paramsSchema = z.object({
slug: z.coerce.string(),
estimatedProb: z.coerce.number().min(0).max(1),
bankroll: z.coerce.number().min(0),
deferenceFactor: z.coerce.number().min(0).max(1).optional().default(0.5),
});
// Copied from https://github.com/Will-Howard/manifolio/blob/master/manifolio-ui/lib/calculate.ts
function calculateNaiveKellyBet({
marketProb,
estimatedProb,
deferenceFactor,
bankroll,
}: { marketProb: number; estimatedProb: number; deferenceFactor: number; bankroll: number }): {
amount: number;
outcome: "YES" | "NO";
} {
const outcome = estimatedProb > marketProb ? "YES" : "NO";
const marketWinProb = outcome === "YES" ? marketProb : 1 - marketProb;
// kellyFraction * ((p - p_market) / (1 - p_market))
const fraction = deferenceFactor
* (Math.abs(estimatedProb - marketProb) / (1 - marketWinProb));
// clamp fraction between 0 and 1
const clampedFraction = Math.min(Math.max(fraction, 0), 1);
const amount = bankroll * clampedFraction;
return {
amount,
outcome,
};
}
async function getMarket(slug: string) {
const res = await fetch(`https://api.manifold.markets/v0/slug/${slug}`);
if (!res.ok) {
const body = await res.text();
throw new Error(body ?? "Error fetching market");
}
return res.json();
}
export default async function(req: Request): Promise<Response> {
const searchParams = new URL(req.url).searchParams;
const params = paramsSchema.parse(Object.fromEntries(searchParams.entries())) as z.infer<typeof paramsSchema>;
const market = await getMarket(params.slug);
const kelly = calculateNaiveKellyBet({
marketProb: market.probability,
estimatedProb: params.estimatedProb,
deferenceFactor: params.deferenceFactor,
bankroll: params.bankroll,
});
return Response.json(kelly);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
February 14, 2024