Category: Finance & Trading

Quantitative finance and algorithmic trading

  • JavaScript Finance: Calculate ichimoku value

    Looking to enhance your trading strategy with JavaScript? The Ichimoku Kinko Hyo indicator, commonly known as the Ichimoku Cloud, is a powerful tool for identifying market trends and support/resistance levels. In this article, we’ll walk through how to calculate Ichimoku values in JavaScript and use them to make buy/sell decisions.

    Ichimoku Kinko Hyo is a comprehensive technical analysis indicator comprised of several components: Tenkan-sen (Conversion Line), Kijun-sen (Base Line), Senkou Span A (Leading Span A), Senkou Span B (Leading Span B), and Chikou Span (Lagging Span). Each component helps traders visualize momentum, trend direction, and potential reversal points.

    To compute Ichimoku values for a stock, you need to specify several parameters: the time frame, the number of periods for each component, and the stock price data. Here’s how you might define these parameters in JavaScript:

    // Define the time frame to use for the Ichimoku indicator (e.g. daily, hourly, etc.)
    const timeFrame = 'daily';
    
    // Define the number of periods to use for each of the Ichimoku components
    const conversionPeriod = 9;
    const basePeriod = 26;
    const spanAPeriod = 52;
    const spanBPeriod = 26;
    
    // Define the stock price for which to calculate the Ichimoku values
    const price = 123.45;
    
    // Initialize the Ichimoku Kinko Hyo indicator with the given parameters
    const ichimoku = initializeIchimoku({
      timeFrame,
      conversionPeriod,
      basePeriod,
      spanAPeriod,
      spanBPeriod,
    });
    

    With these parameters set, you can calculate the Ichimoku values for a given stock price. Below is an example implementation in JavaScript:

    const ichimoku = {
      // Define the Ichimoku parameters (fictional example)
      tenkanSen: 9,
      kijunSen: 26,
      senkouSpanB: 52,
      
      // Calculate the Ichimoku values for the given stock price
      calculate(params) {
        const { stock} = params;
        
        // Calculate the Tenkan-sen and Kijun-sen values
        const tenkanSen = (stock.highValues.slice(-this.tenkanSen).reduce((a, b) => a + b, 0) / this.tenkanSen)
        const kijunSen = (stock.lowValues.slice(-this.kijunSen).reduce((a, b) => a + b, 0) / this.kijunSen)
        
        // Calculate the Senkou Span A value
        const senkouSpanA = ((tenkanSen + kijunSen) / 2)
        
        // Calculate the Senkou Span B value
        const senkouSpanB = (stock.highValues.slice(-this.senkouSpanB).reduce((a, b) => a + b, 0) / this.senkouSpanB)
        
        // Calculate the Chikou Span value
        const chikouSpan = (this.prices[-this.senkouSpanB])
        
        // Return the calculated Ichimoku values
        return { tenkanSen, kijunSen, senkouSpanA, senkouSpanB, chikouSpan };
      }
    };
    
    // Calculate the Ichimoku values for the given stock price
    const ichimokuValues = ichimoku.calculate({ price });
    
    // Output the calculated Ichimoku values
    console.log('Tenkan-sen:', ichimokuValues.tenkanSen);
    console.log('Kijun-sen:', ichimokuValues.kijunSen);
    console.log('Senkou Span A:', ichimokuValues.senkouSpanA);
    console.log('Senkou Span B:', ichimokuValues.senkouSpanB);
    console.log('Chikou Span:', ichimokuValues.chikouSpan);
    

    In this example, the ichimoku.calculate() function receives an object containing the stock price and returns an object with the computed Ichimoku values. The function leverages the parameters defined in the ichimoku object and uses fictional historical data (such as this.highs and this.lows) for its calculations.

    To interpret the Ichimoku Cloud indicator and make trading decisions, focus on these key values:

    • Tenkan-sen: The average of the highest high and lowest low over the past 9 periods. If the price is above Tenkan-sen, the trend is up; below, the trend is down.
    • Kijun-sen: The average of the highest high and lowest low over the past 26 periods. Price above Kijun-sen indicates an uptrend; below signals a downtrend.
    • Senkou Span A: The average of Tenkan-sen and Kijun-sen, shifted forward 26 periods. Price above Senkou Span A suggests an uptrend; below, a downtrend.
    • Senkou Span B: The average of the highest high and lowest low over the past 52 periods, shifted forward 26 periods. Price above Senkou Span B means uptrend; below, downtrend.
    • Chikou Span: The current price shifted back 26 periods. If Chikou Span is above the price, it signals an uptrend; below, a downtrend.

    Traders typically look for a combination of these signals. For instance, if the price is above both Tenkan-sen and Kijun-sen, and Chikou Span is above the price, this is considered bullish—a potential buy signal. Conversely, if the price is below Tenkan-sen and Kijun-sen, and Chikou Span is below the price, it’s bearish—a potential sell signal. Remember, interpretations may vary among traders.

    function buySellDecision(ichimokuValues) {
    if (ichimokuValues.tenkanSen > ichimokuValues.kijunSen && ichimokuValues.chikouSpan > ichimokuValues.senkouSpanA) {
    return "buy";
    } else if (ichimokuValues.tenkanSen < ichimokuValues.kijunSen && ichimokuValues.chikouSpan < ichimokuValues.senkouSpanA) {
    return "sell";
    } else {
    return "hold";
    }
    }
    
    const decision = buySellDecision(ichimokuValues);
    console.log('Buy/Sell decision:', decision);
    
  • JavaScript Finance: Calculate RSI value

    Looking for a reliable way to spot market momentum and potential buy or sell signals? The Relative Strength Index (RSI) is a popular technical indicator that helps traders gauge whether an asset is overbought or oversold. In this article, you’ll learn how to calculate RSI using JavaScript, with clear explanations and practical code examples.

    To calculate the RSI value, you first need to compute the average gain and average loss over a specified number of periods. These values are then used to determine the relative strength and, ultimately, the RSI using the following formula:

    RSI = 100 – 100 / (1 + (average gain / average loss))

    Start by determining the price change for each period. If the price increases, the change is positive and added to the total gain. If the price decreases, the change is negative and added to the total loss. Calculate the average gain and average loss by dividing the total gain and total loss by the number of periods used for the RSI.

    For example, if you’re calculating RSI over 14 periods, compute the price change for each of the last 14 periods. If the price increased by $1 in a period, add that to the total gain; if it decreased by $1, add that to the total loss. Divide each total by 14 to get the average gain and average loss, then use the formula above to calculate the RSI.

    Remember, RSI is an oscillator that fluctuates between 0 and 100. An RSI above 70 is considered overbought, while below 30 is considered oversold. These thresholds can help identify potential buying and selling opportunities.

    function rsi(prices, period) {
      const gains = [];
      const losses = [];
    
      for (let i = 1; i < prices.length; i++) {
        const change = prices[i] - prices[i - 1];
        if (change > 0) {
          gains.push(change);
        } else {
          losses.push(change);
        }
      }
    
      const avgGain = average(gains.slice(0, period));
      const avgLoss = average(losses.slice(0, period).map(Math.abs));
      const rs = avgGain / avgLoss;
    
      return 100 - (100 / (1 + rs));
    }
    
    function average(values) {
      return values.reduce((total, value) => total + value) / values.length;
    }

    The code above calculates the RSI value for a given list of prices over a specified period. It computes the gains and losses for each price change, calculates the average gain and average loss, then determines the relative strength (RS) as the ratio of average gain to average loss. Finally, it calculates the RSI value using the standard formula.

    To use this code, simply call the rsi function with your price list and desired period, for example:

    const prices = [100, 105, 110, 115, 120, 130, 135];
    const period = 5;
    const rsiValue = rsi(prices, period);

    This will calculate the RSI value for the provided prices array over a period of 5. The resulting rsiValue will be a number between 0 and 100, indicating the relative strength of the asset. Values below 30 suggest oversold conditions, while values above 70 indicate overbought conditions.

    function rsiBuySellDecision(rsi) {
      if (rsi < 30) {
        return 'BUY';
      } else if (rsi > 70) {
        return 'SELL';
      } else {
        return 'HOLD';
      }
    }
    

    Keep in mind, this is a basic example and RSI thresholds for buy or sell decisions may vary depending on your trading strategy. RSI should not be used in isolation; it’s best combined with other indicators and market analysis for more reliable results.