Formulas for Studies and Attribute Server Macros

Studies and server macros are listed together in the Studies window (select the Studies button to access the list).

The server macros have a Macro Code description.

% move

% move is the difference, expressed as a percentage, between a specified starting value and an ending specified value.

If either X or Xn is a NaN, the immediately preceding value will be considered instead, i.e., X1 or Xn+1. If these values are also NaN, the percent move will be NaN as well. For example, when computing a 2 day percent move, if X is a NaN, but X2 is not, then XMIM will return X1 – X2 instead of X – X2. But, if X1 is also NaN, then XMIM will return NaN.

Percent move is negative precisely when the move is negative; i.e., the percent move from -10 to -12 is -20, not 20.

Example 1:

   SHOW 
     t+5: percent_move from today to 5 values later  of NG  
     t+10: percent_move from today to 10 values later  of NG  
   WHEN 
       1 value percent_move of NG  is up 
     AND 
       1 value percent_move of HO  is less than -5

Example 2:

   SHOW 
     Dow-SP500: 1 value percent_move of DJIA  - 1 value percent_move of SPX  
     Dow: 1 value percent_move of DJIA  
     SP: 1 value percent_move of SPX  
     t+1: percent_move from today to 1 value later  of DJIA  
     t+2: percent_move from today to 2 values later  of DJIA  
   WHEN 
       Date is within 10 years 
     AND 
       
       (1 value percent_move of DJIA  - 1 value percent_move of SPX 
       ) is at least 1.00

absolute_value

This study returns the absolute value for a specified attribute. Where the value is a holiday or missing data series (expressed as NaN) the return will be NaN.

If X is NaN, absolute_value returns NaN as well.

Example:

   SHOW 
     dyn: Close of DYN 
     abVal: absolute_value of percent_move from today to 3 months later  of 
            Close of DYN   
   WHEN 
       Date is within 5 years 
     AND 
       1 day percent_move of Close of DYN  is more than 10 

AccDist

The accumulation/distribution is a momentum indicator that associates changes in price with the daily range. Divergences between the accumulation/distribution and the security's price imply a change is imminent. When a divergence does occur, prices usually change to confirm the accumulation/distribution. For example, if the indicator is moving up and the security's price is going down, prices will probably reverse and start going up. If the days price change is positive then the difference in the daily high and low price is added to the total, and conversely if the daily change is negative then the daily range is subtracted from the total.

AccDist (Series)

Example: AccDist (DELL)

   SHOW 
     1: AccDist ( DELL )  
   WHEN 
       Date is after 2002

Macro Code:

COLUMN MACRO AccDist ( SECURITY Sec )
    RETURN
        Sum from begin_of_time to today of
           if Close of Sec > Close of Sec 1 unit ago then
               absolute_value ( Close of Sec -
                           if Low of Sec < Close of Sec 1 unit ago
                                then Low of Sec
                                else Close of Sec 1 unit ago
                           endif )
           else
               if Close of Sec < Close of Sec 1 unit ago then
                    0 - 
                    absolute_value ( Close of Sec -
                           if High of Sec > Close of Sec 1 unit ago
                                then High of Sec
                                else Close of Sec 1 unit ago
                           endif )
           else
              0
           endif
        endif
ENDMACRO

adjust_contract

XMIM will adjust all studies using futures contract so that the artificial price jump associated with the expiration of a contract will not be factored into the study. For example, if a study using the front continuous contract captured a time period which included a roll or expiration date, by default, that price difference between the old or expiring contract and the new contract would be subtracted or backed out of the equation as of the expiration date. The adjust_contract function is used so that the jump or price difference associated with expiration (cost of carry) is not adjusted out of the study.

There are four fields that are required to be specified within this study—the attribute or series, the deferred number of the contract chosen (i.e., 1 represents the contract nearest to expiration or the front contract, 2 represents the second nearest contract to expiration, etc.), the number of days until expiration that the contract should be followed (i.e., 0 specifies that the contract will be active until expiration, 1 specifies that the contract will be active or followed up until 1 day before expiration, etc.) and contract month which is the parameter which specifies the contract month of interest (i.e., Setting the field to 0 will disable this field thereby allowing the contract to roll to the regularly traded serial months, setting the field to 1 will specify only January contracts, etc.).

where is computed by offsetting each relation of type futures in X with an appropriate amount so that the expiration-day boundaries do not introduce an artificial jump.

Example 1:

Consider the trading day of 10/8/2002 for the following scenarios.

The “prompt” crude oil contract would be Nov 2002, CL_2002X .

DateLIM SYMBOLadjust_contract version

10/8/2002

CL_2002Z - Close

adjust 1st December contract out

adjust_contract (CL, 1, 0, 12)

29.51

29.51

CL_2003J - Close

adjust 6th contract month out

adjust_contract (CL, 6, 0, 0)

27.6

27.6

CL_2004H - Close

adjust 2nd March contract out

adjust_contract (CL, 2, 0, 3)

23.86

23.86

CL_2005F - Close

adjust 3rd January contract out

adjust_contract (CL, 3, 2, 1)

23.03

23.03

Let’s look closer at each of these to see how the adjust_contract function chooses the correct contract.

December 2002 contract: This is the nearest December contract right now. The explicit LIM symbol is CL_2002Z. To ask for the closest contract month using adjust_contract you fill in adjust_contract (CL, 1, 0, 12), where:

  • CL = base commodity symbol of choice.

  • 1 = N nearest. 3 would imply the 3rd nearest, 6 the 6th nearest.

  • 0 = This is “Number of days before Expiration”. Setting this number to “0” indicates the series will locate the next nearest contract when the contract expires. Setting this number to “4” would mean that the contract should roll to the next one 4 days before expiration of the current contract.

  • 12 = This is the contract month, 12 equals December, 5 equals May, 7 equals July. Note: Setting this number to “0” makes the parameter inactive, meaning the other parameters will determine the behavior.

April 2003 contract: This is the 6th nearest contract out. The explicit LIM symbol is CL_2003J. To ask for the literal N contract out using adjust_contract, you fill in adjust_contract (CL, 6, 0, 0), where:

  • CL= base commodity symbol of choice.

  • 6 = N nearest. 6 points to the 6th closest or nearest to expiration active contract.

  • 0 = This is “Number of days before Expiration”. Setting this to “0” indicates the series will locate the next nearest contract when the contract expires. Setting this to “4” would mean that the contract should roll to the next one 4 days before expiration of the current contract.

  • 0 = Normally, this is where you put in the contract month. However, since we want the exact 6th closest contract, this is set to “0”.

March 2004 contract: This is the 2nd nearest March contract. The 1st nearest is the March 2003 contract. The 3rd nearest would be March 2005. To ask for the 2nd nearest March using adjust_contract, you would fill in adjust_contract (CL, 2, 0, 3) where:

  • CL = base commodity symbol of choice.

  • 2 = 2nd nearest

  • 0 = This is “Number of days before Expiration”. Setting this to “0” indicates the series will locate the next nearest contract when the contract expires.

  • 3 = March contract.

January 2005 contract: This is the 3rd nearest January contract. The closest or first nearest would be January 2003. To ask for the 3rd nearest using adjust_contract, you will fill in adjust_contract (CL, 3, 2, 1), where:

  • CL = base commodity symbol of choice

  • 3 = 3rd nearest

  • 2 = This is “Number of days before Expiration”. Setting this to “2” indicates the series will roll 2 days before the contract expires and choose the next 3rd nearest contract.

  • 1 = January contract.

Example 2: More Real-World Examples

How do you ask for?

  1. Spread between the 2nd December and the 1st December contract. Often times this is referred to as a Dec – Red Dec spread. adjust_contract (CL, 1, 0, 12) – adjust_contract (CL, 2, 0, 12)

  2. The spread between the 1st and 2nd nearby contracts. adjust_contract (CL, 1, 0, 0) – adjust_contract (CL, 2, 0, 0)

  3. The 3rd nearest November contract. adjust_contract (CL, 3, 0, 11)

  4. The 15th closest contract out. adjust_contract (CL, 15, 0, 0)

Aspect

Returns the difference in ecliptic longitude degrees between any two planets (except Earth). Choose planets (including Sun & Moon) relations from the “Other>Astronomy” menu in the Search Database window.

Aspect (Planet1, Planet2)

Example:

   SHOW 
     SOL: Aspect ( MERCURY, SOL )  
     MERCURY: Aspect ( MERCURY, MERCURY )  
     VENUS: Aspect ( MERCURY, VENUS )  
     MARS: Aspect ( MERCURY, MARS )  
     JUPITER: Aspect ( MERCURY, JUPITER )  
     SATURN: Aspect ( MERCURY, SATURN )  
     NEPTUNE: Aspect ( MERCURY, NEPTUNE )  
     URANUS: Aspect ( MERCURY, URANUS )  
     PLUTO: Aspect ( MERCURY, PLUTO )  
   WHEN 
       Date is 2002

Macro Code:

ATTR MACRO Aspect (SECURITY Planet1, SECURITY Planet2)
  VARS
      deg_diff
  INITIALIZE
      deg_diff = Longitude of Planet1 - Longitude of Planet2
  RETURN
      If
         absolute_value ( deg_diff ) is more than 180
      Then
         360 - absolute_value ( deg_diff )
      Else
         absolute_value ( deg_diff )
      EndIf
ENDMACRO

AspectEquatorial

Returns the difference in equatorial right ascension between any two planets (except Earth, the Sun, or the Moon).

AspectEquatorial (Planet1, Planet2)

Example:

   SHOW 
     MERCSAT: AspectEquatorial ( MERCURY, SATURN )  
     DJIA: percent_move from today to 3 months later  of DJIA  
   WHEN 
       Date is within 10 years 
     AND 
       AspectEquatorial ( MERCURY, SATURN )  crosses below 50

Macro Code:

ATTR MACRO AspectEquatorial (SECURITY Planet1, SECURITY Planet2)
   VARS
      r_a_diff
      deg_diff
   INITIALIZE 
         r_a_diff =  RightAscension of Planet1 - RightAscension of Planet2
      AND
         deg_diff = ( 15 * RightAscension of Planet1 ) -
                   ( 15 *  RightAscension of Planet2 )
   RETURN
      If
         absolute_value ( r_a_diff )
         is more than 12
      Then
         360 - absolute_value ( deg_diff )
      Else
         absolute_value ( deg_diff )
      EndIf
ENDMACRO

AspectHelio

Returns the difference in heliocentric longitude between any two planets.

AspectHelio (Planet1, Planet2)

Example:

   SHOW 
     SATEARTH: AspectHelio ( SATURN, EARTH )  
     DJIA: percent_move from today to 2 months later  of DJIA  
   WHEN 
       Date is within 10 years 
     AND 
       AspectHelio ( SATURN, EARTH )  crosses above 150 
     AND 
       Date is before April

Macro Code:

ATTR MACRO AspectHelio (SECURITY Planet1, SECURITY Planet2)
  VARS
      deg_diff
  INITIALIZE
      deg_diff = HelioLong of Planet1 - HelioLong of Planet2
  RETURN
      If
         absolute_value ( deg_diff ) is more than 180
      Then
         360 - absolute_value ( deg_diff )
      Else
         absolute_value ( deg_diff )
      EndIf
ENDMACRO

AspectPlot

The following are all used in the same manner. These all plot vertical lines on the chart on days when any astrological aspect is in force. Astrologers are especially interested in the locations of solar system objects relative to other solar system objects - numbers called "aspect" angles with the centers of the Earth or Sun (depending on which coordinate system, geocentric or heliocentric, is used) located at the vertex of the measured angle. Significant aspect angles have names associated with them listed below in order of supposed importance and influence, along with the Orb - the number of degrees of tolerance often used with the aspect, and the usual symbols used to denote the angles in printed Ephemeris tables.

The following are all used in the same manner. These all plot vertical lines on the chart on days when any astrological aspect is in force. Astrologers are especially interested in the locations of solar system objects relative to other solar system objects - numbers called "aspect" angles with the centers of the Earth or Sun (depending on which coordinate system, geocentric or heliocentric, is used) located at the vertex of the measured angle. Significant aspect angles have names associated with them listed below in order of supposed importance and influence, along with the Orb - the number of degrees of tolerance often used with the aspect, and the usual symbols used to denote the angles in printed Ephemeris tables.

No. glyphsAspectAbbrev.Aspect angleOrb (tolerance)Description of standard

1

Conjunct

(Con)

0.00

+/-7 deg.

Circle with extending line

2

Opposite

(Opp)

180.00

+/-7 deg.

Two circles joined by line

3

Square

(Squ)

90.00

+/- 7 deg.

Quadrilateral

4

Trine

(Tri)

120.00

+/- 7 deg.

Triangle

5

Sextile

(Sex)

60.00

+/- 6 deg.

Six pointed asterisk

6

Inconjunct

(Inc)

150.00

+/- 3 deg.

'K' rotated clockwise

7

Semisextile

(Ssx)

30.00

+/- 3 deg.

'K' rotated counter-clockwise

8

Semisquare

(Ssq)

45.00

+/- 3 deg.

Acute angle

9

Sesquisquare

(Ses)

135.00

+/- 3 deg.

Square with extending lines

Minor Aspects (not included in macro set - use "AspectX" macros which let you specify any arbitrary aspect angle.)

  • PlotAspectX (Planet1, Planet2, aspect, orb)

  • PlotConjunct (Planet1, Planet2, orb)

  • PlotInconjunct (Planet1, Planet2, orb)

  • PlotOpposite (Planet1, Planet2, orb)

  • PlotSemisextile (Planet1, Planet2, orb)

  • PlotSemisquare (Planet1, Planet2, orb)

  • PlotSesquisquare (Planet1, Planet2, orb)

  • PlotSextile (Planet1, Planet2, orb)

  • PlotSquare (Planet1, Planet2, orb)

  • PlotTrine (Planet1, Planet2, orb)

Example: Sample Query - Graphing

