This repository was archived by the owner on Oct 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path002-train.ts
More file actions
72 lines (60 loc) · 1.7 KB
/
002-train.ts
File metadata and controls
72 lines (60 loc) · 1.7 KB
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
import candleData from "./candleSticks.json";
import * as tf from "@tensorflow/tfjs-node";
import { Ohlc } from "./999-functions";
import { TRAIN_TICKS_WINDOW, targetToken } from "./000-config";
async function trainModel(
trainX: number[][],
trainY: number[]
): Promise<tf.LayersModel> {
const tensorX = tf.tensor2d(trainX);
const tensorY = tf.tensor1d(trainY);
const model = tf.sequential();
model.add(
tf.layers.dense({
inputShape: [tensorX.shape[1]],
units: 64,
activation: "relu",
})
);
model.add(tf.layers.dense({ units: 32, activation: "relu" }));
model.add(tf.layers.dense({ units: 1 }));
model.compile({
optimizer: tf.train.adam(),
loss: tf.losses.meanSquaredError,
});
await model.fit(tensorX, tensorY, {
batchSize: 32,
epochs: 500,
shuffle: true,
verbose: 1,
});
return model;
}
function preprocessData(candleData: Ohlc[]): {
trainX: number[][];
trainY: number[];
} {
const trainX: number[][] = [];
const trainY: number[] = [];
const volatilities = candleData.map(
(candle) =>
(Number(candle.high) - Number(candle.low)) /
Math.pow(10, targetToken.decimals)
);
const windowSize = TRAIN_TICKS_WINDOW;
for (let i = 0; i < candleData.length - windowSize - 1; i++) {
const window = volatilities.slice(i, i + windowSize);
const next = volatilities[i + windowSize];
trainX.push(window);
trainY.push(next);
}
return { trainX, trainY };
}
async function main() {
const { trainX, trainY } = preprocessData(candleData as Ohlc[]);
console.log("Training model...");
const model = await trainModel(trainX, trainY);
console.log("Model trained.");
await model.save("file://./model");
}
main();