Example usage for java.time LocalDate getYear

List of usage examples for java.time LocalDate getYear

Introduction

In this page you can find the example usage for java.time LocalDate getYear.

Prototype

public int getYear() 

Source Link

Document

Gets the year field.

Usage

From source file:ch.algotrader.option.OptionSymbol.java

/**
 * Generates the ISIN for the specified {@link ch.algotrader.entity.security.OptionFamily}.
 *//*from   w  ww  . j  a v  a2s.co  m*/
public static String getIsin(OptionFamily family, LocalDate expiration, OptionType type, BigDecimal strike) {

    String week = family.isWeekly() ? DateTimePatterns.WEEK_OF_MONTH.format(expiration) : "";

    String month;
    if (OptionType.CALL.equals(type)) {
        month = monthCallEnc[expiration.getMonthValue() - 1];
    } else {
        month = monthPutEnc[expiration.getMonthValue() - 1];
    }

    int yearIndex = expiration.getYear() % 10;
    String year = yearEnc[yearIndex];

    String strike36 = BaseConverterUtil.toBase36(strike.multiply(new BigDecimal(10)).intValue());
    String strikeVal = strike.scale() + StringUtils.leftPad(strike36, 4, "0");

    StringBuilder buffer = new StringBuilder();
    buffer.append("1O");
    buffer.append(family.getIsinRoot() != null ? family.getIsinRoot() : family.getSymbolRoot());
    buffer.append(week);
    buffer.append(month);
    buffer.append(year);
    buffer.append(strikeVal);

    return buffer.toString();
}

From source file:net.tradelib.apps.StrategyBacktest.java

public static void run(Strategy strategy) throws Exception {
    // Setup the logging
    System.setProperty("java.util.logging.SimpleFormatter.format",
            "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n");
    LogManager.getLogManager().reset();
    Logger rootLogger = Logger.getLogger("");
    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) {
        FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.FINEST);
        rootLogger.addHandler(logHandler);
    }//from   ww w . jav a2  s  . c o  m

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) {
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(new SimpleFormatter());
        consoleHandler.setLevel(Level.INFO);
        rootLogger.addHandler(consoleHandler);
    }

    rootLogger.setLevel(Level.INFO);

    // Setup Hibernate
    // Configuration configuration = new Configuration();
    // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    // SessionFactory factory = configuration.buildSessionFactory(builder.build());

    Context context = new Context();
    context.dbUrl = BacktestCfg.instance().getProperty("db.url");

    HistoricalDataFeed hdf = new SQLDataFeed(context);
    hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties"));
    context.historicalDataFeed = hdf;

    HistoricalReplay hr = new HistoricalReplay(context);
    context.broker = hr;

    strategy.initialize(context);
    strategy.cleanupDb();

    long start = System.nanoTime();
    strategy.start();
    long elapsedTime = System.nanoTime() - start;
    System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    start = System.nanoTime();
    strategy.updateEndEquity();
    strategy.writeExecutionsAndTrades();
    strategy.writeEquity();
    elapsedTime = System.nanoTime() - start;
    System.out
            .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    System.out.println();

    // Write the strategy totals to the database
    strategy.totalTradeStats();

    // Write the strategy report to the database and obtain the JSON
    // for writing it to the console.
    JsonObject report = strategy.writeStrategyReport();

    JsonArray asa = report.getAsJsonArray("annual_stats");

    String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix");
    if (!Strings.isNullOrEmpty(csvPath)) {
        csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE)
                + ".csv";
    }

    String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix");
    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + ordersCsvPath;
    }

    String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix");
    if (!Strings.isNullOrEmpty(actionsPath)) {
        actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + actionsPath;
    }

    // If emails are being send out
    String signalText = StrategyText.build(context.dbUrl, strategy.getName(),
            strategy.getLastTimestamp().toLocalDate(), "   ", csvPath, '|');

    System.out.println(signalText);
    System.out.println();

    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(),
                strategy.getLastTimestamp().toLocalDate(), ordersCsvPath);
    }

    File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile,
                signalText + System.getProperty("line.separator") + System.getProperty("line.separator"));
    }

    String message = "";

    if (asa.size() > 0) {
        // Sort the array
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        for (int ii = 0; ii < asa.size(); ++ii) {
            int year = asa.get(ii).getAsJsonObject().get("year").getAsInt();
            map.put(year, ii);
        }

        for (int id : map.values()) {
            JsonObject jo = asa.get(id).getAsJsonObject();
            String yearStr = String.valueOf(jo.get("year").getAsInt());
            String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt());
            String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble());
            String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt());
            String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt());
            String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble());
            String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr
                    + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr;
            message += str + "\n";
        }

        String pnlStr = String.format("$%,d", report.get("pnl").getAsInt());
        String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble());
        String ddStr = String.format("$%,d", report.get("avgdd").getAsInt());
        String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble());
        String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble());
        String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr
                + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr;
        message += str + "\n";
    } else {
        message += "\n";
    }

    // Global statistics
    JsonObject jo = report.getAsJsonObject("total_peak");
    String dateStr = jo.get("date").getAsString();
    int maxEndEq = jo.get("equity").getAsInt();
    jo = report.getAsJsonObject("total_maxdd");
    double cash = jo.get("cash").getAsDouble();
    double pct = jo.get("pct").getAsDouble();
    message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n"
            + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";

    if (report.has("latest_peak") && report.has("latest_maxdd")) {
        jo = report.getAsJsonObject("latest_peak");
        LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE);
        maxEndEq = jo.get("equity").getAsInt();
        jo = report.getAsJsonObject("latest_maxdd");
        cash = jo.get("cash").getAsDouble();
        pct = jo.get("pct").getAsDouble();
        message += "\n" + Integer.toString(ld.getYear()) + " equity peak ["
                + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n"
                + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";
    }

    message += "\n" + "Avg Trade PnL: "
            + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: "
            + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: "
            + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: "
            + Integer.toString(report.get("num_trades").getAsInt());

    System.out.println(message);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true);
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.sendgrid.net");
        props.put("mail.smtp.port", "587");

        String user = BacktestCfg.instance().getProperty("email.user");
        String pass = BacktestCfg.instance().getProperty("email.pass");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pass);
            }
        });

        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from")));
            msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients"));
            msg.setSubject(strategy.getName() + " Report ["
                    + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]");
            msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message);
            Transport.send(msg);
        } catch (Exception ee) {
            Logger.getLogger("").warning(ee.getMessage());
        }
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) {
        HashMap<String, String> fileMap = new HashMap<String, String>();
        if (!Strings.isNullOrEmpty(actionsPath))
            fileMap.put(actionsPath, actionsPath);
        if (!Strings.isNullOrEmpty(ordersCsvPath))
            fileMap.put(ordersCsvPath, ordersCsvPath);
        String user = BacktestCfg.instance().getProperty("sftp.user");
        String pass = BacktestCfg.instance().getProperty("sftp.pass");
        String host = BacktestCfg.instance().getProperty("sftp.host");
        SftpUploader sftp = new SftpUploader(host, user, pass);
        sftp.upload(fileMap);
    }
}

From source file:no.imr.stox.functions.acoustic.PgNapesIO.java

public static void convertPgNapesToLuf20(String path, String fileName, String outFileName) {
    try {//from   w ww  .j  av a  2s  .co  m
        List<String> acList = Files.readAllLines(Paths.get(path + "/" + fileName + ".txt"));
        List<String> acVList = Files.readAllLines(Paths.get(path + "/" + fileName + "Values.txt"));
        if (acList.isEmpty() || acVList.isEmpty()) {
            return;
        }
        acList.remove(0);
        acVList.remove(0);
        List<DistanceBO> dList = acList.stream().map(s -> {
            DistanceBO d = new DistanceBO();
            String[] str = s.split("\t", 14);
            d.setNation(str[0]);
            d.setPlatform(str[1]);
            d.setCruise(str[2]);
            d.setLog_start(Conversion.safeStringtoDoubleNULL(str[3]));
            d.setStart_time(Date.from(LocalDateTime.of(Conversion.safeStringtoIntegerNULL(str[4]),
                    Conversion.safeStringtoIntegerNULL(str[5]), Conversion.safeStringtoIntegerNULL(str[6]),
                    Conversion.safeStringtoIntegerNULL(str[7]), Conversion.safeStringtoIntegerNULL(str[8]), 0)
                    .toInstant(ZoneOffset.UTC)));
            d.setLat_start(Conversion.safeStringtoDoubleNULL(str[9]));
            d.setLon_start(Conversion.safeStringtoDoubleNULL(str[10]));
            d.setIntegrator_dist(Conversion.safeStringtoDoubleNULL(str[11]));
            FrequencyBO freq = new FrequencyBO();
            d.getFrequencies().add(freq);
            freq.setTranceiver(1); // implicit in pgnapes
            freq.setUpper_interpret_depth(0d);
            freq.setUpper_integrator_depth(0d);
            freq.setDistance(d);
            freq.setFreq(Conversion.safeStringtoIntegerNULL(str[12]));
            freq.setThreshold(Conversion.safeStringtoDoubleNULL(str[13]));
            return d;
        }).collect(Collectors.toList());
        // Fill in sa values
        acVList.forEach(s -> {
            String[] str = s.split("\t", 11);
            String cruise = str[2];
            Double log = Conversion.safeStringtoDoubleNULL(str[3]);
            Integer year = Conversion.safeStringtoIntegerNULL(str[4]);
            Integer month = Conversion.safeStringtoIntegerNULL(str[5]);
            Integer day = Conversion.safeStringtoIntegerNULL(str[6]);
            if (log == null || year == null || month == null || day == null) {
                return;
            }
            DistanceBO d = dList.parallelStream().filter(di -> {
                if (di.getCruise() == null || di.getLog_start() == null || di.getStart_time() == null) {
                    return false;
                }
                LocalDate ld = di.getStart_time().toInstant().atZone(ZoneOffset.UTC).toLocalDate();
                return cruise.equals(di.getCruise()) && log.equals(di.getLog_start())
                        && year.equals(ld.getYear()) && month.equals(ld.getMonthValue())
                        && day.equals(ld.getDayOfMonth());
            }).findFirst().orElse(null);
            if (d == null) {
                return;
            }
            FrequencyBO freq = d.getFrequencies().get(0);

            String species = str[7];
            Integer acocat = PgNapesEchoConvert.getAcoCatFromPgNapesSpecies(species);
            Double chUppDepth = Conversion.safeStringtoDoubleNULL(str[8]);
            Double chLowDepth = Conversion.safeStringtoDoubleNULL(str[9]);
            Double sa = Conversion.safeStringtoDoubleNULL(str[10]);
            if (acocat == null || sa == null || sa == 0d || chLowDepth == null || chUppDepth == null) {
                return;
            }
            if (d.getPel_ch_thickness() == null) {
                d.setPel_ch_thickness(chLowDepth - chUppDepth);
            }
            Integer ch = (int) (chLowDepth / d.getPel_ch_thickness() + 0.5);
            SABO sabo = new SABO();
            sabo.setFrequency(freq);
            freq.getSa().add(sabo);
            sabo.setAcoustic_category(acocat + "");
            sabo.setCh_type("P");
            sabo.setCh(ch);
            sabo.setSa(sa);
        });
        // Calculate number of pelagic channels

        /*dList.stream().forEach(d -> {
        FrequencyBO f = d.getFrequencies().get(0);
        Integer minCh = f.getSa().stream().map(SABO::getCh).min(Integer::compare).orElse(null);
        Integer maxCh = f.getSa().stream().map(SABO::getCh).max(Integer::compare).orElse(null);
        if (maxCh != null && minCh != null) {
            f.setNum_pel_ch(maxCh - minCh + 1);
        }
        });*/

        if (dList.isEmpty()) {
            return;
        }
        DistanceBO d = dList.get(0);
        String cruise = d.getCruise();
        String nation = d.getNation();
        String pl = d.getPlatform();
        ListUser20Writer.export(cruise, nation, pl, path + "/" + cruise + outFileName + ".xml", dList);

    } catch (IOException ex) {
        Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ch.algotrader.future.FutureSymbol.java

/**
 * Generates the symbol for the specified {@link ch.algotrader.entity.security.FutureFamily}.
 *
 * Example/*from   w  w w.j a v  a  2  s  .c om*/
 *     <table>
 *     <tr><td><b>Pattern</b></td><td><b>Description</b></td><td><b>Example</b></td></tr>
 *     <tr><td>N</td><td>Name</td><td>CrudeOil</td></tr>
 *     <tr><td>CR</td><td>SymbolRoot</td><td>CL</td></tr>
 *     <tr><td>C</td><td>Currency</td><td>USD</td></tr>
 *     <tr><td>CS</td><td>ContractSize</td><td>1000</td></tr>
 *     <tr><td>M</td><td>Month 1-digit</td><td>6</td></tr>
 *     <tr><td>MM</td><td>Month 2-digit</td><td>06</td></tr>
 *     <tr><td>MMM</td><td>Month Short</td><td>JUN</td></tr>
 *     <tr><td>MMMM</td><td>Month Long</td><td>June</td></tr>
 *     <tr><td>YY</td><td>Year 2-digit</td><td>16</td></tr>
 *     <tr><td>YYYY</td><td>Year 4-digit</td><td>2016</td></tr>
 *     </table>
 */
public static String getSymbol(SecurityFamily family, LocalDate expiration, String pattern) {

    String[] placeHolders = new String[] { "N", "SR", "CS", "C", "MMMM", "MMM", "MM", "MR", "YYYY", "YY",
            "YR" };

    String[] values = new String[] { family.getName(), family.getSymbolRoot(),
            RoundUtil.getBigDecimal(family.getContractSize(), 0).toString(), family.getCurrency().toString(),
            DateTimePatterns.MONTH_LONG.format(expiration).toUpperCase(),
            DateTimePatterns.MONTH_SHORT.format(expiration).toUpperCase(),
            DateTimePatterns.MONTH_2_DIGIT.format(expiration).toUpperCase(),
            monthEnc[expiration.getMonth().getValue() - 1], DateTimePatterns.YEAR_4_DIGIT.format(expiration),
            DateTimePatterns.YEAR_2_DIGIT.format(expiration), yearEnc[expiration.getYear() % 10] };

    return StringUtils.replaceEach(pattern, placeHolders, values);
}

From source file:daylightchart.daylightchart.calculation.RiseSetUtility.java

@SuppressWarnings("boxing")
private static RawRiseSet calculateRiseSet(final Location location, final LocalDate date,
        final boolean useDaylightTime, final boolean inDaylightSavings, final TwilightType twilight) {
    if (location != null) {
        sunAlgorithm.setLocation(location.getDescription(),
                location.getPointLocation().getLatitude().getDegrees(),
                location.getPointLocation().getLongitude().getDegrees());
        sunAlgorithm/*from  w  ww  .  j a  v  a2s .c o m*/
                .setTimeZoneOffset(DefaultTimezones.getStandardTimeZoneOffsetHours(location.getTimeZoneId()));
    }
    sunAlgorithm.setDate(date.getYear(), date.getMonthValue(), date.getDayOfMonth());
    final double[] sunriseSunset = sunAlgorithm.calcRiseSet(twilight.getHorizon());

    if (useDaylightTime && inDaylightSavings) {
        if (!Double.isInfinite(sunriseSunset[0])) {
            sunriseSunset[0] = sunriseSunset[0] + 1;
        }
        if (!Double.isInfinite(sunriseSunset[1])) {
            sunriseSunset[1] = sunriseSunset[1] + 1;
        }
    }

    final RawRiseSet riseSet = new RawRiseSet(location, date, useDaylightTime && inDaylightSavings,
            sunriseSunset[0], sunriseSunset[1]);
    return riseSet;

}

From source file:no.imr.stox.functions.utils.CovariateUtils.java

/**
 * Get temporal full covariate key from a date and temporal with year
 *
 * @param covSourceType/*from  ww w .  j  av  a 2 s  . c  o m*/
 * @param d
 * @param tempM
 * @return
 */
public static String getTemporalFullKey(String covSourceType, LocalDate d, MatrixBO tempM) {
    if (d == null) {
        return null;
    }
    String timeInterval = null;
    for (String cov : tempM.getRowColKeys(covSourceType)) {
        timeInterval = getTimeIntervalByCov(cov);
        break;
    }
    if (timeInterval == null) {
        return null;
    }
    // Find if any of the covariates relates to year
    Boolean seasonal = true;
    for (String cov : tempM.getRowColKeys(covSourceType)) {
        seasonal = CovariateUtils.isCovariateSeasonal(cov);
        break;
    }
    String year = Conversion.safeIntegertoString(d.getYear());
    switch (timeInterval) {
    case Functions.COVARIATETIMEINTERVAL_YEAR:
        return year;
    case Functions.COVARIATETIMEINTERVAL_PERIOD:
        for (String cov : tempM.getRowColKeys(covSourceType)) {
            String def = (String) tempM.getRowColValue(covSourceType, cov);
            if (isInPeriod(d, def)) {
                return (seasonal ? year + "." : "") + cov;
            }
        }
        break;
    default:
        Integer season = CovariateUtils.getSeasonByDate(d, timeInterval);
        String seasonType = CovariateUtils.getSeasonTypeByTimeInterval(timeInterval);
        String code = seasonType + season;
        if (!seasonal) {
            code = year + "." + code;
        }
        return code;
    }
    return null;
}

From source file:Main.java

@Override
public LocalDate queryFrom(TemporalAccessor temporal) {
    LocalDate date = LocalDate.from(temporal);
    LocalDate currentYearMLKDay = getMartinLutherKingDayForDateInYear(date.getYear());

    Period periodToCurrentYearMLKDay = Period.between(date, currentYearMLKDay);

    if (periodToCurrentYearMLKDay.isNegative() || periodToCurrentYearMLKDay.isZero()) {
        return getMartinLutherKingDayForDateInYear(date.getYear() + 1);
    } else {//from  w w  w .  jav  a2 s.c  om
        return currentYearMLKDay;
    }
}

From source file:com.clearprecision.microservices.reference.jetty.service.BirthdayService.java

public Birthday getNumberOfDaysUntilBirthday(Integer day, Integer month) {
    Birthday bd = new Birthday();

    LocalDate date = LocalDate.now();
    LocalDate birthday = LocalDate.of(date.getYear(), month, day);
    long days = date.until(birthday, ChronoUnit.DAYS);

    bd.setDate(days + " days until your birthday");
    return bd;/* ww w .ja  v  a  2  s .  c o m*/
}

From source file:io.sqp.core.types.SqpDateTest.java

@Test(dataProvider = "dateValues")
public void CanDecodeFromJson(byte[] content, DataFormat format) throws Exception {
    ObjectMapper mapper = JacksonObjectMapperFactory.objectMapper(format);

    Object dateObj = mapper.readValue(content, Object.class);
    SqpDate sqpDate = SqpDate.fromJsonFormatValue(dateObj);

    LocalDate localDate = sqpDate.asLocalDate();
    assertThat(localDate.getYear(), is(2015));
    assertThat(localDate.getMonth(), is(Month.JUNE));
    assertThat(localDate.getDayOfMonth(), is(28));
}

From source file:ch.algotrader.option.OptionSymbol.java

/**
 * Generates the symbole for the specified {@link ch.algotrader.entity.security.OptionFamily}.
 *
 * Example//from   w w w.  j  a v a 2  s. com
 *     <table>
 *     <tr><td><b>Pattern</b></td><td><b>Description</b></td><td><b>Example</b></td></tr>
 *     <tr><td>N</td><td>Name</td><td>CrudeOil</td></tr>
 *     <tr><td>CR</td><td>SymbolRoot</td><td>CL</td></tr>
 *     <tr><td>C</td><td>Currency</td><td>USD</td></tr>
 *     <tr><td>CS</td><td>ContractSize</td><td>1000</td></tr>
 *     <tr><td>M</td><td>Month 1-digit</td><td>6</td></tr>
 *     <tr><td>MM</td><td>Month 2-digit</td><td>06</td></tr>
 *     <tr><td>MMM</td><td>Month Short</td><td>JUN</td></tr>
 *     <tr><td>MMMM</td><td>Month Long</td><td>June</td></tr>
 *     <tr><td>YY</td><td>Year 2-digit</td><td>16</td></tr>
 *     <tr><td>YYYY</td><td>Year 4-digit</td><td>2016</td></tr>
 *     <tr><td>W</td><td>Week of Month</td><td>3</td></tr>
 *     <tr><td>T</td><td>Type Short</td><td>C</td></tr>
 *     <tr><td>TT</td><td>Type Long</td><td>CALL</td></tr>
 *     <tr><td>S</td><td>Strike</td><td>500</td></tr>
 *     </table>
 */
public static String getSymbol(OptionFamily family, LocalDate expiration, OptionType type, BigDecimal strike,
        String pattern) {

    String[] placeHolders = new String[] { "N", "SR", "CS", "C", "MMMM", "MMM", "MM", "MR", "YYYY", "YY", "YR",
            "W", "TT", "T", "S" };

    String[] values = new String[] { family.getName(), family.getSymbolRoot(),
            RoundUtil.getBigDecimal(family.getContractSize(), 0).toString(), family.getCurrency().toString(),
            DateTimePatterns.MONTH_LONG.format(expiration).toUpperCase(),
            DateTimePatterns.MONTH_SHORT.format(expiration).toUpperCase(),
            DateTimePatterns.MONTH_2_DIGIT.format(expiration).toUpperCase(),
            OptionType.CALL.equals(type) ? monthCallEnc[expiration.getMonth().getValue() - 1]
                    : monthPutEnc[expiration.getMonthValue() - 1],
            DateTimePatterns.YEAR_4_DIGIT.format(expiration), DateTimePatterns.YEAR_2_DIGIT.format(expiration),
            yearEnc[expiration.getYear() % 10], DateTimePatterns.WEEK_OF_MONTH.format(expiration),
            type.toString(), type.toString().substring(0, 1), strike.toString() };

    return StringUtils.replaceEach(pattern, placeHolders, values);
}