%graph.report.title:"Aspects of SATURN & MARS vs. Corn Prices" 
%graph.back.color:"black" 
%graph.plot.colors:"red yellow green cyan white magenta orange pink " 
%graph.graphtype:"Conjunct"line
%graph.graph.title:"Conjunct""Conjunct"
%graph.graph.title:"Opposite""Opposite"
%graph.scalewith:"Opposite""Conjunct"
%graph.graph.title:"Square""Square"
%graph.scalewith:"Square""Conjunct"
%graph.graph.title:"Trine""Trine"
%graph.scalewith:"Trine""Conjunct"
%graph.graph.title:"Sextile""Sextile"
%graph.scalewith:"Sextile""Conjunct"
%graph.graph.title:"Inconjunct""Inconjunct"
%graph.scalewith:"Inconjunct""Conjunct"
%graph.graph.title:"Semisextile""Semisextile"
%graph.scalewith:"Semisextile""Conjunct"
%graph.graph.title:"Semisquare""Semisquare"
%graph.scalewith:"Semisquare""Conjunct"
%graph.graph.title:"Sesequisqu""Sesequisqu"
%graph.scalewith:"Sesequisqu""Conjunct"
%graph.graph.title:"Aspect""Aspect"
%graph.linewidth:"Aspect"3
%graph.scalewith:"Aspect""Conjunct"
#>>Show-When<<  
   SHOW 
     Corn: Close of C 
     Conjunct: PlotConjunct ( SATURN, MARS, 0 )  
     Opposite: PlotOpposite ( SATURN, MARS, 0 )  
     Square: PlotSquare ( SATURN, MARS, 0 )  
     Trine: PlotTrine ( SATURN, MARS, 0 )  
     Sextile: PlotSextile ( SATURN, MARS, 0 )  
     Inconjunct: PlotInconjunct ( SATURN, MARS, 0 )  
     Semisextile: PlotSemisextile ( SATURN, MARS, 0 )  
     Semisquare: PlotSemisquare ( SATURN, MARS, 0 )  
     Sesequisqu: PlotSesquisquare ( SATURN, MARS, 0 )  
     Aspect: Aspect ( SATURN, MARS )  
   WHEN 
       Date is within 10 years

average

Calculates a simple moving average of values in the specified time period.

When calculating an N day average, XMIM will display a moving N day average for any executable date; however, where there is a holiday or missing data point (expressed as NaN) a moving average of less than N days will be displayed. For example, if a 5 day average was calculated and our executable dates include December 25, a holiday, the study would calculate a 4 day average for this date because no data point exists for December 25. Likewise, on December 26 a 4 day average will be displayed because of the missing data associated with the holiday. On December 25, a 5 value average will display (NaN) because no data exists to perform the calculation. However on December 26, or the next date where data exists, the study include the data on December 26 and will search back for the other 4 values to perform the calculation (skipping over December 25). To ensure that N actual ‘values’ are used in the calculation the term value should be substituted instead of day in the formula.

Example:

   SHOW 
     50day: 50 day average of front SP  
     200day: 200 day average of front SP  
     t+1: percent_move from today to 1 month later  of front SP  
     t+2: percent_move from today to 2 months later  of front SP  
   WHEN 
       50 day average of front SP  crosses above 200 day average of front SP

BackContract

Returns the price of the back contract. This functionality is now built into the language itself. The default selection for a parent futures contract (e.g., US) is the front continuous contract. You can specify the contract by manually typing "front", "back" or "far" prior to the future symbol name (e.g., 1 month average of Close of front NG, or Close of back US).

BackContract (Series, NumDays, ContractMth)

Example:

   SHOW 
     macro: BackContract ( NG, 0, 0 )  
     xmimlanguage: back NG 
   WHEN 
       Date is within 2 months

Macro Code:

ATTR MACRO BackContract (ATTR Series, CONSTANT NumDays = 0,
                CONSTANT ContractMth = 0)
    RETURN
          adjust_contract (Series, 2, NumDays, ContractMth)
ENDMACRO

BlackScholesOptionPrice

This macro computes the option price based on the Black Scholes model for a European option. The following shows the formula for computing the Black Scholes model:

Theoretical option price =

where

The variables are:

  • p = stock price

  • s = striking price

  • t = time remaining until expiration, expressed as a percent of a year

  • r = current risk-free interest rate

  • v = volatility measured by annual standard deviation

  • 1n = natural logarithm

  • N(x) = cumulative normal density function

BlackScholesOptionPrice (ATTR @underlying_price, ATTR @strike, ATTR @interest_rate, ATTR @sigma, ATTR @days_expiration, CONSTANT @is_call)

The interest rate must be expressed as a decimal fraction. For example, 2% will be 0.02. The sigma argument must also be expressed as decimal fraction: e.g., 16% is 0.16. The days to expiration are in actual days and will be divided by 365 to convert to fractions of a year. For a 252 day year adjust the days input by 365/252.

Example:

The following is a sample query using S&P futures options:

   SHOW 
     settle: Close of SP_2004Z.C1100 
     m: BlackScholesOptionPrice ( Close of SP_2004Z, 1100, FRH_DGS1 / 100, 
        (30 day std_dev of Close of SP_2004Z 
        ) / 100, periods_in_range from today to SP_2004Z.C1100  last_data_day, 
        1 )  
     s: Close of SP_2004Z 
     x: 1100 
     r: FRH_DGS1 / 100 
     sigma: 30 day std_dev of Close of SP_2004Z  
     t: periods_in_range from today to SP_2004Z.C1100  last_data_day  
   WHEN 
       Date is 11/7/2004

Macro Code:

ATTR MACRO BlackScholesOptionPrice (ATTR @underlying_price, ATTR @strike, ATTR @interest_rate, ATTR @sigma, ATTR @days_expiration, CONSTANT @is_call) VARS
    @S @X @r @days_exp @time_sqrt @e @d1 @d2 INITIALIZE
       @S = @underlying_price
     AND
       @X = @strike
     AND
       @r = @interest_rate
     AND
       @days_exp = (@days_expiration / 365)
     AND
       @time_sqrt = @days_exp ** 0.5
     AND
       @e = 2.7182818284590455349
     AND
       @d1 =
       (
         (natural_log ( @S / @X ) + @r * @days_exp) / (@sigma * @time_sqrt
         )) + (0.5 * @sigma * @time_sqrt)
     AND
       @d2 = @d1 - (@sigma * @time_sqrt) RETURN
       IF @is_call > 0 THEN
          @S * NormalDist ( @d1 )  - @X * @e ** (-1 * @r * @days_exp) * NormalDist ( @d2 )
       ELSE
           -1.0 * @S * NormalDist ( -1.0 * @d1 )  + @X
* @e ** (-1 * @r * @days_exp) * NormalDist ( -1.0 *
@d2 )
       ENDIF
ENDMACRO

bollinger_high/bollinger_low

bollinger_high and bollinger_low studies return values that are derived from a moving average plus (high) or minus some relative percent of the moving average. The relative value, subtracted or added to the moving average, is the standard deviation for the time window. These price bands can be defined so that they encompass most of the price activity with the ceiling (bollinger_high) coinciding with the relative highs and the floor (bollinger_low) coinciding with relative lows. These significant high and low thresholds can be used to measure overbought or oversold levels in the market. There are three fields that are required to be specified within this study- the Attribute or series, the relevant time period for the study and the width of the band (1 denotes 1 standard deviation, 2 denotes 2 standard deviations and 3 denotes 3 standard deviations).

Example 1:

   SHOW 
     21V: percent_move from today to 21 values later  of S  
   WHEN 
       S crosses above bollinger_high ( S, 20 units, 2 ) 
     AND 
       1 day percent_move of S  is more than 2.5

Example 2:

   1: ORDER 
     1.1: Buy 1 contract of AAPL 
       Enter on the market 
   WHEN 
       AAPL crosses below bollinger_low ( AAPL, 20 units, 2 ) 
     AND 
       simple_rsi ( AAPL, 26 days ) is less than 35 
     AND 
       Date is within 5 years 
   EXIT 
       AAPL crosses above bollinger_high ( AAPL, 20 units, 2 )

BollingerBandHighSDP / BollingerBandLowSDP

BollingerBandHighSDP and BollingerBandLowSDP are the same as the bollinger_high and bollinger_low studies except that the standard deviation population is used instead of the standard deviation as the relative value, subtracted or added to the moving average. There are three fields that are required to be specified within this study- the Attribute or series, the relevant time period for the study and the width of the band (1 denotes 1 standard deviation, 2 denotes 2 standard deviations and 3 denotes 3 standard deviations).

BollingerBandHighSDP (Series, TimePeriod, Width)

BollingerBandLowSDP (Series, TimePeriod, Width)

Example 1:

   SHOW 
     21V: percent_move from today to 21 values later  of S  
   WHEN 
       S crosses above BollingerBandHighSDP ( S, 20 values, 2 ) 
     AND 
       1 day percent_move of S  is more than 2.5

Example 2:

   1: ORDER 
     1.1: Buy 1 contract of AAPL 
       Enter on the market 
   WHEN 
       AAPL crosses below BollingerBandLowSDP ( AAPL, 20 values, 2 )
     AND 
       simple_rsi ( AAPL, 26 days ) is less than 35 
     AND 
       Date is within 5 years 
   EXIT 
       AAPL crosses above BollingerBandHighSDP ( Close of AAPL, 20 values, 2 )

Macro Code:

ATTR MACRO BollingerBandHighSDP ( ATTR Series, PERIOD TimePeriod = 20 day, CONSTANT Width )

 RETURN
(TimePeriod average of Series)+ Width * (TimePeriod std_dev_pop of Series)

ENDMACRO

Macro Code:

ATTR MACRO BollingerBandLowSDP ( ATTR Series, PERIOD TimePeriod = 20 day, CONSTANT Width )

 RETURN
(TimePeriod average of Series)- Width * (TimePeriod std_dev_pop of Series)

ENDMACRO

builtin_vwap

This study is currently under development.

ChannelIndex

Returns an index of Bollinger bands, a statistical version of the stochastic. Donald Lambert developed this price momentum indicator - Commodity Channel Index (CCI). It shows how the most recent close relates to the standard deviation range over the recent time period.

ChannelIndex (Series, TimePeriod)

Example:

   SHOW 
     HLT: Close of HLT 
     CCI: ChannelIndex ( HLT, 20 days )  
     t+1: percent_move from today to 1 week later  of HLT  
   WHEN 
       Date is within 2 years 
     AND 
       ChannelIndex ( HLT, 20 days )  crosses below -120

Macro Code:

ATTR MACRO ChannelIndex ( SECURITY Sec, PERIOD TimePeriod )
    DEFINED OVER TimePeriod
    VARS
    MidPt
    Mid0
    MidAvg
    MidDeviation
    Num
    INITIALIZE
    MidPt := ( High of Sec + Low of Sec + Close of Sec ) / 3
      AND
    MidAvg := MovingAvg ( ( High of Sec + Low of Sec + Close of Sec ) / 3,
                       TimePeriod )
      AND
    forall
        Mid0 := ( High of Sec + Low of Sec + Close of Sec ) / 3
      AND
        Mid0 is defined
      AND
        MidDeviation := MidDeviation +
                       if Mid0 > MidAvg then
                          Mid0 - MidAvg
                       else
                          MidAvg - Mid0
                       endif
      AND
        Num := Num + 1
    endfor
      AND
MidDeviation := MidDeviation / Num
    RETURN
    ( MidPt - MidAvg ) / ( .015 * MidDeviation )
ENDMACRO

ChoppinessIndex

Returns an indicator that measures the sum of all the ranges in a time period to the range over the time period as a measure of the trendiness or choppiness of a price series. Inspired by chaos theory, it is similar to Wilder's Directional Movement Index but with simpler calculations and less lag. The Choppiness Index varies between 0 and 100, the higher the index the choppier the price action is and the lower the index the more trending the price action.

ChoppinessIndex (Series, TimePeriod)

Example:

   SHOW 
     ORCL: Close of ORCL 
     CI: ChoppinessIndex ( ORCL, 14 days )  
     t+1: percent_move from today to 1 week later  of ORCL  
   WHEN 
       Date is within 1 year 
     AND 
       ChoppinessIndex ( ORCL, 14 days )  is exactly 10 day lowest of 
       ChoppinessIndex ( ORCL, 14 days )

Macro Code:

ATTR MACRO ChoppinessIndex ( SECURITY Sec, PERIOD TimePeriod )
    VARS
    n_high
    n_low
    n_range
    INITIALIZE
      n_high := TimePeriod highest of if High of Sec > Close of Sec 1 unit ago
                then High of Sec
                else Close of Sec 1 unit ago
                endif
      AND
      n_low := TimePeriod lowest of if Low of Sec < Close of Sec 1 unit ago
               then Low of Sec
               else Close of Sec 1 unit ago
               endif
      AND
      n_range := n_high - n_low
    RETURN
    100 * ( TimePeriod sum of TrueRange (Sec) / n_range ) / (TimePeriod sum of 1)
ENDMACRO

compound_return

compund_return is the accumulated return of a specified relation column, between a specified start and end date. Since the formula relies on multiplication, all NaN values should be skipped at all times. If the relation column value is zero, then the value is 1. If the relation column is all NaN then the return value is NaN. For this study, it is practical to use % move as the attribute.

where C = compound_return and R = relation column

Example:

   SHOW 
     1: compound_return ( 1 day percent_move of GII.DELL.NASDAQ, from 1 year 
        ago  to today )

construct_date

This study returns XMIM's mathematical value corresponding to the date month/day/year format.

where D is an integer corresponding to the date m/d/y (month/day/year format). The number D is guaranteed to be in the standard date representation of XMIM, as given by the XMIM construct current date.

Example 1:

   SHOW 
     xmimDate: construct_date ( 1, 2, 2002 )

Example 2:

INITIALIZE 
   myBeginDate = construct_date ( 1, 1, 1997 ) 
AND 
  myEndDate = construct_date ( 12, 31, 2002 ) 

SHOW 
  Avg: average from date:myBeginDate to date:myEndDate of HO  
  StdDev: std_dev from date:myBeginDate to date:myEndDate of HO  
WHEN 
    Date is after date:myBeginDate 
  AND 
    Date is before date:myEndDate

coregression

Returns the statistical co-regression of two series where X is the Independent variable and Y is the dependent variable.

where and are the regression coefficients, computed as follows:

As in the case for linear regression, the formulas above are unstable and prone to round-off errors, so we replace them with the mathematically equivalent ones below:

NaNs are handled exactly as in the case for linear_regression (see the section called “linear_regression”).

Example:

   SHOW 
     Cregr: 70 day coregression of front CL and front NG  
     ng: Close of NG 
     cl: Close of CL 
     t+1: percent_move from today to 1 week later  of close of NG  
     t+2: percent_move from today to 2 weeks later  of close of NG  
   WHEN 
       Date is after 2001 
     AND 
       1 day percent_move of 70 day coregression of front CL and front NG   is 
       more than 0 
     AND 
       1 day percent_move of NG  is less than 0

coregression_intercept

Returns the statistical co-regression intercept of two series where X is the Independent variable and Y is the dependent variable.

where is the regression intercept, computed as follows:

As in the case for linear regression, the formulas above are unstable and prone to round-off errors, so we replace them with the mathematically equivalent ones below:

NaNs are handled exactly as in the case for linear_regression (see the section called “linear_regression”).

Example:

   SHOW 
     Intercept: 30 day coregression_intercept of CL and NG  
   WHEN 
       Date is within 1 year

coregression_slope

Returns the statistical co-regression slope of two series where X is the Independent variable and Y is the dependent variable.

where is the regression slope, computed as follows:

