CUSIP Source Code

From EggeWiki
(Redirected from LUHN Source Code)

The algorithm used to assign [CUSIP]s a variation of the LUHN algorithm. CUSIPs are very important for being able to uniquely identify securities. For example, I've used the code below to validate when a user has entered a valid CUSIP number.

Source Code

/**
 * This class impliments the 
 * Modulus 10 Double Add Double in order
 * to check if a <a href="http://en.wikipedia.org/wiki/CUSIP">CUSIP</A>
 * is valid.
 * @author Brian Egge
 */
public class CusipValidator {

  public static boolean isValid(String ccNum) {

    char number[] = ccNum.toCharArray();

    int len = number.length;
    int sum = 0;
    for (int i = 0; i < len - 1; i++) {
      int num = mapChar(number[i]);

      // Double all the odd digits
      if (i % 2 != 0)
        num *= 2;

      // Combine digits.  i.e., 16 = (1 + 6) = 7
      if (num > 9)
        num = (num % 10) + (num / 10);
      sum += num;
    }

    int checkDigit = mapChar(number[number.length - 1]);
    
    // This is the mathmatical modulus - not the remainder.  i.e., 10 mod 7 = 3
    int mod = (10 - (sum % 10)) % 10;
    if (mod == checkDigit) {
      return true;
    }

    return false;
  }

  /**
   * Standard & Poor's maps A..Z to 10..35 
   * @param c
   * @return numeric value of the letter
   */
  private static int mapChar(char c) {
    if (c >= '0' && c <= '9')
      return c - '0';
    return c - 'A' + 10;
  }
}

Test case

public class CusipValidatorTest extends TestCase {

  public void testCUSIP() {
    assertTrue(CusipValidator.isValid("31430F200"));
    assertTrue(CusipValidator.isValid("037833100")); // Apple
    assertTrue(CusipValidator.isValid("316549401"));
    assertTrue(CusipValidator.isValid("022615AC2"));
    assertTrue(CusipValidator.isValid("931142103")); // Walmart
    assertTrue(CusipValidator.isValid("883199AQ4"));
    assertTrue(CusipValidator.isValid("14911QGW5"));
    assertTrue(CusipValidator.isValid("14911QHM6"));
    assertTrue(CusipValidator.isValid("339072407"));
    assertTrue(CusipValidator.isValid("3133XBC78"));
    assertTrue(CusipValidator.isValid("808905AB9"));
    
    assertFalse(CusipValidator.isValid("2005"));
    assertFalse(CusipValidator.isValid("?"));
  }

}