-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
265 lines (230 loc) · 7.75 KB
/
index.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { getHistoricalData, getHorses } from "./fs-utils";
import {
calculateChances,
convertFractionOddsToDecimal,
determineWinner,
generateLineUp,
} from "./utils";
export type Horse = {
name: string;
oddsNumerator: number;
oddsDenominator: number;
group: "favourites" | "outsiders" | "underdogs";
};
export const convertFractionOddsToPercentage = (
oddsNumerator: number,
oddsDenominator: number
): number => {
return oddsDenominator / (oddsNumerator + oddsDenominator);
};
export type LineUp = Horse[];
export const calculateNetWinnings = (
bet: { horse: Horse; amount: number },
winner: Horse
) => {
let winnings = 0;
if (bet.horse === winner) {
winnings =
bet.amount *
convertFractionOddsToDecimal(
bet.horse.oddsNumerator,
bet.horse.oddsDenominator
);
}
return winnings - bet.amount;
};
type getBet = (
lineUp: LineUp,
currentMoney: number
) => { horse: Horse; amount: number };
const playGame = (
getBet: getBet,
currentMoney: number,
horses: Horse[],
overrides?: { lineUp: LineUp; winner: Horse }
): number => {
const lineUp = overrides?.lineUp ?? generateLineUp(horses);
const bet = getBet(lineUp, currentMoney);
if (!bet.amount) throw new Error("bet amount not defined");
if (!bet.horse) throw new Error("bet horse not defined");
if (bet.amount > 10_000) throw new Error("bet amount too high");
if (bet.amount < 100) throw new Error("bet amount too low");
if (bet.amount % 100 !== 0) throw new Error("bet amount not multiple of 100");
if (bet.amount >= 1000 && bet.amount % 500 !== 0)
throw new Error("bet amount not multiple of 500");
// console.log(bet);
const winner = overrides?.winner ?? determineWinner(lineUp);
return calculateNetWinnings(bet, winner);
};
export const convertScientificNotationNumber = (value: number): string => {
const decimalsPart = value?.toString()?.split(".")?.[1] || "";
const eDecimals = Number(decimalsPart?.split("e-")?.[1]) || 0;
const countOfDecimals = decimalsPart.length + eDecimals;
return Number(value).toFixed(countOfDecimals);
};
export const getBetByReturns =
(log = false) =>
(lineUp: LineUp, currentMoney: number) => {
const order = [
5, 4, 3, 15, 14, 13, 12, 30, 29, 28, 27, 26, 25, 24, 10, 23, 22, 21, 20,
9, 19, 18, 17, 16, 8, 7, 6, 2, 1,
];
for (let i = 0; i < order.length; i++) {
const horse = lineUp.find((h) => h.oddsNumerator === order[i]);
if (horse) {
return {
horse,
amount: 10000,
};
}
}
throw new Error("no horse found");
};
export const getBetByOdds =
(log = false) =>
(lineUp: LineUp, currentMoney: number) => {
return {
horse: lineUp
.filter((x) => x.oddsNumerator !== 1)
.sort((a, b) => a.oddsNumerator - b.oddsNumerator)[0],
amount: 10000,
};
};
export const getBetKelly =
(log = false) =>
(lineUp: LineUp, currentMoney: number) => {
const kellyCriterion = (decimalOdds: number, actualProbability: number) =>
(decimalOdds * actualProbability - 1) / (decimalOdds - 1);
const chances = calculateChances(lineUp);
const kellyCriterions = chances.map((chance, i) => {
// if (chance === 0) return -Infinity;
return kellyCriterion(
convertFractionOddsToDecimal(
lineUp[i].oddsNumerator,
lineUp[i].oddsDenominator
),
chance
);
});
const maxKellyCriterion = Math.max(...kellyCriterions);
const maxKellyCriterionIndex = kellyCriterions.indexOf(maxKellyCriterion);
const horse = lineUp[maxKellyCriterionIndex];
const adjustedChance = chances[maxKellyCriterionIndex];
log &&
console.log(
`${convertScientificNotationNumber(
maxKellyCriterion
)},${convertScientificNotationNumber(
adjustedChance
)},${convertScientificNotationNumber(
convertFractionOddsToPercentage(
horse.oddsNumerator,
horse.oddsDenominator
)
)}`
);
const getAmount = () => {
if (maxKellyCriterion <= 0) {
// console.log("maxKellyCriterion <= 0, ", maxKellyCriterion);
return 100;
}
let amount = 0;
// const kellyAmount = Math.min(44_000, currentMoney) * maxKellyCriterion;
const kellyAmount = currentMoney * maxKellyCriterion;
amount = kellyAmount;
amount = Math.min(amount, 10_000);
if (amount < 1_000) amount = Math.ceil(amount / 100) * 100;
amount = Math.ceil(amount / 500) * 500;
return amount;
// return Math.min(amount, 50_000);
};
const amount = getAmount();
return {
horse,
amount,
};
};
export const getXthFavourite =
(
x = 0,
log = false,
chanceType: "proportionate" | "first-horse" | "equal" = "proportionate"
) =>
(lineUp: LineUp) => {
const favourite = lineUp.sort(
(a, b) =>
convertFractionOddsToDecimal(a.oddsNumerator, a.oddsDenominator) -
convertFractionOddsToDecimal(b.oddsNumerator, b.oddsDenominator)
)[x];
const amount = 10_000;
// console.log(lineUp, favourite);
const chances = calculateChances(lineUp, chanceType);
const adjustedChance = chances[lineUp.indexOf(favourite)];
const odds = convertFractionOddsToPercentage(
favourite.oddsNumerator,
favourite.oddsDenominator
);
log && console.log([odds, adjustedChance].join(","));
return {
horse: favourite,
amount,
};
};
export const main = async (getBet: getBet, showBalance = false) => {
let historicalData: Awaited<ReturnType<typeof getHistoricalData>> = [];
historicalData = await getHistoricalData("all");
const horses = await getHorses();
// const historicalData = shuffle(await getHistoricalData());
const totalGames = historicalData.length || 2000;
const startingMoney = 10_000_000;
let currentMoney = startingMoney;
showBalance && console.log(currentMoney);
for (let i = 0; i < totalGames; i++) {
const result = playGame(getBet, currentMoney, horses, historicalData[i]);
currentMoney += result;
// console.log(result);
showBalance && console.log(currentMoney);
if (currentMoney <= 0) {
console.log(`bankrupt in ${i} games`);
break;
}
}
console.log(
`${startingMoney.toLocaleString()} => ${Math.round(
currentMoney
).toLocaleString()}`
);
};
// basically the goal will be to find which horse will provide the closest match in bet for Kelly Criterion
function shuffle(array) {
let currentIndex = array.length,
randomIndex;
// While there remain elements to shuffle.
while (currentIndex > 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex],
];
}
return array;
}
// (async () => {
// // console.log("\n\n\nkelly -----------------------------------------------")
// await main(getBetKelly(false));
// // console.log("\n\n\nfavourite -----------------------------------------------")
// // await main(getXthFavourite(0));
// // console.log("\n\n\n2nd favourite -----------------------------------------------")
// // await main(getXthFavourite(1));
// // console.log("\n\n\n3rd favourite -----------------------------------------------")
// // await main(getXthFavourite(2));
// // console.log("\n\n\n4th favourite -----------------------------------------------")
// // await main(getXthFavourite(3));
// // console.log("\n\n\n5th favourite -----------------------------------------------")
// // await main(getXthFavourite(4));
// // console.log("\n\n\n6th favourite -----------------------------------------------")
// // await main(getXthFavourite(5));
// })();