As in the case for linear regression, the formulas above are unstable and prone to round-off errors, so we replace them with the mathematically equivalent ones below:

NaNs are handled exactly as in the case for linear_regression (see the section called “linear_regression”).

Example:

   SHOW 
     Slope: 30 day coregression_slope of CL and NG  
   WHEN 
       Date is within 1 year

correlation

This study returns the statistical correlation coefficient between two series. This study will return values between the range of 1 (perfect correlation) and -1 (perfectly negative correlation).

where is equal to average (X, n) and similarly for . NaNs are handled exactly as in the case for covariance (see the section called “covariance”).

Example 1:

   SHOW 
     corr: 30 day correlation of CL and FB  
     move1: percent_move from today to 1 week later  of CL  
     move2: percent_move from today to 2 weeks later  of CL  
   WHEN 
       30 day correlation of CL and FB  crosses below 0.85 
     AND 
       Date is within 3 years

Example 2:

   LET 
     testSymbol = IBM
   LET 
     theSec = Equities:a
     TOP 20  80 day correlation of testSymbol and theSec  
   SHOW 
     corr: 80 day correlation of testSymbol and theSec  
     sec: theSec 
     test: testSymbol
   WHEN 
       Date is within 1 year 
     AND 
       theSec 250 days ago  is DEFINED 
     AND 
       testSymbol 250 days ago  is DEFINED 

count

This study counts the number of occurrences for which a value is returned for a given time period. This function will not include holidays or other NaN (Not a Number) values in its count.

where defined(X) returns a 0 if X is NaN and 1 otherwise.

Example:

   SHOW 
     count: count from begin_of_time to today of Close of A  
   WHEN 
       Date is within 1 day

covariance

A statistical covariance measure is the measure of the relationship between two series whose values are observed over a moving time window.

where is equal to average (X, n) and similarly for . As in the variance study, if n is less than or equal to 1, covariance returns NaN.

Example:

   SHOW 
     CoVariance: 80 day covariance of front C and front LH  
     moveLH: percent_move from today to 1 month later  of front LH  
     moveC: percent_move from today to 1 month later  of front C  
   WHEN 
       Date is within 5 years 
     AND 
       0 day covariance of front C and front LH  crosses below 0 

DeferredContract

This study provides a generalized macro for dealing with futures contracts. The DeferredContract function is used to identify certain back contract relationships within the software.

There are two methods to identify a futures contract:

  1. You may identify the 'specific' contract (e.g., the March 1998 30 year U.S. Treasury Bond contract or US_1998H); or

  2. You may identify a 'generic' contract based upon the contracts expiration (e.g., the front continuous adjusted 30 year U.S. Treasury Bond contract or US). If you wanted to test a trading strategy that involved the sixth contract on the board, or some contract expiring later than the front, far and back contracts, DeferredContract would be used to define the contract.

There are four fields that are required to be specified within this study:

  1. The attribute or series (select your futures series).

  2. The deferred number of the contract chosen (i.e., 1 represents the contract nearest to expiration or the front contract, 2 represents the second nearest contract to expiration, etc.).

  3. The number of days until expiration that the contract should be followed (i.e., 0 specifies that the contract will be active until expiration, 1 specifies that the contract will be active or followed up until 1 day before expiration, etc.).

  4. Contract month which is the parameter which specifies the contract month of interest (i.e., Setting the field to 0 will disable this field thereby allowing the contract to roll to the regularly traded serial months, setting the field to 1 will specify only January contracts, etc.).

DeferredContract (Series, DeferredNum, NumDays, ContractMth)

Example 1:

As the macro code below shows, the deferred contract macro is using the adjust_contract study. Therefore, the properties that are required entry for the adjust contract are the same for the deferred contract.

Assuming the 10/8/2002 trade date, the prompt/front contract for the NYMEX natural gas futures is the November 2002 contract (NG_2002X). If you wanted to use the deferred contract macro to modify the continuous NG contract to show the 5th contract out instead of the prompt contract, you could use the following syntax:

   SHOW 
     1: DeferredContract ( NG, 5, 0, 0 )

This will modify NG to the 5th contract out. (Prompt +4). This will now show the price for the March 2003 NG contract. (NG_2003H)

  • NG = base commodity symbol of choice.

  • 5 = N nearest. 5 points to the 5th closest or nearest to expiration active contract.

  • 0 = This is “Number of days before Expiration”. Setting this to “0” indicates the series will locate the next nearest contract when the contract expires. Setting this to “4” would mean that the contract should roll to the next one 4 days before expiration of the current contract.

  • 0 = Normally, this is where you put in the contract month. However, since we want the exact 6th closest contract, this is set to “0”.

Any of the 4 parameters can be modified to adjust the continuous contract as described in the adjust_contract study definition (see the section called “adjust_contract”).

Here is an example of the data:

Date Day Deferred NG_2003H

10/08/2002 Tue 4.023 4.023

Example 2:

   SHOW 
     twoSixAvg: 
       (DeferredContract ( NG, 2, 0, 0 )  + DeferredContract ( NG, 3, 0, 0 )  
        + DeferredContract ( NG, 4, 0, 0 )  + DeferredContract ( NG, 5, 0, 
        0 )  + DeferredContract ( NG, 6, 0, 0 ) 
       ) / 5 
     frontNG: NG 
   WHEN 
       Date is within 2 years 
     AND 
       NG is DEFINED

Macro Code:

ATTR MACRO DeferredContract ( ATTR Series, CONSTANT DeferredNum = 1,
                        CONSTANT NumDays = 0, CONSTANT ContractMth = 0 )
    RETURN
    adjust_contract ( Series, DeferredNum, NumDays, ContractMth )
ENDMACRO

DeMarker

Returns Tom DeMark's Oscillator. The DeMarker identifies potential price bottoms and tops. The indicator fluctuates between 0 and 1.

DeMarker (Series, TimePeriod)

Example:

   SHOW 
     FB: Close of front FB 
     Demarker: DeMarker ( FB, 14 days )  
     t+1w: percent_move from today to 1 week later  of front FB  
   WHEN 
       Date is within 2 years 
     AND 
       DeMarker ( front FB, 14 days )  crosses below 0.3 

Macro Code:

ATTR MACRO DeMarker (SECURITY Sec, PERIOD TimePeriod )
    RETURN
    MovingAvg ( If High of Sec > High of Sec 1 unit ago
            then High of Sec - High of Sec 1 unit ago Else 0
       Endif, TimePeriod ) /
    MovingAvg ( if High of Sec > High of Sec 1 unit ago 
    then High of Sec - High of Sec 1 unit ago Else 0 
    EndIf + If Low of Sec > Low of Sec 1 unit ago Then 0 
    else Low of Sec 1 unit ago - Low of Sec endif, TimePeriod )  
ENDMACRO

DirMove/DirMoveIdx

DirMove returns the Welles Wilder's Directional Movement indicator. To be used in conjunction with DirMoveIdx, which returns the Welles Wilder's Directional Movement Index. DirMove uses an exponential average in its calculation, while DirMoveIdx uses simple moving average.

DirMove (Series, Weight)

DirMoveIdx (Series, Weight)

Example:

   SHOW 
     DirMove: DirMove ( CVX, 1 / 20 )  
     DirMoveIdx: DirMoveIdx ( CVX, 20 days )  
     CVX: CVX 
     move: percent_move from today to 10 days later  of CVX  
   WHEN 
       Date is within 3 years 
     AND 
       DirMoveIdx ( CVX, 20 days )  crosses above 15

Macro Code:

ATTR MACRO DirMove ( SECURITY Series, CONSTANT Weight = 0.071428571 )
    VARS
    AvgTrueRange
    SmoothPDM
    SmoothMDM
    DEFINE
    COLUMN MACRO PlusDM ( SECURITY Series )
        RETURN
        if InsideDay ( Series ) then
            0
        else
            if High of Series - High of Series 1 unit ago >
                Low of Series 1 unit ago - Low of Series then
                High of Series - High of Series 1 unit ago
            else
                   0
                endif
            endif
    ENDMACRO
     COLUMN MACRO MinusDM ( SECURITY Series )
        RETURN
         if InsideDay ( Series ) then
             0
         else
             if High of Series - High of Series 1 unit ago >
                   Low of Series 1 unit ago - Low of Series then
                 0
             else
                 Low of Series 1 unit ago - Low of Series
             endif
         endif
    ENDMACRO
    INITIALIZE
           AvgTrueRange := exponential_average ( TrueRange of Series, Weight )
      AND
           SmoothPDM :=  exponential_average ( PlusDM of Series, Weight ) / AvgTrueRange 
      AND
           SmoothMDM := exponential_average ( MinusDM of Series, Weight ) / AvgTrueRange 
    RETURN
      if Close of Series is defined
      then
           if SmoothPDM > SmoothMDM then
              SmoothPDM - SmoothMDM
           else
              SmoothMDM - SmoothPDM
           endif / ( SmoothPDM + SmoothMDM ) * 100
      endif
ENDMACRO
ATTR MACRO DirMoveIdx ( SECURITY Sec, PERIOD TimePeriod = 14 day )
    VARS
         SmoothPlusDM
         SmoothMinusDM
         AvgTrueRange
    DEFINE
    COLUMN MACRO PlusDM ( SECURITY Sec )
        RETURN
           if InsideDay ( Sec ) then
               0
           else
               if High of Sec - High of Sec 1 unit ago >
                      Low of Sec 1 unit ago - Low of Sec then
                   High of Sec - High of Sec 1 unit ago
               else
                  0
               endif
           endif
    ENDMACRO
    COLUMN MACRO MinusDM ( SECURITY Sec )
        RETURN
           if InsideDay ( Sec ) then
               0
           else
               if High of Sec - High of Sec 1 unit ago >
                       Low of Sec 1 unit ago - Low of Sec then
                   0
               else
                   Low of Sec 1 unit ago - Low of Sec
               endif
           endif
    ENDMACRO
    ATTR MACRO SimDirMove ( SECURITY Sec, PERIOD TimePeriod )
        INITIALIZE
           AvgTrueRange := TimePeriod average of TrueRange of Sec
         AND
           SmoothPlusDM := TimePeriod average of PlusDM of Sec / AvgTrueRange
         AND
           SmoothMinusDM := TimePeriod average of MinusDM of Sec / AvgTrueRange
        RETURN
           if SmoothPlusDM > SmoothMinusDM then
               SmoothPlusDM - SmoothMinusDM
           else
               SmoothMinusDM - SmoothPlusDM
           endif / ( SmoothPlusDM + SmoothMinusDM )
    ENDMACRO
    RETURN
         100 * TimePeriod average of SimDirMove ( Sec, TimePeriod )
ENDMACRO

dividend_adjusted_return

dividend_adjusted_return is the overall percentage return of a dividend paying stock when it is assumed additional shares (or fractions of shares) are purchased with the dividend gains on Ex-Dividend date at the current stock’s closing price. On each ex-dividend date, the amount of shares increases, but the initial investment remains the same. The formula assumes a purchase of 1 share at the start date at the then current closing price (this is the initial investment).

Example:

   SHOW 
     1: dividend_adjusted_return ( close of GII.C.NYSE, from 12/31/2003 to 12/
        31/2004 )

DrawLine

DrawLine draws a point-to-point line segment from the coordinates defined in the function parameters. Parameters consist of start price, start date, end price and end date. The construct_date study needs to be used in the Date1 & Date2 parameters to supply a numeric date that the MIM can read.

For instance:

DrawLine (6500, construct_date ( 1, 29, 1966) , 2500, construct_date (8, 30, 1984))

Use this study in conjunction with Trendline which draws a ray that extends infinitely into the future from the coordinates defined in the function parameters.

DrawLine (Price1, Date1, Price2, Date2)

Example:

%exec.units:           monthly
%attr.units:           exec
%graph.report.title:   "Dow Jones Industrial Average, Constant 2007 Dollars"
%graph.graph.title:    "Trend"          "NBER Recessions in light blue"
%graph.plottype:       no
%graph.overlay:        yes
%graph.showdate:       yes
%graph.graphperpage:   "1x1 2x1 2x2 3x2"
%graph.back.color:     "white"
%graph.viewport:       "Trend"          ""
%graph.showby:         "Trend"          default
%graph.gridtype:       "Trend"          default
%graph.graphtype:      "Trend"          default
%graph.linetype:       "Trend"          solid
%graph.showfrom:       "Trend"          no
%graph.linewidth:      "Trend"          0
%graph.scalewith:      "Trend"          "Dow"
%graph.scalewith:      "Segment"        "Dow"
%graph.scalewith:      "SecondDow"      "Dow"
%graph.scalewith:      "AllTimeHigh"    "Dow"
%graph.plot.color:     "Trend"          "orange"
%graph.axis.color:     "Trend"          "black"
%graph.grid.color:     "Trend"          "lightgrey"
%graph.viewport:       "Recession"      ""
%graph.graph.title:    "Recession"      "Recession"
%graph.showby:         "Recession"      default
%graph.gridtype:       "Recession"      default
%graph.graphtype:      "Recession"      line histogram
%graph.linetype:       "Recession"      default
%graph.showfrom:       "Recession"      no
%graph.linewidth:      "Recession"      0
%graph.plot.color:     "Recession"      "lightblue"
%graph.axis.color:     "Recession"      "grey"
%graph.viewport:       "Dow"            ""
%graph.graph.title:    "Dow"            "DJIA"
%graph.showby:         "Dow"            default
%graph.gridtype:       "Dow"            default
%graph.graphtype:      "Dow"            default
%graph.linetype:       "Dow"            default
%graph.showfrom:       "Dow"            no
%graph.linewidth:      "Dow"            2
%graph.plot.color:     "SecondDow"      "navy"
%graph.plot.color:     "Segment"        "orange"
%graph.axis.color:     "Dow"            "black"
%graph.grid.color:     "Dow"            "grey"
%graph.plot.color:     "AllTimeHigh"    "red"


   SHOW 
     Dow: CPIBaseValue * Close of DJIA / FRH_CPIAUCNS 
     Recession: IF InNBERRecession ( ) 
                THEN 100 
                ELSE 0 
                ENDIF  
     Trend: Trendline ( 655, construct_date ( 6, 29, 1932 ), 1727.9325, 
            construct_date ( 7, 30, 1982 ) )  
     Segment: DrawLine ( 6500, construct_date ( 1, 29, 1966 ), 2500, 
              construct_date ( 8, 30, 1984 ) )  
     AllTimeHigh: Trendline ( 14300, construct_date ( 12, 29, 1999 ), 14300, 
                  construct_date ( 1, 30, 2000 ) )  
     SecondDow: CPIBaseValue * Close of DJIA / FRH_CPIAUCNS 
   WHEN 
       Date is after 1919 
     AND 
       CPIBaseValue = 208.352 

Graph Results:

ease_of_move

This study is derived from Richard Arms' Ease of Movement indicator and is a momentum indicator that incorporates range and volume to signal certain trends evolving within the markets. This indicator was developed in order to quantify volume and price changes in order to determine the ease, or lack thereof, with which price is able to move up or down. The formula for this study is the difference of the today's midpoint minus a previous midpoint multiplied by today's range all divided by today's volume.

where M is equal to midpoint (S) and is the previous value of midpoint (S).

Example:

   1: ORDER 
     1.1: Buy 1 contract of IBM 
   WHEN 
       ease_of_move of IBM  crosses above 0 
   EXIT 
       ease_of_move of IBM  crosses below 0

Energy

The following are the energy related studies.

_2X16Average

_2X16Average is located in XMIM under the Energy listing. This macro is designed to calculate the average for Saturday and Sunday from 7am – 10pm.

_2X16Average (Series)

Example:

The series input will be the symbol for a particular zone/node. The column “lmpVal” is assigned to each Series in the macro script. Therefore only symbols with the column, LmpVal can be used in this macro. Run this using “hourly” execution units.

   SHOW 
     1: _2X16Average ( NEPOOL.Z.CONNECTICUT.DA )  
   WHEN 
       Date is within 3 months 
     AND 
       Time is 04:00 pm 
     AND 
       Date is from Saturday  to Sunday

The query above will calculate the average for hours 8-23 on Saturday and Sunday for the real-time LMP prices for the New England ISO LMP LOAD ZONE Day Ahead Market . Notice in the macro code below, there are some assumptions being made in the calculation. These have been collected from industry and seem to be standard.

Macro Code:

ATTR MACRO _2X16Average (SECURITY PricePoint)  
RETURN  
IF Date is Saturday
OR Date is Sunday
THEN average from 07:00 am to 10:00 pm of lmpval of  
PricePoint ENDIF
ENDMACRO

_2X8Average

_2X8Average is located in XMIM under the Energy listing. This macro is designed to calculate the average for Saturday and Sunday from 12am – 6pm and 11pm.

_2X8Average (Series)

Example:

The Series input will be the symbol for a particular zone/node. The column “lmpVal” is assigned to each series in the macro script. Therefore only symbols with the column, LmpVal can be used in this macro. Run this using “hourly” execution units.

   SHOW 
     1: _2X8Average ( A418.138KV.TR7212.PJMRT )  
   WHEN 
       Date is within 1 week

The query above will calculate the average for hours 1-7 and hour 24 on Saturday and Sunday for the real-time LMP prices for the Pnode ID: 32408579 for PJM. Notice in the macro code below, there are some assumptions being made in the calculation. These have been collected from industry and seem to be standard.

Macro Code:

ATTR MACRO _2X8Average ( SECURITY PricePoint)  
RETURN 
IF Date is Saturday
OR Date is Sunday
THEN average from 12:00 am to 11:00 pm of 
IFTime is from 12:00 am to 06:00 am 
OR Time is 11:00 pm 
THEN lmpval of PricePoint ENDIF ENDIF
ENDMACRO

_5X16Average

_5X16Average is located in XMIM under the Energy listing. This macro is designed to calculate the average for Monday through Friday from 7am – 10pm.

_5X16Average (Series)

Example:

The series input will be the symbol for a particular zone/node. The column “lmpVal” is assigned to each Series in the macro script. Therefore only symbols with the column, LmpVal can be used in this macro. Run this using “hourly” execution units.

   SHOW 
     1: _5X16Average ( DELAWARECT11.AGGREGATE.PJMDA )  
   WHEN 
       range of DELAWARECT11.AGGREGATE.PJMDA  is less than 0.25 
     AND 
       Date is from Monday  to Friday

The query above will calculate the average for hours 8-23 on Monday thru Friday for the real-time LMP prices for the Day Ahead Locational Marginal Price in Delaware. Notice in the macro code below, there are some assumptions being made in the calculation. These have been collected from industry and seem to be standard.

Macro Code:

ATTR MACRO _5X16Average (SECURITY PricePoint) 
RETURN

IF Date is from Monday  to Friday

THEN average from 07:00 am to 10:00 pm of lmpval of
PricePoint
ENDIF 
ENDMACRO

_5X8Average

_5x8Average is located in XMIM under the Energy listing. This macro is designed to calculate the average for Monday through Friday from 12am-6am and 11pm.

_5X8Average (Series)

Example:

The series input will be the symbol for a particular zone/node. The column “lmpVal” is assigned to each Series in the macro script. Therefore only symbols with the column, LmpVal can be used in this macro. Run this using “hourly” execution units.

   SHOW 
     1: _5X8Average ( NYISO_GENESE_DA )  
   WHEN 
       Date is within 2 years 
     AND 
       Date is from Monday  to Friday

The query above will calculate the average for hours 1-7 and hour 24 Monday through Friday for the real-time LMP prices for the NYISO Load Zone Genesee Real Time Market. Notice in the macro code below, there are some assumptions being made in the calculation. These have been collected from industry and seem to be standard.

Macro Code:

ATTR MACRO _5X8Average ( SECURITY PricePoint)  
RETURN
  
IF Date is from Monday  to Friday
THEN average from 12:00 am to 11:00 pm of IF
Time is from 12:00 am to 06:00 am 
OR
Time is 11:00 pm

THEN lmpval of PricePoint 
ENDIF

ENDMACRO

_7X16Average

_7X16Average is located in XMIM under the Energy listing. This macro is designed to calculate the average for Monday through Friday from 7am – 10pm.

_7X16Average (Series)

Example:

The series input will be the symbol for a particular zone/node. The column “lmpVal” is assigned to each Series in the macro script. Therefore only symbols with the column, LmpVal can be used in this macro. Run this using “hourly” execution units.

   SHOW 
     1: _7X16Average ( NEPOOL.LD.ASHCREEK115.DA )  
   WHEN 
       Date is 1 week before  any holiday

The query above will calculate the average for hours 8-23 on Sunday thru Saturday for the real-time LMP prices for the New England ISO LMP NETWORK NOD Day Ahead Market . Notice in the macro code below, there are some assumptions being made in the calculation. These have been collected from industry and seem to be standard.

Macro Code:

ATTR MACRO _7X16Average (SECURITY PricePoint)
RETURN  
average from 07:00 am to 10:00 pm of lmpval of
PricePoint  
ENDMACRO

_7X8Average

_7X8Average is located in XMIM under the Energy listing. This macro is designed to calculate the average for Monday through Friday from 12am-6am and 11pm.

_7X8Average (Series)

Example:

The series input will be the symbol for a particular zone/node. The column “lmpVal” is assigned to each Series in the macro script. Therefore only symbols with the column, LmpVal can be used in this macro. Run this using “hourly” execution units.

   SHOW 
     1: _7X8Average ( NYISO_ALLEGHENY_COGEN_DA )  
   WHEN 
       Date is before 7/27/2001

The query above will calculate the average for hours 1-7 and hour 24 on Sunday thru Saturday for the real-time LMP prices for the NYISO Generator ALLEGHENY_COGEN Real Time Market . Notice in the macro code below, there are some assumptions being made in the calculation. These have been collected from industry and seem to be standard.

Macro Code:

ATTR MACRO _7X8Average (SECURITY PricePoint) 
RETURN

average from 12:00 am to 11:00 pm of IF
{Time is from 12:00 am to 06:00 am
OR 
Time is 11:00 pm}
THEN lmpval of PricePoint
ENDIF
ENDMACRO

_CoolingDegreeDays

_CoolingDegreeDays is located in XMIM under the Energy listing. Originally designed to evaluate energy demand and consumption, degree days are based on how far the average temperature departs from a human comfort level of 65 °F. Simply put, each degree of temperature above 65 °F is counted as one “cooling degree day”. For example, a day with an average temperature of 80 °F will have 15 cooling degree days. Source: www.weather2000.com/dd_glossary.html.

_CoolingDegreeDays (Series)

Example:

The series input is always the symbol for a city.

   SHOW 
     cdd: _CoolingDegreeDays ( HOUSTON.TX )  
   WHEN 
       Date is August

The query above will calculate the daily cooling degree days during the month of August in Houston, TX . As you can see it gets quite warm.

Macro Code:

ATTR MACRO _CoolingDegreeDays (SECURITY City) 
RETURN 
  IF 
    ((HighTemp of City + LowTemp of City ) / 2 ) - 65  > 0 
    THEN ((HighTemp of City + LowTemp of City ) / 2 ) - 65 
    ELSE 0 
  ENDIF 
ENDMACRO

_HeatingDegreeDays

_HeatingDegreeDays is located in XMIM under the Energy listing. Originally designed to evaluate energy demand and consumption, degree days are based on how far the average temperature departs from a human comfort level of 65 °F. Simply put, each degree of temperature below 65 °F is counted as one “heating degree day”. For example, a day with an average temperature of 60 °F will have 5 heating degree days. Source: www.weather2000.com/dd_glossary.html.

_HeatingDegreeDays (Series)

Example:

The series input is always the symbol for a city.

   SHOW 
     hdd: _HeatingDegreeDays ( CHICAGO.OHARE.IL )  
   WHEN 
       Date is February

The query above will calculate the daily heating degree days during the month of February in Chicago,IL . Bring a jacket!

Macro Code:

ATTR MACRO _HeatingDegreeDays (SECURITY City) 
RETURN 
IF  
65 - ((HighTemp of City + LowTemp of City ) / 2 ) > 0
THEN
65 - ((HighTemp of City + LowTemp of City ) / 2 )
    ELSE 0 
  ENDIF
ENDMACRO 

_OffPeakAverage

_OffPeakAverage is located in XMIM under the Energy listing. This macro is designed to calculate the Off Peak Average as it relates to hourly power prices. Many ISO data feeds are available from LIM. (PJM, NYISO, NEPOOL, IMO, and many European ones as well).

_OffPeakAverage (Series)

Example:

The series input will be the symbol for a particular zone/node. Run this using “hourly” execution units.

   SHOW 
     1: _OffPeakAverage ( WESTERNHUB.HUB.PJMRT )  
   WHEN 
       Date is within 1 week 

The query above will calculate the Off Peak Average for the real-time LMP prices on the Western Hub area of PJM. Notice in the macro code below, there are some assumptions being made in the calculation. These have been collected from industry and seem to be standard. Namely, on NERC holidays the Off Peak Average uses all hours in the day. On normal days (non-NERC holidays) the macro considers hours 1-7 and hour 24 in the calculation.

Macro Code:

ATTR MACRO _OffPeakAverage ( SECURITY PricePoint)   
RETURN   
IF Date is from Monday to Friday and Date is not in 
"nerc_holidays.rpt" THEN average from 12:00am to 11:00pm of IF  
{Time is from 12:00am to 6:00am or Time is 11:00pm} THEN  
LmpVal of PricePoint ENDIF ELSE average from  
12:00am to 11:00pm of LmpVal of PricePoint ENDIF 
ENDMACRO  

_OnPeakAverage

_OnPeakAverage is located in XMIM under the Energy listing. This macro is designed to calculate the On Peak Average as it relates to hourly power prices. Many ISO data feeds are available from LIM. (PJM, NYISO, NEPOOL, IMO, and many European ones as well).

_OnPeakAverage (Series)

Example:

The series input will be the symbol for a particular zone/node. Run this using “hourly” execution units.

   SHOW 
     1: _OnPeakAverage (NYISO_DUNWOD_TWRT)  
   WHEN 
       Date is within 3 weeks 
     AND 
       Date is from Monday to Friday  
     AND 
       Time is 03:00 pm

The query above will calculate the On Peak Average for the real-time LMP prices in ZONE I (Dunwoodie) of NYISO. Notice in the macro code below, there are some assumptions being made in the calculation. These have been collected from industry and seem to be standard. The On Peak average is calculated during Monday to Friday only. Hours 8 – 23 are considered in the average. Notice that you can have 1 number per day returned if you anchor the WHEN condition with a time. This is only an anchor and will not affect the results of the query, as this is being called from the macro. Output some raw data and check it for confidence.

Macro Code:

ATTR MACRO _OnPeakAverage (SECURITY PricePoint)  
RETURN  
IF Date is from Monday  to Friday   
THEN average from 07:00 am to 10:00 pm of LmpVal of  
PricePoint ENDIF   
ENDMACRO  

These macros below (_2x8Average through _7x16Average) will only be relevant when looking at intraday data (e.g., hourly) in the electricity markets. The typical sources of this data from LIM are the Independent System Operators (ISO’s) in North America, which include PJM, (Pennsylvania Jersey Maryland), NYISO (New York), NEISO (New England) and MISO (Midwest) – in particular the macros will only work in those markets that use LMP pricing methods. The user should note that different US regions have different concepts of peak and off-peak and that generally speaking, the Western region treats Saturday as a peak period and the Eastern region does not.

These types of calculation may also be relevant for European Electricity markets with intraday pricing as well, although definitions of peak and off-peak pricing again will vary by region.

exponential_average

There exists a school of thought that says that using a simple moving average system, where all days are weighted equally, does not properly acknowledge the impact of more recent prices on future price movement. Hence, it is argued that it would be preferred to 'weight' the more recent days more heavily in a 'moving average' equation. This study is calculated as of the sum of the current price multiplied by a 'weight' or smoothing constant and the previous day's study is multiplied by (1 - weight). The weight of a prior day's price will decrease the further back in time, relevant to today's price, it is. There are two fields that are required to be specified within this study- the Attribute or series and weight. There are two acceptable ways to calculate weight: 1 / n (where n represents the number of days) or 2 / n + 1. For example, if we were to use a 14 day equivalent, we could type in either 1 / 14 or 2 / 14 + 1 into the 'weight' field for our study.

where w is restricted to lie in the range and is the previous value of (or NaN if none). ignores any NaNs in X. That is, if a given value is NaN, then the is simply equal to the previous value of the .

Although exponential average takes into account the entire history of X, it is sometimes useful to compare it to an “n-day” average. The closer w is to 1, the shorter term the exponential average becomes. From the formula, it is clear that for w equal to 1, the exponential average of X is precisely X. Conversely, the closer w is to zero, the longer term the exponential average becomes.

Example:

   SHOW 
     DJIA: Close of DJIA 
     avg: exponential_average ( Close of DJIA, (1 / 21) ) 
     move: percent_move from today to 2 weeks later  of Close of DJIA  
   WHEN 
       Close of DJIA crosses above exponential_average ( Close of DJIA, (1 / 21
       ) )

extract_day

This study returns XMIM's mathematical value corresponding to the day as encoded within the software.

where d is the day encoded in the XMIM date D. See the section called “construct_date” for an explanation.

Example:

   SHOW 
     NG: NG 
     today: extract_day from dateVariable  
     yesterday: extract_day ( dateVariable - 1 ) 
   WHEN 
       Date is NG  expiration_day 
     AND 
       dateVariable = current date

