Function to simulate stochastic oscillator for algorithmic trading

Loading data from Talking to Chatbots Dataset reddgr/talking-to-chatbots-chats

😎 Write a function that simulates a stochastic oscillator for algorithmic trading
🤖
javascript
function stochasticOscillator(prices, kPeriod = 14, dPeriod = 3) {
  let kValues = [];
  let dValues = [];
  let stochastics = [];

  for (let i = 0; i < prices.length; i++) {
    if (i >= kPeriod - 1) {
      const highMax = Math.max(...prices.slice(i - kPeriod + 1, i + 1).map(p => p.high));
      const lowMin = Math.min(...prices.slice(i - kPeriod + 1, i + 1).map(p => p.low));
      const close = prices[i].close;
      const k = ((close - lowMin) / (highMax - lowMin)) * 100;
      kValues.push(k);

      if (kValues.length >= dPeriod) {
        const d = kValues.slice(-dPeriod).reduce((acc, val) => acc + val, 0) / dPeriod;
        dValues.push(d);

        stochastics.push({ k, d });
      } else {
        stochastics.push({ k, d: null });
      }
    } else {
      stochastics.push({ k: null, d: null });
    }
  }

  return stochastics;
}



This function takes an array of price objects (`prices`), where each object has `high`, `low`, and `close` properties. It calculates the stochastic oscillator values, given a `kPeriod` and a `dPeriod`. The function returns an array of objects, where each object contains the `%K` and `%D` values for each corresponding price point, with `null` for those periods where the calculation cannot be performed.

Hugging Face Dataset Metrics

All the conversation prompts, responses, and metrics are available to download and explore on Hugging Face dataset reddgr/talking-to-chatbots-chats: