const candlestickData = require('./data.js'); class TradingEnvironment {…
- User
const candlestickData = require('./data.js');
class TradingEnvironment { constructor(data) { this.data = data; console.log(
Total number of candles: ${this.data.length}); this.initialCash = 10000; this.reset(); }reset() { this.currentStep = 0; this.cash = this.initialCash; this.sharesOwned = 0; this.done = false; return this.getState(); } getState() { if (this.currentStep >= this.data.length) { this.done = true; return null; } const candle = this.data[this.currentStep]; return [ parseFloat(candle[1]), // open parseFloat(candle[2]), // high parseFloat(candle[3]), // low parseFloat(candle[4]), // close parseFloat(candle[5]) // volume ]; } step(action) { if (this.done) { console.log("Episode already finished"); return { state: null, reward: 0, done: true }; } const currentPrice = parseFloat(this.data[this.currentStep][4]); // Closing price // Apply action if (action === 1) { // Buy const maxShares = Math.floor(this.cash / currentPrice); this.sharesOwned += maxShares; this.cash -= maxShares * currentPrice; console.log('Bought! Cash is ' + this.cash) } else if (action === 2) { // Sell this.cash += this.sharesOwned * currentPrice; this.sharesOwned = 0; console.log('Sold! Cash is ' + this.cash) } // Calculate reward before moving to next step const portfolioValue = this.cash + (this.sharesOwned * currentPrice); const reward = portfolioValue - this.initialCash; // Move to next step this.currentStep++; if (this.currentStep >= this.data.length) { this.done = true; } const nextState = this.getState(); return { state: nextState, reward, done: this.done }; } getCurrentPortfolioValue() { if (this.currentStep >= this.data.length) { return this.cash; // If we're at the end, just return the cash } const currentPrice = parseFloat(this.data[this.currentStep][4]); return this.cash + (this.sharesOwned * currentPrice); }}
const tf = require('@tensorflow/tfjs');
// Define the Q-network (policy network) function createQNetwork(inputShape, outputSize) { const model = tf.sequential(); model.add(tf.layers.dense({ units: 128, inputShape: inputShape, activation: 'relu' })); model.add(tf.layers.dense({ units: 128, activation: 'relu' })); model.add(tf.layers.dense({ units: outputSize })); // Output Q-values for each action (Buy, Sell, Hold) model.compile({ optimizer: 'adam', loss: 'meanSquaredError' }); return model; }
// Experience Replay (to improve learning) class ReplayBuffer { constructor(size) { this.buffer = []; this.size = size; }
add(experience) { if (this.buffer.length >= this.size) { this.buffer.shift(); // Remove the oldest experience } this.buffer.push(experience); }
sample(batchSize) { const sample = []; for (let i = 0; i < batchSize; i++) { const index = Math.floor(Math.random() * this.buffer.length); sample.push(this.buffer[index]); } return sample; } }
- Assistant