extract_month

This study returns XMIM's mathematical value corresponding to the month as encoded within the software.

where m is the month encoded in the XMIM date D. See the section called “construct_date” for an explanation.

Example 1:

   SHOW 
     currentMonth: extract_month from dateVariable  
   WHEN 
       Date is within 2 years 
     AND 
       dateVariable = current date

Example 2:

   SHOW 
     yearavg10: total / 10 
     current: HighTemp of AUSTIN.TX 
   WHEN 
       Date is within 30 days 
     AND 
       total = 0 
     AND 
       curDate = current date 
     AND 
       MONTHnum = extract_month from curDate  
     AND 
       DAYnum = extract_day from curDate  
     AND {
         total = total + HighTemp of AUSTIN.TX } 
       repeated for the previous 9 and current 
         Date is MONTHnum/DAYnum/_

extract_year

This study returns XMIM's mathematical value corresponding to the year as encoded within the software.

where y is the year encoded in the XMIM date D. See the section called “construct_date” for an explanation.

Example:

   SHOW 
     currentYear: extract_year from dateVariable  
   WHEN 
       Date is Presidential Election year 
     AND 
       Date is last day of the year 
     AND 
       dateVariable = current date

FarContract

Returns the price of the third nearest-to-delivery futures contract in a futures market. This functionality is now built into the language itself. The default selection for a parent futures contract (e.g., US) is the front continuous contract. You can specify the contract by manually typing "front", "back" or "far" prior to the future symbol name (e.g., 1 month average of Close of front NG, or Close of back US).

FarContract (Series, NumDays, ContractMth)

Example 1:

As the macro code below shows, The FarContract macro is using the adjust_contract study. Therefore, the properties that are required entry for the adjust contract are the same for the far contract with the exception of the second adjust_contract parameter which indicates the N month out. This is always set to 3.

You can utilize the FarContract macro to modify a continuous contract to pull the far (3rd) closest contract to expiration.

Assuming the 10/8/2002 trade date, the prompt/front contract for the NYMEX natural gas futures is the November 2002 contract (NG_2002X). If you wanted to use the FarContract macro to modify the continuous NG contract to show the 3rd contract out instead of the prompt contract, you could use the following syntax:

   SHOW 
     1: FarContract ( NG, 0, 0 )

This will always modify NG to the 3rd contract out. (Prompt +2). This will now show the price for the January 2003 NG contract. (NG_2003F).

  • NG = base commodity symbol of choice.

  • 0 = This is “Number of days before Expiration”. Setting this to “0” indicates the series will locate the next nearest contract when the contract expires. Setting this to “4” would mean that the contract should roll to the next one 4 days before expiration of the current contract.

  • 0 = Normally, this is where you put in the contract month. However, since we want the exact 6th closest contract, this is set to “0”.

Any of the 3 parameters can be modified to adjust the continuous contract as described in the adjust_contract study definition (see the section called “adjust_contract” for more information).

Here is an example of the data:

Date Day Far NG_2003F

10/08/2002 Tue 4.243 4.243

Example 2:

   SHOW 
     macro: FarContract ( CL, 0, 0 )  
     xmimlanguage: far CL 
   WHEN 
       Date is 2001

Macro Code:

ATTR MACRO FarContract (ATTR Series, CONSTANT NumDays = 0,
                  CONSTANT ContractMth = 0)
 RETURN
    adjust_contract (Series, 3, NumDays, ContractMth)
ENDMACRO

forward_curve

Currently under development.

FrontContract

Returns the price of the nearest-to-delivery futures contract in the futures market. This functionality is now built into the language itself. The default selection for a parent futures contract (e.g., US) is the front continuous contract. You can specify the contract by manually typing "front", "back" or "far" prior to the future symbol name (e.g., 1 month average of Close of front NG, or Close of back US).

FrontContract (Series, NumDays, ContractMth)

Example 1:

As the macro code below shows, the FrontContract macro is using the adjust_contract built-in. Therefore, the properties that are required entry for the adjust contract are the same for the FrontContract macro with the exception of the second adjust_contract parameter which indicates the N month out. This is always set to 1.

You can utilize the FrontContract macro to modify a continuous contract to pull the prompt or closest contract to expiration.

Assuming the 10/8/2002 trade date, the prompt/front contract for the NYMEX natural gas futures is the November 2002 contract (NG_2002X). If you wanted to use the FrontContract macro to pull the front contract, you could use the following syntax:

  SHOW 
   Front: FrontContract ( NG, 0, 0 )

This will always modify NG to the front contract (Prompt). This will now show the price for the November 2002 NG contract. (NG_2002X)

  • NG = base commodity symbol of choice.

  • 0 = This is “Number of days before Expiration”. Setting this to “0” indicates the series will locate the next nearest contract when the contract expires. Setting this to “4” would mean that the contract should roll to the next one 4 days before expiration of the current contract.

  • 0 = Normally, this is where you put in the contract month. However, since we want the exact 6th closest contract, this is set to “0”.

Any of the 3 parameters can be modified to adjust the continuous contract as described in the adjust_contract study definition (see the section called “adjust_contract” for more information).

Here is an example of the data:

Date Day Front NG_2002X

10/08/2002 Tue 3.862 3.862

Example 2:

   SHOW 
     macro: FrontContract ( US, 0, 0 )  
     xmimlanguage: front US 
   WHEN 
       Date is 2002

Macro Code:

ATTR MACRO FrontContract (ATTR Series, CONSTANT NumDays = 0,
                     CONSTANT ContractMth = 0)
    RETURN
    adjust_contract (Series, 1, NumDays, ContractMth)
ENDMACRO

greatest_integer

This study returns a ceiling for a series using the some units specified as “steps”. There are two fields that are required to be specified within this study: the attribute or series (this may also be a constant/number or variable) and step. This study will return a value that is greater or equal to the attribute and that is a multiple of the number specified in the steps field. For example, if the Close of US was specified as the attribute and '2' was specified in the steps field, the study would return a number that was divisible by 2 and that was greater than the daily closing price.

Example:

   SHOW 
     FB: FB 
     roundUP: greatest_integer ( FB, 1 ) 
     multipleOfTwo: greatest_integer ( FB, 2 ) 
     halfUp: greatest_integer ( FB, 0.5 )

highest

Returns the highest value in a data series during a specified period of time. Identification of a succession of higher highs and higher lows is a technical method commonly used to designate an uptrend and may be used to identify certain trending patterns within your studies.

This study will ignore any NaN values. If all the X values are NaN, it will return NaN. Otherwise, it will return the maximum of the non-NaN values.

Example 1:

   SHOW 
     HU: Close of HU 
     1yearhighest: 1 year highest of Close of HU  
     move: percent_move from today to 1 week later  of Close of HU  
   WHEN 
       HU is exactly 1 year highest of Close of HU

Example 2:

   SHOW 
     t+2: percent_move from today to 2 values later  of front HU  
     t+3: percent_move from today to 3 values later  of front HU  
     t+3->12: percent_move from 4 values later  to 12 values later  of front 
              HU  
   WHEN 
       Date is after 2001 
     AND 
       front HU is exactly 6 month highest of front HU  
       repeated 2 times out of 5 days

HistVolLog

Returns the historical volatility of a series: the standard deviation of the logarithmic price changes measured at regular intervals of time. The default time period is 20 days. The default number of units per year is 250.

HistVolLog (Series, NumUnits, UnitsPerYear)

Example:

   SHOW 
     Vol: HistVolLog ( TY, 20 days, 250 )  
     TY: TY 
   WHEN 
       HistVolLog ( TY, 20 days, 250 )  crosses above 8

Macro Code:

ATTR MACRO HistVolLog ( ATTR Series,
                        PERIOD NumUnits = 20 days,
                        CONSTANT UnitsPerYear = 250 )
RETURN 
 If Series is defined
       Then StdDevPop (NaturalLog (AbsVal (
        1 +  1 day adjusted pct. move of 
          Series / 100)), NumUnits ) * 
         ( UnitsPerYear ** 0.5 ) * 100
       EndIf
ENDMACRO

HistVolPct

Returns the historical volatility of a series: the standard deviation of the percent price changes measured at regular intervals of time. The default time period is 20 days. The default number of units per year is 250.

HistVolPct (Series, NumUnits, UnitsPerYear)

Example:

   SHOW 
     Vol: HistVolPct ( YUM, 20 days, 250 )  
     YUM: YUM 
     t+1w: percent_move from today to 1 week later  of YUM  
   WHEN 
       HistVolPct ( YUM, 20 days, 250 )  crosses above 70

Macro Code:

ATTR MACRO HistVolPct ( ATTR Series,
                        PERIOD NumUnits = 20 days,
                        CONSTANT UnitsPerYear = 250 )
RETURN 
   If
      Series is defined
   Then 
      StdDevPop (1 day adjusted pct. move of Series, NumUnits)
      * (UnitsPerYear ** 0.5)
   Endif
ENDMACRO

inverse_log

This study returns the inverse logarithm for a specified attribute or series.

If X is NaN, its inverseLog is also NaN.

Example:

   SHOW 
     DJIA: Close of DJIA 
     SP500: Close of SPX 
     ratio: Close of DJIA / CLose of SPX 
     invLog: inverse_log ( Close of DJIA / Close of SPX ) 
   WHEN 
       Date is within 6 months 
     AND 
       Close of DJIA is DEFINED

linear_regression

Returns a value for a given attribute based on a linear regression (fitting data to a line, such as y=ax + b) over a specified time period. Linear regression is a statistical method of following trends. According to industry authorities, the results of linear regression studies are quite similar to the moving averages. This study performs a linear regression over a specified time period.

where and are the linear regression coefficients, computed as follows:

The formulas stated above are the standard formulas for linear regression; however, they are not well-suited to a computer implementation, because they suffer from severe round-off errors. To alleviate this, XMIM implements the equivalent formulas below instead:

Some of the expressions above are actually simple functions of n, i.e., . In general, XMIM will pre-compute these expressions, and so the formulas above are greatly simplified (and largely unrecognizable). LinearRegression ignores any NaN values in X. That is, if 3 values are NaN in the computation of linearRegression(X, 10), XMIM computes linearRegression(X’ 7) instead, where the X’ are derived from X by “stripping” away the NaN values. Note in particular that the placement of NaNs throughout the X time series is not significant.

Example:

   SHOW 
     LReg: 25 day average of LUV  
     avg: 25 day regression of LUV  
     t+1w: percent_move from today to 1 week later  of LUV  
     t+2w: percent_move from today to 2 weeks later  of LUV  
   WHEN 
       Date is within 5 years 
     AND 
       25 day regression of LUV  crosses above 25 day average of LUV

lowest

Returns the lowest value in a data series during a specified period of time. This function is helpful in identifying lower highs and lower lows, characterizing an downward trend pattern.

This study will ignore any NaN values. If all the X values are NaN, it will return NaN. Otherwise, it will return the minimum of the non-NaN values.

Example:

   SHOW 
     FB: FB 
     yearLow: 1 year lowest of Low of FB  1 value ago  
     t+3: percent_move from today to 3 values later  of FB  
     t+4: percent_move from today to 4 values later  of FB  
     t+5: percent_move from today to 5 values later  of FB  
   WHEN 
       Date is within 1 year 
     AND 
       FB is less than 1 year lowest of Low of FB  1 value ago

macd_osc

This study's name is short hand for moving average convergence divergence oscillator. This indicator was developed by Gerald Appel and is widely employed to measure market momentum as well as detecting and following trends. This study measures the rate of convergence and divergence between two exponentially smoothed moving averages (or the rate of acceleration or deceleration between a faster or shorter period moving average and a slower or longer period moving average). There are three fields that must required to be specified within this study: the attribute or series and two fields representing the weights for the faster and slower exponentially smooth moving averages. This study will return the difference between the two moving averages. A value of '0' would indicate that the averages are exactly the same whereas a positive value (where the faster average was the first defined weight field) would indicate acceleration and a negative value would indicate deceleration.

For an explanation of the and arguments, see the section called “exponential_average”.

Example:

   SHOW 
     move: percent_move from today to 1 week later  of Close of NKE  
     oscillator: macd_osc ( Close of NKE, 0.15, 0.075 ) 
     signal: macd ( Close of NKE, 0.15, 0.075, 0.2 ) 
   WHEN 
       Date is within 3 years 
     AND 
       macd_osc ( Close of NKE, 0.15, 0.075 ) crosses above macd ( Close of 
       NKE, 0.15, 0.075, 0.2 )

macd_signal

This study incorporates a 'signal' line into the study, macd_osc, listed above. Where the first two fields represent the faster and slower moving averages in the macd_osc study, the third weight represents the exponential weight of this macd_osc study. So in effect this study is an exponential study, as defined by the third weight, of macd_osc created by the first two weight fields. The basic method of incorporating this study into a trading program is to look for buy signals when the macd_osc crosses above the macd_signal and to look for sell signals upon the reverse.

For an explanation of the , , and arguments, see the section called “exponential_average”.

Example:

   LET 
     ATTR fast = 2 / (12 + 1) 
     ATTR slow = 2 / (26 + 1) 
     ATTR signal = 2 / (12 + 1) 

   1: ORDER 
     1.1: Buy 1 contract of NG 
   WHEN 
       macd_osc ( NG, fast, slow ) 1 day ago  crosses above macd ( NG, fast, 
       slow, signal ) 1 day ago  
     AND 
       macd_osc ( NG, fast, slow ) is more than 0 
   EXIT 
       macd_osc ( NG, fast, slow ) 1 day ago  crosses below macd ( NG, fast, 
       slow, signal ) 1 day ago

median

Returns the median value in a data series. Median function first sorts the data series, and then returns the median value. If the data item number in the series is odd, it returns the middle data item in the series. Otherwise, it returns the middle two data item average. For example, if the data series is (10, 4, 7), the median value is 7. If the data series is (10, 2, 3, 27), the median value is (3+10)/2=6.5

This study will ignore any NaN values. If all the X values are NaN, it will return a NaN. Otherwise, it will return the non-NaN median value.

Example:

   SHOW 
     Median: median ( Close of CL, 3 days ) 
     Close: Close of CL 
   WHEN 
       Date is within 1 month

midpoint or mid_point

Returns the mathematical midpoint for a specified attribute and is calculated by dividing the sum, of the High of the Attribute and the Low of the Attribute, by 2. A popular method of employing this study is to gauge a 50% market retracement (as defined as some point below the midpoint), off from some specified high, as potential entry points for a trading program.

“midpoint” or the alternate syntax “mid_point” may be used.

Where X is the High of the attribute and Y is the Low of the attribute.

Example 1:

   midpoint of HO

Example 2:

   mid_point of HO

MoneyFlowIndex

The Money Flow Index measures the amount of money flowing in and out of a security. It is an oscillator non unlike RSI that incorporates Volume into its calculation. The values range between 0 and 100. Market tops generally occur around 80 and bottoms around 20.

MoneyFlowIndex(Series, TimePeriod)

Example:

   SHOW 
     SP: SP 
     MFlow: MoneyFlowIndex ( SP, 14 days )  
   WHEN 
       Date is within 2 years 
     AND 
       MoneyFlowIndex ( SP, 14 days )  crosses above 70

Macro Code:

COLUMN MACRO MoneyFlowIndex ( SECURITY Series, PERIOD TimePeriod )    
RETURN     
 100 - 100 / (1 + (TimePeriod sum of    
   
         IF     
                move ( ((High of Series + Low of     
                                                      Series + Close of Series    
                                                     ) / 3) * Volume of     
                                             Series, 1 value ) is more than 0     
                                         THEN (((High of Series+ Low of     
                                                 Series + Close of Series) / 3    
                                               ) * Volume of Series)     
                                         ELSE 0     
                                         ENDIF   / TimePeriod sum of IF     
                                             move ( ((High of Series + Low of     
                                                     Series + Close of Series    
                                                     ) / 3) * Volume of     
                                            Series, 1 value ) is less than 0     
                                         THEN (((High of Series + Low of     
                                                Series + Close of Series) / 3    
                                               ) * Volume of Series)     
                                         ELSE 0     
                                         ENDIF      
                                        )    
                           )     
   ENDMACRO    

For more information, see the Money Flow Index document located in the "Documentation" section of the LIM Web site.

move

Returns the difference between the start and end values over a specified time period.

If either X or X n is a NaN, the immediately preceding value will be considered instead, i.e., X 1 or X n+1. If these values are also NaN, the move will be NaN as well. For example, when computing a 2 day move, if X is a NaN, but X 2 is not, then XMIM will return X 1 – X 2 instead of X – X 2. But, if X 1 is also NaN, then XMIM will return NaN.

Example 1:

   SHOW 
     move: move from 10:30 am to 12:00 pm of Close of NG  
   WHEN 
       Date is within 1 month 
     AND 
       Time is 12:00 pm 
     AND 
       move from 10:30 am to 12:00 pm of Close of NG  is more than 0.01 

Example 2:

SHOW
move1: move from 1/1/2002 to 2/1/2002 of Close of DJIA
move2: move from 9/15/2001 to 11/30/2001 of Close of DJIA
WHEN
Date is 2/1/2002

natural_log

This study returns the natural logarithm for a specified Attribute or series.

If X is NaN or less than or equal to 0, naturalLog returns NaN

Example:

   SHOW 
     DJIA: DJIA 
     Log: natural_log of DJIA  
   WHEN 
       Date is within 10 years 

nearest_integer

This study will return either the smallest integer or the greatest integer, depending upon which value is closest to the value of the attribute or series selected. This study may be used to calibrate where the value of the attribute is relative to some ceiling (greatest integer) or floor (smallest integer).

or

depending on which of the two values is closer to N. If N is the midpoint of these two values, XMIM chooses greatestInteger (N, s) arbitrarily.

Example:

   SHOW 
     High: High of ED 
     roundedHigh: nearest_integer ( High of ED, 1 ) 
   WHEN 
       Date is within 2 years

negative_value

This study will only return the value of the attribute specified where the value is a negative number. Where the value is positive or zero the value returned is '0'.

Notice that this function never returns a positive number. If X is NaN, negativeValue returns NaN as well.

Example 1:

   SHOW 
     SoyBean: Close of BO 
     negative: negative_value of 1 day move of Close of BO   
     totalDownDays: counter 
   WHEN 
       Date is within 1 year 
     AND 
       IF 
         negative_value of 1 day move of Close of BO   is not exactly 0 
         THEN 
           counter = counter + 1 
       ENDIF

Example 2:

   SHOW 
     NASD: Close of NASD 
     negative: negative_value of 5 day move of Close of NASD   
   WHEN 
       Date is from 1/1/2001 to within 0 days 
     AND 
       negative_value of 5 day move of Close of NASD   is not exactly 0

net_change

This study is the same as the “move study”, but the sign of the change is removed. Net change is the absolute value of the move.

This study treats NaNs analogously to move. It also performs the same special cases.

Example:

   SHOW 
     t+1: percent_move from today to 1 week later  of DJIA  
     t+2: percent_move from today to 2 weeks later  of DJIA  
   WHEN 
       1 value net_change of DJIA  is more than 100 
     AND 
       Date is after 2001

net_percent_change

This study returns the absolute value of the percentage move over some time period specified.

This study treats NaNs analogously to move. It also performs the same special cases.

Example:

   SHOW 
     t+1: percent_move from today to 1 week later  of SPX  
     t+2: percent_move from today to 2 weeks later  of SPX  
   WHEN 
       Date is Friday  
     AND 
       Date is within 4 years 
     AND 
       1 value net_percent_change of SPX  is more than 1 
       repeated for the previous 4 values

NetHedgers

Returns the net open interest held by traders in the commercial hedgers category of futures traders in a market. The calculation is net long minus net short positions.

NetHedgers(Series)

Example:

   SHOW 
     NetHed: NetHedgers ( CL )  
     CL: Close of CL 
   WHEN 
       Date is in "cot.rpt"

Macro Code:

COLUMN MACRO NetHedgers ( SECURITY Sec )
   RETURN
     CoTCHL of Sec - CoTCHS of Sec
ENDMACRO

NetHedgersPct

Returns the net open interest holdings of the commercial hedger category as a percentage of total open interest in the market.

NetHedgersPct(Series)

Example:

   SHOW 
     US: NetHedgersPct ( US )  
   WHEN 
       Date is in "cot.rpt"

Macro Code:

COLUMN MACRO NetHedgersPct ( SECURITY Sec )
   RETURN
     (CoTCHL of Sec - CoTCHS of Sec)/ TotalOI of Sec * 100
ENDMACRO

NetLargeSpecs

Returns the net open interest held by traders in the large speculator category of futures traders in a market. That is, the net long minus net short positions.

NetLargeSpecs(Series)

Example:

   SHOW 
     US: NetLargeSpecs ( NG )  
   WHEN 
       Date is in "cot.rpt"

Macro Code:

COLUMN MACRO NetLargeSpecs ( SECURITY Sec )
   RETURN
     CoTLSL of Sec - CoTLSS of Sec
ENDMACRO

NetLargeSpecsPct

Returns the net open interest holdings of the large speculator category as a percentage of total open interest in the market.

NetLargeSpecsPct(Series)

Example:

   SHOW 
     US: NetLargeSpecsPct ( HU )  
   WHEN 
       Date is in "cot.rpt"

Macro Code:

COLUMN MACRO NetLargeSpecsPct ( SECURITY Sec )
   RETURN
     (CoTLSL of Sec - CoTLSS of Sec)/ TotalOI of Sec * 100
ENDMACRO

NetSmallTraders

Returns the remaining net open interest held by traders with positions smaller than reporting thresholds.

NetSmallTraders(Series)

Example:

   SHOW 
     US: NetSmallTraders ( S )  
   WHEN 
       Date is in "cot.rpt" 

Macro Code:

COLUMN MACRO NetSmallTraders ( SECURITY Sec )
   RETURN
     CoTSTL of Sec - CoTSTS of Sec
ENDMACRO

NetSmallTradersPct

Returns the net open interest of the Small Traders category as a percentage of total open interest.

NetSmallTradersPct(Series)

Example:

   SHOW 
           US: NetSmallTradersPct ( S )  
   WHEN 
           Date is in "cot.rpt"

Macro Code:

COLUMN MACRO NetSmallTradersPct ( SECURITY Sec )
   RETURN
     (CoTSTL of Sec - CoTSTS of Sec)/ TotalOI of Sec * 100
ENDMACRO

NormalDist

NormalDist(n) returns the percent of area under the normal distribution curve commonly called the z-table. The parameter n is the number of standard deviations from the mean. The macro NormalDist(n) returns the percent of the curve below parameter n. This is commonly used to compute probability.

NormalDist(n)

Example:

Compute the probability of a future price level for a given volatility of the 5 day move over the last 100 days.

   LET 
     @stock = IBM

   SHOW 
     prob_above: 1 - NormalDist ( natural_log ( price_target / price_now ) / 
                 volatility_period )  
     price_target: price_target 
     price_now: price_now 
     vol_period: volatility_period 
     5_day: percent_move from today to 5 days later  of Close of @stock  
     worked: IF 
                 Close of @stock 5 days later  - Close of @stock is more than 
                 0.01 * Close of @stock 
             THEN 1 
             ELSE -1 
             ENDIF  
   WHEN 
       Date is within 1 year 
     AND 
       Close of @stock 5 days later  is DEFINED 
     AND 
       Close of @stock is DEFINED 
     AND 
       price_target = Close of @stock * 1.01 
     AND 
       price_now = Close of @stock 
     AND 
       volatility_period = std_dev ( 
       (5 day percent_move of Close of @stock 
       ) / 100, 100 days )

Macro Code:

ATTR MACRO NormalDist ( ATTR @z )
VARS
   @answer
   @b1 @b2 @b3 @b4 @b5 @p @c2 @a @t @e @b @n
INITIALIZE
   @answer = 1
AND
    @z < 6.0 
AND
    @answer = 0
AND 
    @z > -6.0 
AND
    @b1 =  0.31938153
    AND @b2 = -0.356563782
    AND @b3 =  1.781477937
    AND @b4 = -1.821255978
    AND @b5 =  1.330274429 
    AND @p  =  0.2316419 
    AND @c2 =  0.3989423 
    AND @a = absolute_value(@z) 
    AND @t = 1.0 / (1.0 + (@a * @p)) 
    AND @e = 2.7182818284590452354
    AND @b = @c2 * (@e ** ((-1 * @z) * (@z / 2.0)))
    AND @n = (((( @b5 * @t + @b4 ) * @t + @b3 ) * @t + @b2 ) * @t + @b1 ) * @t 
    AND @n = 1.0 - (@b * @n) 
AND
  @answer = 
    IF  @z < 0.0 
    THEN
1.0 - @n
    ELSE
@n
    ENDIF 
RETURN 
@answer
ENDMACRO
  

on_balance_volume

This study quantifies the trend in volume over time and is most closely identified with research conducted by Joseph Granville. There are several methods by which this study may be analyzed. The primary methods are trend assessment and divergence analysis. The study returns a cumulative value representing the running total equated to the sum of (daily or periodic volume multiplied by 1, where the daily or periodic move is positive, or by -1, where the move is negative). This study is a 'running' calculation based on market direction and volume. The only field required to be specified for the study is the attribute.

where sign is 1 if Close of S is up and -1 otherwise. The expression refers to the previous value of onBalanceVolume(S).

Example:

   SHOW 
     OBV: on_balance_volume of PEP  
     t+1: percent_move from today to 1 week later  of PEP  
     t+2: percent_move from today to 2 weeks later  of PEP  
     t+3: percent_move from today to 3 weeks later  of PEP  
   WHEN 
       Date is within 4 years 
     AND 
       on_balance_volume of PEP  is up 
       repeated for 5 times

periods_in_range

This study returns the number of periods (days, weeks, etc.) in some specified window time. The most interesting use of this study is to calibrate the number of periods or days between two given conditions. For example, the periods in range from the time when some value crosses above a moving average to when the value crosses below. This example could assist in identifying the period of time a certain trade would be active based on a moving average system.

where #n counts the number of periods (days, weeks, etc.) in the time period n. If this time period is specified as a from/to range, and the boundaries are reversed (i.e., the “from” occurs after the “to”), periodsInRange returns a negative number.

Example 1:

  SHOW 
     CL: CL 
     daystoexp: periods_in_range from today to HU_K expiration_day  
   WHEN 
       Date is after 2001

Example 2:

   SHOW 
     close: NG 
     t+7: percent_move from today to 7 values later  of NG  
     t+8: percent_move from today to 8 values later  of NG  
     t+9: percent_move from today to 9 values later  of NG  
   WHEN 
       periods_in_range from today to next in "opec_meet.date"   is exactly 10 

positive_value

This study will only return the value of the Attribute specified where the value is a positive number. Where the value is negative or zero the value returned is '0'.

If X is NaN, positiveValue returns NaN as well.

Example:

   SHOW 
     US: US 
     pVal: positive_value of 10 value move of front US   
           repeated for the previous 2 and current day 
   WHEN 
       positive_value of 10 value move of front US   is not exactly 0 
       repeated 2 times in the previous 3 days

product

This study will return the product (the multiplication of some values to each other) of those values of an attribute as defined over some period of time. Where there exists a holiday or missing data (expressed by NaN) the equation is multiplied by '1'. There are two fields that must be specified within this study- the attribute or series and time period.

This study will ignore any values that are NaN. That is, it returns the product of the non-NaN values in the given range. If all the X values are NaN, product returns a NaN.

Example:

   SHOW 
     W: percent_move from today to 2 weeks later  of front W  
     product: product ( 1 day move of front W, 5 days ) 
   WHEN 
       Date is within 3 years 
     AND 
       product ( 1 day move of front W, 5 days ) is more than 2000

range

This study will return the range for some specified attribute by subtracting the High of the attribute - the Low of the attribute. Trading ranges, performed for certain key periods (i.e., calendar month or 6 months), are used to establish the upper and lower boundaries that are essential to defining levels of support and resistance. Breakouts from established trading ranges provide important trading signals.

Example:

   SHOW 
     high: High of CL 
     low: Low of CL 
     range_CL: range of CL  
   WHEN 
       range of CL  is exactly 10 day highest of range of CL   

   SHOW 
     range_TY: range of TY  
     move1: percent_move from today to 2 days later  of TY  
     move2: percent_move from today to 3 days later  of TY  
   WHEN 
       Date is after 2001 
     AND 
       range of TY  is more than 1

RangeExpIndex

Returns Tom DeMark's REI2 indicator as explained in his book The New Science of Technical Analysis.

RangeExpIndex(Series, TimePeriod)

Example:

   SHOW 
     Range: RangeExpIndex ( IBM, 20 days )  
   WHEN 
       RangeExpIndex ( IBM, 20 days )  crosses above 0

Macro Code:

ATTR MACRO RangeExpIndex   (SECURITY sec, PERIOD TimePeriod )
    DEFINE
    COLUMN MACRO sub_values (SECURITY sec ) 
           VARS
                  var1
                  var2
                  num_zero
                  num_zero2
           INITIALIZE 
                  var1 := High of sec - High of sec 2 units ago 
                  AND
                  var2 := Low of sec - Low of sec 2 units ago 
                  AND 
                  num_zero := if High of sec 2 units ago < Close of sec 7 units ago AND 
                          High of sec 2 units ago < Close of sec 8 units ago AND 
                          High of sec < Low of sec 5 units ago  AND 
                          High of sec < Low of sec 6 units ago then 0 Else 1 Endif
                  AND 
                  num_zero2 := if Low of sec 2 units ago > Close of sec 7 units ago  AND 
                          Low of sec 2 units ago > Close of sec 8 units ago AND 
                          Low of sec > High of sec 5 units ago AND 
                          Low of sec > High of sec 6 units ago then 0 Else 1 EndIf  
                   RETURN
                   ( num_zero * num_zero2 * var1 ) + ( var2 * num_zero * num_zero2 ) 
           ENDMACRO
  COLUMN MACRO AbsDailyVal ( SECURITY sec ) 
    VARS 
       var3
       var4 
    INITIALIZE 
       var3 := AbsVal ( High of sec - High of sec 2 units ago ) 
           AND var4 := AbsVal ( Low of sec - Low of sec 2 units ago ) 
    RETURN 
           var3 + var4
           ENDMACRO 
RETURN 
    TimePeriod sum of sub_values ( sec )  / TimePeriod sum of AbsDailyVal ( sec ) 
ENDMACRO

RealSum

Here Counter is a number which is the # of days to start the look back. Returns the sum of the last N days.

RealSum(Attribute, Counter)

Example:

   SHOW 
     RealSum: RealSum ( 1 day percent_move of SPX, 100 )  
   WHEN 
       Date is within 1 month

Macro Code:

ATTR MACRO RealSum (ATTR Series, CONSTANT Counter)
   RETURN
     Counter value sum of Series
ENDMACRO

rel_strength

This study returns the difference between the period percent move of one data series versus another defined series. This study is useful for attribution analysis (research that defines what portion of a security's price is 'attributable' to the broad market moves). The most interesting use of this study is to compare the price of a security or market sector versus its comparable broad market index to see whether the security or sector is out pacing or under-performing the index.

Example:

   SHOW 
     rel: rel_strength ( ERTS, NASD, 65 ) 
     erts: Close of ERTS 
     nasd: Close of NASD 
   WHEN 
       Date is within 2 years 

   SHOW 
     2.1: rel_strength ( YHOO, NASD, 65 ) 
     yhoo: Close of YHOO 
     2.2: Close of NASD 
     move1: percent_move from today to 1 week later  of YHOO  
   WHEN 
       Date is within 2 years 
     AND 
       rel_strength ( YHOO, NASD, 65 ) crosses below 10

select_contract

XMIM will adjust all studies using futures contract so that the artificial price jump associated with the expiration of a contract will not be factored into the study. For example, if a study using the front continuous contract captured a time period which included a roll or expiration date, by default, that price difference between the old or expiring contract and the new contract would be subtracted or backed out of the equation as of the expiration date. The select_contract function is used so that the jump or price difference associated with expiration (cost of carry) is not adjusted out of the study. This is accomplished by 'anchoring' the current contract that satisfies our expiration requirements (i.e., if the front contract is the March 1998 contract, the studies will be performed exclusively on this contract and will ignore all previous contracts that meet our expiration requirement). There are four fields that are required to be specified within this study: the attribute or series (select your futures series), the deferred number of the contract chosen (i.e., 1 represents the contract nearest to expiration or the front contract, 2 represents the second nearest contract to expiration, etc.), the number of days until expiration that the contract should be followed (i.e., 0 specifies that the contract will be active until expiration, 1 specifies that the contract will be active or followed up until 1 day before expiration, etc.) and contract month which is the parameter which specifies the contract month of interest (i.e., Setting the field to 0 will disable this field thereby allowing the contract to roll to the regularly traded serial months, setting the field to 1 will specify only January contracts, etc.).

whereis computed by replacing all references to a relation in X with the corresponding “current” contract. The current contract is selected as in adjustContract (see the section called “adjust_contract”).

Example 1:

Consider the trading day of 10/8/2002 for the following scenarios. The “prompt” crude oil contract would be Nov 2002, CL_2002X .

Date

LIM SYMBOL

adjust_contract version

10/8/2002

CL_2002Z - Close

adjust 1st December contract out

select_contract (CL, 1, 0, 12)

29.51

29.51

CL_2003J - Close

adjust 6th contract month out

select_contract (CL, 6, 0, 0)

27.6

27.6

CL_2004H - Close

adjust 2nd March contract out

select_contract (CL, 2, 0, 3)

23.86

23.86

CL_2005F - Close

adjust 3rd January contract out

select_contract (CL, 3, 2, 1)

23.03

23.03

Let’s look closer at each of these to see how the select_contract function chooses the correct contract.

December 2002 contract : This is the nearest December contract right now. The explicit LIM symbol is CL_2002Z. To ask for the closest contract month using select_contract you fill in select_contract (CL, 1, 0, 12), where:

  • CL = base commodity symbol of choice.

  • 1 = N nearest. 3 would imply the 3rd nearest, 6 the 6th nearest.

  • 0 = This is “Number of days before Expiration”. Setting this number to “0” indicates the series will locate the next nearest contract when the contract expires. Setting this number to “4” would mean that the contract should roll to the next one 4 days before expiration of the current contract.

  • 12 = This is the contract month, 12 equals December, 5 equals May, 7 equals July. Note: Setting this number to “0” makes the parameter inactive, meaning the other parameters will determine the behavior.

April 2003 contract: This is the 6th nearest contract out. The explicit LIM symbol is CL_2003J. To ask for the literal N contract out using select_contract, you fill in select_contract (CL, 6, 0, 0), where:

  • CL = base commodity symbol of choice.

  • 6 = N nearest. 6 points to the 6th closest or nearest to expiration active contract.

  • 0 = This is “Number of days before Expiration”. Setting this to “0” indicates the series will locate the next nearest contract when the contract expires. Setting this to “4” would mean that the contract should roll to the next one 4 days before expiration of the current contract.

  • 0 = Normally, this is where you put in the contract month. However, since we want the exact 6th closest contract, this is set to “0”.

March 2004 contract: This is the 2nd nearest March contract. The 1st nearest is the March 2003 contract. The 3rd nearest would be March 2005. To ask for the 2nd nearest March using select_contract, you would fill in select_contract (CL, 2, 0, 3) where:

  • CL = base commodity symbol of choice.

  • 2 = 2nd nearest

  • 0 = This is “Number of days before Expiration”. Setting this to “0” indicates the series will locate the next nearest contract when the contract expires.

  • 3 = March contract.

January 2005 contract: This is the 3rd nearest January contract. The closest or first nearest would be January 2003. To ask for the 3rd nearest using select_contract, you will fill in select_contract (CL, 3, 2, 1), where:

  • CL = base commodity symbol of choice

  • 3 = 3rd nearest

  • 2 = This is “Number of days before Expiration”. Setting this to “2” indicates the series will roll 2 days before the contract expires and choose the next 3rd nearest contract.

  • 1 = January contract.

Example 2:

   SHOW 
     NGjan: select_contract ( NG, 1, 0, 0 ) 
     NGfeb: select_contract ( NG, 2, 0, 0 ) 
     NGmar: select_contract ( NG, 3, 0, 0 ) 
     avg: 
       (select_contract ( NG, 1, 0, 0 ) + select_contract ( NG, 2, 0, 0 ) + 
        select_contract ( NG, 3, 0, 0 )
       ) / 3 
   WHEN 
       Date is December

simple_rsi

Simple relative strength index is a variation of Welles Wilder's Relative Strength Index indicator and is a popular overbought-oversold measure. These measures are intended to reflect situations when prices have risen or fallen too sharply and are thus vulnerable to a market reaction. Wilder's version uses a form of exponential smoothing where simple_rsi uses a simple moving average. This study compares the relative strength of prices gains (closes that are higher than the previous day's close) versus price losses (closes that are lower than the previous day's close) by averaging these values for some specified period of time. Simple_rsi may be performed for any time period. Wilder originally suggested 14 days, however, technicians sometimes prefer a shorter/more sensitive period of time such as 5 or 7 days. Industry standards derive the overbought and oversold indicators at levels that range around 70 (overbought) and 30 (oversold).

where U and D are the average of the 1-period up-and down-moves of X, respectively, over the period n. That is, U and D are given by

Note in the definition of D that D is always positive, since negativeValue is never positive.

Example:

   SHOW 
     NG: Close of NG 
     rsi: simple_rsi ( front NG, 14 days ) 
     t+5: percent_move from today to 5 values later  of NG  
   WHEN 
       simple_rsi ( front NG, 14 days ) crosses above 75 

   1: ORDER 
     1.1: Sell 1 contract of UAL 
   WHEN 
       Date is within 5 years 
     AND 
       simple_rsi ( UAL, 14 days ) crosses above 85 
   EXIT 
       Date is 3 days after  entry_date

smallest_integer

This study returns the floor for a series using units specified as 'steps'. There are two fields that are required to be specified within this study: the attribute or series (this may also be a constant/number or variable) and step. This study will return a value that is lesser or equal to the attribute and that is a multiple of the number specified in the steps field. For example, if the Close of US was specified as the attribute and '2' was specified in the steps field, the study would return a number that was divisible by 2 and that was lesser than or equal to the daily closing price.

That is, smallestInteger returns the floor of N using the units in s. For example, smallestInteger (5, 2) is equal to 4, because 4 is the largest multiple of 2 less than or equal to 5. Similarly, smallestInteger (5.3, .25) is equal to 5.25.

Example:

   SHOW 
     NASD1: smallest_integer ( NASD, 1 ) 
     NASD2: smallest_integer ( NASD, 2 )

standard_deviation

This study provides the standard deviation of a population based on the sample as defined by the values included in the specified time period. Standard deviation measures the spread from the mean (or measures how far from the center or mean the data tends to range). This study is a commonly used statistic used to measure the degree of dispersion in the data.

This corresponds to the standard deviation used for population samples.

Example:

   SHOW 
     T+1: percent_move from today to 5 days later  of front NG  
     STD: 180 day std_dev of close of front NG  
   WHEN 
       Date is within 2 years 
     AND 
       front NG is more than 
       (1 year average of front NG  + 180 day std_dev of close of front NG 
       ) 

standard_deviation_population

Returns a moving population standard deviation of values in the time period (uses n as a divisor) based on the population itself, that is, the values in the period.

For efficiency and stability, this formula is actually computed as follows:

Example:

   SHOW 
     stdDev: 100 day std_dev_pop of front SP  
     pmove: percent_move from today to 1 week later  of front SP  
   WHEN 
       100 day std_dev_pop of front SP  crosses above 50

Stochastics

See below for the descriptions of the Stochastics server macros.

KStochastic

Stochastics is a momentum or price velocity indicator developed by George C. Lane. This macro is sometimes referred to as "%K" in the market. This is the normal stochastic.

KStochastic(Security, TimePeriod)

Example:

   SHOW 
     K: KStochastic ( DELL, 30 days )  
     SK: SKStochastic ( DELL, 30 days, 20 days )  
     t+1: percent_move from today to 1 week later  of DELL  
   WHEN 
       KStochastic ( DELL, 30 days )  crosses below SKStochastic ( DELL, 30 
       days, 20 days ) 

Macro Code:

ATTR MACRO KStochastic ( SECURITY Sec, PERIOD TimePeriod = 10 unit )
    RETURN
    100 * ( Close of Sec - TimePeriod lowest of Low of Sec ) /
          ( TimePeriod highest of High of Sec -
              TimePeriod lowest of Low of Sec )
ENDMACRO

SDStochastic

This macro is an average of the "SKStochastic" macro.

SDStochastic(Security,Timeperiod, Timeperiod2)

Example:

   SHOW 
     SD: SDStochastic ( DELL, 30 days, 20 days, 10 days )  
     SK: SKStochastic ( DELL, 30 days, 20 days )  
     t+1: percent_move from today to 1 week later  of DELL  
   WHEN 
       SDStochastic ( DELL, 30 days, 20 days, 10 days )  crosses below 
       SKStochastic ( DELL, 30 days, 20 days )

Macro Code:

ATTR MACRO SDStochastic ( SECURITY Sec, PERIOD TimePeriod1 = 10 unit,
                     PERIOD TimePeriod2 = 3 unit,
                     PERIOD TimePeriod3 = 3 unit )
    RETURN
         TimePeriod3 average of SKStochastic ( Sec, TimePeriod1, TimePeriod2 )
ENDMACRO

SKStochastic

This macro is sometimes referred to as "%D" in the market. It is the slower moving stochastic.

SKStochastic(Security, TimePeriod,TimePeriod2)

Example:

   SHOW 
     K: KStochastic ( DELL, 30 days )  
     SK: SKStochastic ( DELL, 30 days, 20 days )  
     t+1: percent_move from today to 1 week later  of DELL  
   WHEN 
       KStochastic ( DELL, 30 days )  crosses below SKStochastic ( DELL, 30 
       days, 20 days )

Macro Code:

ATTR MACRO SKStochastic ( SECURITY Sec, PERIOD TimePeriod1 = 10 unit,
                     PERIOD TimePeriod2 = 3 unit )
    RETURN
        TimePeriod2 average of KStochastic ( Sec, TimePeriod1 )
ENDMACRO

sum

Returns the sum total of all the values in the series during some specified time period. Holidays and missing values (expressed as Nan) have no effect on the sum. As with any study, if you want the sum to always include a set number of periods or days than use the term 'value' in lieu of day.

This study will ignore any values that are NaN. That is, it returns the sum of all the non-NaN values in the period n. If all the X values are NaN, sum returns a NaN.

Example 1:

   SHOW 
     average: 25 value sum of Close of AMD  / 25 
   WHEN 
       Date is 2002

Example 2:

   SHOW 
     US: US 
     between105and110: sum from 1 year ago  to today of IF 
                           Close of US is at least 105 
                         AND 
                           Close of US is less than 110 
                       THEN 1 
                       ELSE 0 
                       ENDIF   
   WHEN 
       Date is within 2 years

Trendline

Returns drawing of a line to connect a series of peaks or troughs on a Chart. Both uptrends and downtrends in a market can be defined in terms of trendlines.

Trendline (Price1, Date1, Price2, Date2)

Example:

   SHOW 
     CL: BAR of CL 
     Trend: Trendline ( 21.20, construct_date ( 1, 1, 2001 ), 17.85, 
            construct_date ( 2, 3, 2002 ) )  
   WHEN 
       Date is after 1/1/2001

Macro Code:

ATTR MACRO Trendline ( CONSTANT Price1, 
                       CONSTANT Date1, 
                       CONSTANT Price2,
                       CONSTANT Date2 )
VARS
   m
   x
   b
INITIALIZE
      x = current date
   AND
      m = ( Price2 - Price1 ) / ( Date2 - Date1 )
   AND
      b = Price1 - ( m * Date1 )
RETURN
   if x >= Date1
   then
      (m * x) + b     
   endif
ENDMACRO

true_midpoint

This study is very similar to the 'midpoint' study except 'High' is defined as the true High or the greater of either today's or yesterday's High and 'Low' is defined as the true Low or lesser of either today's or yesterday's Low. For most days, the true High will be identical to today's High and the true Low will be identical to today's low. The differences, where the previous day's value is selected, will occur on downside gap days (the range is below yesterday's range) or conversely upside gap days (the range is above yesterday's range). By using the 'true' value, we can factor in the downside or upside gap in price.

where H is the higher of the High of S and the previous Close of S, and L is the lower of the Low of S and the previous Close of S.

Example:

   SHOW 
     Bar: BAR of IBM 
     midpoint: true_midpoint of IBM  
     pmove: percent_move from today to 10 days later  of IBM  
   WHEN 
       IBM crosses above 20 day average of true_midpoint of IBM

true_range

The true_range indicator is the greatest of the following:

  • The current High less the current Low

  • The absolute value of: current High less the previous Close

  • The absolute value of: current Low less the previous Close

Example:

   SHOW 
     C: BAR of C 
     Range: true_range of C  
   WHEN 
       Date is within 5 years 
     AND 
       true_range of C  is more than 6

variance

This study returns the statistical variance of a population based on the values specified in the time period. Variance is the square of the standard deviation, which is a measure of data dispersion. A data series that has values that are widely dispersed will have a high standard deviation and variance.

We choose to use a different but equivalent formula to compute the above expression, so that it can be computed in a single pass. The actual formula used is

In the cases where there are less than two non-NaN values in n, variance returns NaN.

Example:

   SHOW 
     W: W 
     avg: 10 day average of front W  
     var: 20 day variance of 10 day average of front W   
   WHEN 
       20 day variance of 10 day average of front W   is less than 5

Volatility

Returns the high of the period divided by the low.

Volatility(Series)

Example:

   SHOW 
     Volatility: Volatility ( SUNW )  
   WHEN 
       Volatility ( SUNW )  is more than 1.1 
       repeated for 3 days

Macro Code:

COLUMN MACRO Volatility ( SECURITY Sec )
   RETURN
     High of Sec / Low of Sec
ENDMACRO

VolatilityIdx

Returns the exponential moving average of the true range. Refer to Exponential Average notes for weight info.

VolatilityIdx(Security, Weight)

Example:

   SHOW 
     Volatility: VolatilityIdx ( URBN, 1 / 21 )  
   WHEN 
       VolatilityIdx ( URBN, 1 / 21 )  crosses above 10 day average of 
       VolatilityIdx ( URBN, 1 / 21 )

Macro Code:

ATTR MACRO VolatilityIdx ( SECURITY Sec, CONSTANT Weight = 0.0714 )
   RETURN
     exponential_average ( TrueRange of Sec, Weight )
ENDMACRO

VolPriceTrend

Returns an index which takes the distance of the close of the day from the midpoint of the day, multiplies that times the volume and sums the results over time.

VolPriceTrend(Series, TimePeriod)

Example:

   SHOW 
     Trend: VolPriceTrend ( IBM, 50 days )  
     IBM: Close of IBM 
   WHEN 
       VolPriceTrend ( IBM, 50 days )  is less than 0 
       repeated for 10 times

Macro Code:

ATTR MACRO VolPriceTrend ( SECURITY Sec, PERIOD TimePeriod )
    RETURN
    Summation ( ( Close of Sec - ( High of Sec + Low of Sec ) / 2 ) *
                      Volume of Sec,
               TimePeriod )
ENDMACRO

VolumeAccum

VolumeAccum(Series)

Created by Mark Chaikin, the Volume Accumulation Oscillator shows the cumulative volume adjusted by the difference between the close and the midpoint of the day's range. Compared to the On Balance Volume (OBV) indicator which assigns all the day's volume to the buyers if a security closes up or to the sellers if it closes down, Volume Accumulation uses the relationship of the closing price to the mean price to assign a proportion to the volume.

Example:

   SHOW 
     1: on_balance_volume of IBM  
     2: VolumeAccum ( IBM )  
   WHEN 
       Date is within 1 year 

Macro Code:

COLUMN MACRO VolumeAccum ( SECURITY Sec )

    RETURN
        Sum from begin_of_time to today of
     ( ( Close of Sec - (( High of Sec + Low of Sec ) / 2) ) *
       Volume of Sec )

ENDMACRO

WildersRSI

Returns the Welles Wilder's Relative Strength Index indicator, a popular overbought-oversold measure. This study is very similar to simple_rsi, except Wilder's version uses a form of exponential smoothing where simple_rsi uses a simple moving average.

This study compares the relative strength of prices gains (closes that are higher than the previous day's close) versus price losses (closes that are lower than the previous day's close) by using an exponentially smooth average of these values for some specified period of time.

Like simple_rsi, wilders_rsi may be performed for any time period. Wilder originally suggested 14 days, however, technicians sometimes prefer a shorter/more sensitive period of time such as 5 or 7 days. This study will range between 0 and 100.

Industry standards derive the overbought and oversold indicators at levels that range around 70 (overbought) and 30 (oversold).

where U and D are the exponential average of the 1-period up-and down-moves of X, respectively, using the weight w. That is, U and D are given by

For an explanation of the weight w, see the discussion in the section called “exponential_average”.

WildersADX

The familiar average directional movement index is simply the directional movement index (WildersDX) averaged for the time period chosen for study related to the previous day's average directional movement index.

WildersADX(Series, Weight)

Example:

   SHOW 
     adx: WildersADX ( BO, (1 / 14) )  
     adxr: WildersADXR ( BO, (1 / 14) )  
   WHEN 
       Date is within 1 year 
     AND 
       WildersADX ( BO, (1 / 14) )  crosses above WildersADXR ( BO, (1 / 14
       ) )

Macro Code:

ATTR MACRO WildersADX ( SECURITY Series, CONSTANT Weight = 0.071428571 )
VARS
   DMPlus
   DMMinus
   DMSum
   DMDiff
   RawDX
INITIALIZE
   DMPlus := WildersDIPlus ( Series, Weight )
AND
   DMMinus := WildersDIMinus ( Series, Weight )
AND
   DMSum := DMPlus + DMMinus
AND
   DMDiff := DMPlus - DMMinus
AND
   RawDX := AbsVal ( ( DMDiff / DMSum ) * 100 )
RETURN
      if Close of Series is defined
      then
          exponential_average ( RawDX, Weight )
      endif
ENDMACRO

WildersADXR

Returns an exponentially smoothed version of the WildersADX study (see the section called “WildersADX”).

WildersADXR(Series, Weight)

Example:

   SHOW 
     adx: WildersADX ( BO, (1 / 14) )  
     adxr: WildersADXR ( BO, (1 / 14) )  
   WHEN 
       Date is within 1 year 
     AND 
       WildersADX ( BO, (1 / 14) )  crosses above WildersADXR ( BO, (1 / 14
       ) )

Macro Code:

ATTR MACRO WildersADXR ( SECURITY Series, CONSTANT Weight = 0.071428571 )
RETURN
   (  WildersADX ( Series, Weight ) +
      WildersADX ( Series, Weight ) 14 days ago ) / 2
ENDMACRO

WildersDIMinus

Returns a momentum indicator typically used to identify downtrend directional behavior in the market and developed by Welles Wilder. This study is calculated by dividing the exponentially Positive Directional Movement (those days when the difference between today's low minus the previous day's low is greater than the difference between today's high minus the previous day's high) by the smoothed True Range.

WildersDIMinus (Series, Weight)

Example:

   SHOW 
     diminus: WildersDIMinus ( BO, (1 / 14) )  
     t+1w: percent_move from today to 1 week later  of BO  
     t+2w: percent_move from today to 2 weeks later  of BO  
   WHEN 
       Date is within 5 years 
     AND 
       WildersDIMinus ( BO, (1 / 14) )  crosses below 15

Macro Code:

ATTR MACRO WildersDIMinus ( SECURITY Series, CONSTANT Weight = 0.071428571 )
    VARS
       STRFOO
       SPDM
       SMDM
DEFINE COLUMN MACRO MinusDM ( SECURITY Series )
 RETURN
  if Close of Series is defined then
   if InsideDay ( Series )
   then 0
   else
      if
        High of Series - High of Series 1 unit ago > 
        Low of Series 1 unit ago - Low of Series 
      then 0
      else
        Low of Series 1 unit ago - Low of Series
      endif
   endif
  endif
ENDMACRO
INITIALIZE
   STRFOO := exponential_average ( TrueRange of Series, Weight )
AND
   SMDM := exponential_average ( MinusDM of Series, Weight ) / STRFOO
RETURN
   if Close of Series is defined
   then
     SMDM * 100
   endif
ENDMACRO

WildersDIPlus

Returns a momentum indicator typically used to identify up-trend directional behavior in the market and developed by Welles Wilder. This study is calculated by dividing the exponentially smoothed Positive Directional Movement (those days when the difference between today's high minus the previous day's high is greater than the difference between today's low minus the previous day's low) by the smoothed True Range.

WildersDIPlus(Series, Weight)

Example:

   SHOW 
     diplus: WildersDIPlus ( BO, (1 / 14) )  
     t+1w: percent_move from today to 1 week later  of BO  
     t+2w: percent_move from today to 2 weeks later  of BO  
   WHEN 
       WildersDIPlus ( BO, (1 / 14) )  crosses above 40

Macro Code:

ATTR MACRO WildersDIPlus ( SECURITY Series, CONSTANT Weight = 0.071428571 )
VARS
   STRFOO
   SPDM
   SMDM
DEFINE
   COLUMN MACRO PlusDM ( SECURITY Series )
   RETURN
      if Close of Series is defined
      then
         if InsideDay ( Series )
         then 0
         else
            if High of Series - High of Series 1 unit ago >
               Low of Series 1 unit ago - Low of Series
           then
              High of Series - High of Series 1 unit ago
            else
              0
            endif
         endif
      endif
   ENDMACRO
INITIALIZE
  STRFOO := exponential_average ( TrueRange of Series, Weight )
AND
  SPDM := exponential_average ( PlusDM of Series, Weight ) / STRFOO
     
RETURN
   if Close of Series is defined
   then SPDM * 100
   endif
ENDMACRO 

WildersDX

WildersDX returns the equivalent to Welles Wilder's Directional Movement equation. This calculation divides the difference between DI+ and DI- (true directional movement) and sum of DI+ and DI- (total percentage of directional movement), and then multiplies this value by 100%.

The directional movement index (DX) is thus an accounting or a scoring between 0 - 100 of the power of the trend, be the trend up or down, a high score means the market is strongly trending (up or down) and a low score bespeaks of weak or no trend.

WildersDX(Series, Weight)

Example:

   SHOW 
     adx: WildersDX ( BO, (1 / 14) )  
     adxr: WildersADXR ( BO, (1 / 14) )  
   WHEN 
       Date is within 1 year 
     AND 
       WildersDX ( BO, (1 / 14) )  crosses above WildersADXR ( BO, (1 / 14
       ) )

Macro Code:

ATTR MACRO WildersDX ( SECURITY Series, CONSTANT Weight = 0.071428571 )
VARS
   DIPlus
   DIMinus
   DISum
   DIDiff
   RawDX
INITIALIZE
   DIPlus := WildersDIPlus ( Series, Weight )
AND
   DIMinus := WildersDIMinus ( Series, Weight )
AND
   DISum := DIPlus + DIMinus
AND
   DIDiff := DIPlus - DIMinus
AND
   RawDX := AbsVal ( ( DIDiff / DISum ) * 100 )
RETURN
      if Close of Series is defined
      then
         RawDX
      endif
ENDMACRO

WildersRSI

Returns the Welles Wilder's Relative Strength Index indicator, a popular overbought-oversold measure. This study is very similar to simple_rsi, except Wilder's version uses a form of exponential smoothing where simple_rsi uses a simple moving average.

This study compares the relative strength of prices gains (closes that are higher than the previous day's close) versus price losses (closes that are lower than the previous day's close) by using an exponentially smooth average of these values for some specified period of time.

Like simple_rsi, wilders_rsi may be performed for any time period. Wilder originally suggested 14 days, however, technicians sometimes prefer a shorter/more sensitive period of time such as 5 or 7 days. This study will range between 0 and 100.

Industry standards derive the overbought and oversold indicators at levels that range around 70 (overbought) and 30 (oversold).

WildersRSI(Series, Weight)

Example:

   SHOW 
     rsi: WildersRSI ( BO, (1 / 14) )  
     t+1w: percent_move from today to 1 week later  of BO  
     t+2w: percent_move from today to 2 weeks later  of BO  
   WHEN 
       WildersRSI ( BO, (1 / 14) )  crosses above 75

Macro Code:

ATTR MACRO WildersRSI ( ATTR Series, CONSTANT Weight )
    VARS
    Gains
    Losses
    INITIALIZE
    Gains := exponential_average ( if Series is up then
                                      1 unit move of Series
                                 else
                                     0
                                 endif,
                                 Weight )
      AND
    Losses := exponential_average ( if Series is down then
                                      0 - 1 unit move of Series
                               else
                                      0
                                  endif,
                               Weight )
    RETURN
          100 - 100 / ( 1 + Gains / Losses )
ENDMACRO

williamsr

This study is a momentum indicator and is used to calibrate the position of the Close relative to the High for some period. Successive values of 100 for the study may indicate an upward trend since the price of a series closes at its High. Conversely, successive values of 0 may indicate a downward trend since the price of the series closes at its Low.

WilliamsVolAD

Returns the Larry Williams Volume Accumulation-Distribution indicator.

WilliamsVolAD(Security, TimePeriod)

Example:

   SHOW 
     AccDist: WilliamsVolAD ( JDSU, 10 days )  
   WHEN 
       WilliamsVolAD ( JDSU, 10 days )  is down

Macro Code:

ATTR MACRO WilliamsVolAD ( SECURITY Sec, PERIOD TimePeriod )
    RETURN
    Summation ( Volume of Sec * ( Close of Sec - Open of Sec ) /
                                ( High of Sec - Low of Sec ),
              TimePeriod )
ENDMACRO

ZeroFill

Returns the time series of the attribute filled with a zero value on dates or times that previously were NAN. This is recommended when applying a mathematical calculation across more than one symbol because a value plus a NAN equals a NAN.

ZeroFill(Series)

Example:

   SHOW 
     Close: Close of IBM 
     divs: ExDividends of IBM 
     sumWoZero: sum from 1/1/2004 to today of ExDividends of IBM  
     sumWZero: ZeroFill ( sum from 1/1/2004 to today of ExDividends of IBM  )  
   WHEN 
       Date is after 1/1/2004 

Macro Code:

ATTR MACRO ZeroFill (ATTR Series) 
 RETURN 
        if Series is defined 
            then Series 
            else 0 
        ENDIF 
ENDMACRO