Example usage for org.jfree.data.time TimeSeries add

List of usage examples for org.jfree.data.time TimeSeries add

Introduction

In this page you can find the example usage for org.jfree.data.time TimeSeries add.

Prototype

public void add(RegularTimePeriod period, Number value) 

Source Link

Document

Adds a new data item to the series and sends a org.jfree.data.general.SeriesChangeEvent to all registered listeners.

Usage

From source file:de.fau.amos.ChartRenderer.java

/**
 * //from   w  w  w.ja va 2s .  c o  m
 * Creates TimeSeriesCollection by querying energy data from database.
 * 
 * @param granularity Accuracy of distinguishment of displayed values (Summarise data to hours, days, months, years).
 * @param startTime Start of queried period.
 * @param endTime End of queried period.
 * @param sumOrAvg Shall values be added or averaged.
 * @param groupParameters Controlpoints that are affected.
 * @param unit Sets Unit (kWh or kWh/TNF)
 * @return TimeSeriesCollection that privedes the basis for creation of a png-chart
 */
private TimeSeriesCollection createTimeCollection(String granularity, String startTime, String endTime,
        String sumOrAvg, String groupParameters, String unit) {

    //time series containing all data
    TimeSeriesCollection collection = new TimeSeriesCollection();
    //split groupParameter string to get all queryed groups seperated
    groupParameters = groupParameters.replace("||", "splitHere");
    String[] groups = groupParameters.split("splitHere");

    //handle groups one after another
    for (int i = 0; i < groups.length; i++) {
        //get group name
        String groupName = groups[i].contains("'") ? groups[i].substring(0, groups[i].indexOf("'")) : groups[i];
        groups[i] = groups[i].contains("'") ? groups[i].substring(groupName.length()) : "";

        if (!groups[i].contains("|")) {
            continue;
        }
        //get used plants
        String plants = groups[i].substring(groups[i].indexOf("|") + 1);

        //prepare queryString
        groups[i] = groups[i].substring(0, groups[i].indexOf("|"));

        //generate series for group
        TimeSeries series = new TimeSeries(groupName);

        ResultSet rs = null;

        //skip group if nothing is selected to query
        if (groups[i].trim() != "") {
            if ("1".equals(unit)) {
                //query kWh
                rs = SQL.queryToResultSet("select * from (select round(" + sumOrAvg
                        + "(gruppenWert),4), gruppenZeit from(select " + sumOrAvg
                        + "(wert) as gruppenWert,control_point_name, zeit1 as gruppenZeit from (select "
                        + sumOrAvg + "(value)as wert,control_point_name,date_trunc('" + granularity
                        + "',measure_time)as zeit1 from measures inner join controlpoints on measures.controlpoint_id=controlpoints.controlpoints_id where measure_time >= '"
                        + startTime + "' AND measure_time < '" + endTime + "' AND controlpoints_id in("
                        + groups[i]
                        + ") group by measure_time,control_point_name)as data group by zeit1,control_point_name)as groupedByTime group by gruppenZeit)as result order by gruppenZeit"
                        + ";");
            } else if ("2".equals(unit)) {
                //query kWh/TNF (only as sum, not avg)

                rs = SQL.queryToResultSet(

                        "select * from (select round(sum(gruppenWert)/(select sum(am) from(select sum(amount)as am,date_trunc('"
                                + granularity
                                + "',measure_time)as zeit from productiondata inner join controlpoints on productiondata.controlpoint_id=controlpoints.controlpoints_id "
                                + "where productiondata.measure_time >= '" + startTime
                                + "' AND productiondata.measure_time < '" + endTime
                                + "' AND reference_point='t' AND plant_id in(" + plants
                                + ") group by measure_time)as wat where zeit=gruppenZeit group by zeit order by zeit),4), gruppenZeit from("
                                + "select sum(wert) as gruppenWert,control_point_name, zeit1 as gruppenZeit from (select sum(value)as wert,control_point_name,date_trunc('"
                                + granularity
                                + "',measure_time)as zeit1 from measures inner join controlpoints on measures.controlpoint_id=controlpoints.controlpoints_id where measure_time >= '"
                                + startTime + "' AND measure_time < '" + endTime + "' AND controlpoints_id in("
                                + groups[i]
                                + ")group by measure_time,control_point_name)as data group by zeit1,control_point_name)as groupedByTime group by gruppenZeit)as result order by gruppenZeit"
                                + ";");

            }
        }
        if (rs != null) {
            try {
                while (rs.next()) {
                    switch (granularity) {

                    case "minute":
                        series.add(new Minute(Integer.parseInt(rs.getString(2).substring(14, 16)),
                                Integer.parseInt(rs.getString(2).substring(11, 13)),
                                Integer.parseInt(rs.getString(2).substring(8, 10)),
                                Integer.parseInt(rs.getString(2).substring(5, 7)),
                                Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1));
                        break;
                    case "day":
                        series.add(new Day(Integer.parseInt(rs.getString(2).substring(8, 10)),
                                Integer.parseInt(rs.getString(2).substring(5, 7)),
                                Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1));
                        break;

                    case "month":
                        series.add(new Month(Integer.parseInt(rs.getString(2).substring(5, 7)),
                                Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1));
                        break;

                    case "year":
                        series.add(new Year(Integer.parseInt(rs.getString(2).substring(0, 4))),
                                rs.getDouble(1));
                        break;

                    //default: day
                    default:
                        series.add(new Day(Integer.parseInt(rs.getString(2).substring(8, 10)),
                                Integer.parseInt(rs.getString(2).substring(5, 7)),
                                Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1));

                    }
                }
                rs.close();

            } catch (NumberFormatException e) {

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //Add the series to the collection
        collection.addSeries(series);
    }
    return collection;
}

From source file:LineChart.java

private static JFreeChart createDataset(JTable table) {
    TimeZone tz = TimeZone.getTimeZone("GMT");

    XYDataset ds = null;//from   www  .  ja  v a2s.c o  m

    if (table.getColumnCount() > 0) {
        Class klass = table.getColumnClass(0);

        if ((klass == Date.class) || (klass == Time.class) || (klass == c.Month.class)
                || (klass == c.Minute.class) || (klass == c.Second.class) || (klass == Timestamp.class)) {
            TimeSeriesCollection tsc = new TimeSeriesCollection();

            for (int col = 1; col < table.getColumnCount(); col++) {
                TimeSeries series = null;

                try {
                    if (klass == Date.class) {
                        series = new TimeSeries(table.getColumnName(col), Day.class);

                        for (int row = 0; row < table.getRowCount(); row++) {
                            Date date = (Date) table.getValueAt(row, 0);
                            Day day = new Day(date, tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof Number) {
                                ((TimeSeries) series).addOrUpdate(day, (Number) table.getValueAt(row, col));
                            }
                        }
                    } else if (klass == Time.class) {
                        series = new TimeSeries(table.getColumnName(col), Millisecond.class);

                        for (int row = 0; row < table.getRowCount(); row++) {
                            Time time = (Time) table.getValueAt(row, 0);
                            Millisecond ms = new Millisecond(time, tz);

                            //    Millisecond ms = new Millisecond(time);
                            Object o = table.getValueAt(row, col);
                            if (o instanceof Number) {
                                series.addOrUpdate(ms, (Number) table.getValueAt(row, col));
                            }
                        }
                    } else if (klass == Timestamp.class) {
                        series = new TimeSeries(table.getColumnName(col), Millisecond.class);

                        for (int row = 0; row < table.getRowCount(); row++) {
                            Timestamp time = (Timestamp) table.getValueAt(row, 0);
                            Millisecond ms = new Millisecond(time, tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof Number) {
                                series.addOrUpdate(ms, (Number) table.getValueAt(row, col));
                            }

                        }
                    } else if (klass == c.Month.class) {
                        series = new TimeSeries(table.getColumnName(col), Month.class);

                        for (int row = 0; row < table.getRowCount(); row++) {
                            c.Month time = (c.Month) table.getValueAt(row, 0);
                            int m = time.i + 24000;
                            int y = m / 12;
                            m = 1 + m % 12;

                            Month month = new Month(m, y);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof Number) {
                                series.addOrUpdate(month, (Number) table.getValueAt(row, col));
                            }

                        }
                    } else if (klass == c.Second.class) {
                        series = new TimeSeries(table.getColumnName(col), Second.class);

                        for (int row = 0; row < table.getRowCount(); row++) {
                            c.Second time = (c.Second) table.getValueAt(row, 0);

                            Second second = new Second(time.i % 60, time.i / 60, 0, 1, 1, 2001);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof Number) {
                                series.addOrUpdate(second, (Number) table.getValueAt(row, col));
                            }

                        }
                    } else if (klass == c.Minute.class) {
                        series = new TimeSeries(table.getColumnName(col), Minute.class);

                        for (int row = 0; row < table.getRowCount(); row++) {
                            c.Minute time = (c.Minute) table.getValueAt(row, 0);

                            Minute minute = new Minute(time.i % 60, time.i / 60, 1, 1, 2001);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof Number) {
                                series.addOrUpdate(minute, (Number) table.getValueAt(row, col));
                            }
                        }
                    }
                } catch (SeriesException e) {
                    System.err.println("Error adding to series");
                }

                if (series.getItemCount() > 0)
                    tsc.addSeries(series);
            }

            ds = tsc;
        } else if ((klass == double.class) || (klass == int.class) || (klass == short.class)
                || (klass == long.class) || (klass == Time.class)) {
            XYSeriesCollection xysc = new XYSeriesCollection();

            for (int col = 1; col < table.getColumnCount(); col++) {
                XYSeries series = null;

                try {
                    series = new XYSeries(table.getColumnName(col));

                    for (int row = 0; row < table.getRowCount(); row++) {
                        Number x = (Number) table.getValueAt(row, 0);

                        Object y = table.getValueAt(row, col);
                        if (y instanceof Number) {
                            series.add(x, (Number) y);
                        }
                    }
                } catch (SeriesException e) {
                    System.err.println("Error adding to series");
                }

                if (series.getItemCount() > 0)
                    xysc.addSeries(series);
            }

            ds = xysc;
        }
    }

    if (ds != null) {
        boolean legend = false;

        if (ds.getSeriesCount() > 1) {
            legend = true;
        }

        if (ds instanceof XYSeriesCollection) {
            return ChartFactory.createXYLineChart("", "", "", ds, PlotOrientation.VERTICAL, legend, true, true);
        } else if (ds instanceof TimeSeriesCollection)
            return ChartFactory.createTimeSeriesChart("", "", "", ds, legend, true, true);
    }

    return null;
}

From source file:interfaces.InterfazPrincipal.java

private void botonGenerarReporteClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGenerarReporteClienteActionPerformed
    // TODO add your handling code here:
    try {//from w ww .j a v  a 2  s  .  c om
        if (clienteReporteClienteFechaFinal.getSelectedDate().getTime()
                .compareTo(clienteReporteClienteFechaInicial.getSelectedDate().getTime()) < 0) {
            JOptionPane.showMessageDialog(this, "La fecha final debe ser posterior al dia de inicio");
        } else {
            final ArrayList<Integer> listaIDFlujos = new ArrayList<>();
            final JDialog dialogoEditar = new JDialog();
            dialogoEditar.setTitle("Reporte cliente");
            dialogoEditar.setSize(350, 610);
            dialogoEditar.setResizable(false);

            JPanel panelDialogo = new JPanel();
            panelDialogo.setLayout(new GridBagLayout());

            GridBagConstraints c = new GridBagConstraints();
            //c.fill = GridBagConstraints.HORIZONTAL;

            JLabel ediitarTextoPrincipalDialogo = new JLabel("Informe cliente");
            c.gridx = 0;
            c.gridy = 0;
            c.gridwidth = 1;
            c.insets = new Insets(10, 45, 10, 10);
            Font textoGrande = new Font("Arial", 1, 18);
            ediitarTextoPrincipalDialogo.setFont(textoGrande);
            panelDialogo.add(ediitarTextoPrincipalDialogo, c);

            final JTable tablaDialogo = new JTable();
            DefaultTableModel modeloTabla = new DefaultTableModel() {

                @Override
                public boolean isCellEditable(int row, int column) {
                    //all cells false
                    return false;
                }
            };
            ;

            modeloTabla.addColumn("Factura");
            modeloTabla.addColumn("Tipo Flujo");
            modeloTabla.addColumn("Fecha");
            modeloTabla.addColumn("Valor");

            //Llenar tabla
            ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
            ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                    " where factura_id in (select factura_id from Factura where cliente_id = "
                            + String.valueOf(jTextFieldIdentificacionClienteReporte.getText())
                            + ") order by factura_id");
            // {"flujo_id","factura_id","tipo_flujo","fecha","valor"};
            ArrayList<Calendar> fechasFlujos = new ArrayList<>();

            for (int i = 0; i < flujosCliente.size(); i++) {
                String fila[] = new String[4];
                String[] objeto = flujosCliente.get(i);
                fila[0] = objeto[1];
                fila[1] = objeto[2];
                fila[2] = objeto[3];
                fila[3] = objeto[4];

                //Filtrar, mirar las fechas
                String[] partirEspacios = objeto[3].split("\\s");
                //El primer string es la fecha sin hora
                //Ahora esparamos por -
                String[] tomarAgeMesDia = partirEspacios[0].split("-");

                //Realizar filtro
                int ageConsulta = Integer.parseInt(tomarAgeMesDia[0]);
                int mesConsulta = Integer.parseInt(tomarAgeMesDia[1]);
                int diaConsulta = Integer.parseInt(tomarAgeMesDia[2]);

                //Obtenemos dias, mes y ao de la consulta
                //Inicial
                int anioInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.YEAR);
                int mesInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.DAY_OF_MONTH);
                //Final
                int anioFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.YEAR);
                int mesFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.DAY_OF_MONTH);

                //Construir fechas
                Calendar fechaDeLaBD = new GregorianCalendar(ageConsulta, mesConsulta, diaConsulta);
                //Set year, month, day)

                Calendar fechaInicialRango = new GregorianCalendar(anioInicial, mesInicial, diaInicial);
                Calendar fechaFinalRango = new GregorianCalendar(anioFinal, mesFinal, diaFinal);

                if (fechaDeLaBD.compareTo(fechaInicialRango) <= 0
                        && fechaDeLaBD.compareTo(fechaFinalRango) >= 0) {
                    fechasFlujos.add(fechaDeLaBD);
                    modeloTabla.addRow(fila);
                }

            }

            if (modeloTabla.getRowCount() > 0) {
                tablaDialogo.setModel(modeloTabla);
                tablaDialogo.getColumn("Factura").setMinWidth(80);
                tablaDialogo.getColumn("Tipo Flujo").setMinWidth(80);
                tablaDialogo.getColumn("Fecha").setMinWidth(90);
                tablaDialogo.getColumn("Valor").setMinWidth(80);
                tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                JScrollPane scroll = new JScrollPane(tablaDialogo);
                scroll.setPreferredSize(new Dimension(330, 150));

                c.gridx = 0;
                c.gridy = 1;
                c.gridwidth = 1;
                c.insets = new Insets(0, 0, 0, 0);
                panelDialogo.add(scroll, c);

                TimeSeries localTimeSeries = new TimeSeries("Compras del cliente en el periodo");

                Map listaAbonos = new HashMap();

                for (int i = 0; i < modeloTabla.getRowCount(); i++) {
                    listaIDFlujos.add(Integer.parseInt(flujosCliente.get(i)[0]));

                    if (modeloTabla.getValueAt(i, 1).equals("abono")) {
                        Calendar fechaFlujo = fechasFlujos.get(i);
                        double valor = Double.parseDouble(String.valueOf(modeloTabla.getValueAt(i, 3)));

                        int anoDato = fechaFlujo.get(Calendar.YEAR);
                        int mesDato = fechaFlujo.get(Calendar.MONTH) + 1;
                        int diaDato = fechaFlujo.get(Calendar.DAY_OF_MONTH);
                        Day FechaDato = new Day(diaDato, mesDato, anoDato);

                        if (listaAbonos.get(FechaDato) != null) {
                            double valorAbono = (double) listaAbonos.get(FechaDato);
                            listaAbonos.remove(FechaDato);
                            listaAbonos.put(FechaDato, valorAbono + valor);
                        } else {
                            listaAbonos.put(FechaDato, valor);

                        }

                    }

                }
                Double maximo = 0.0;
                Iterator iterator = listaAbonos.keySet().iterator();
                while (iterator.hasNext()) {
                    Day key = (Day) iterator.next();
                    Double value = (double) listaAbonos.get(key);
                    maximo = Math.max(maximo, value);
                    localTimeSeries.add(key, value);
                }

                //localTimeSeries.add();
                TimeSeriesCollection datos = new TimeSeriesCollection(localTimeSeries);

                JFreeChart chart = ChartFactory.createTimeSeriesChart("Compras del cliente en el periodo", // Title
                        "Tiempo", // x-axis Label
                        "Total ($)", // y-axis Label
                        datos, // Dataset
                        true, // Show Legend
                        true, // Use tooltips
                        false // Configure chart to generate URLs?
                );
                /*Altering the graph */
                XYPlot plot = (XYPlot) chart.getPlot();
                plot.setAxisOffset(new RectangleInsets(5.0, 10.0, 10.0, 5.0));
                plot.setDomainCrosshairVisible(true);
                plot.setRangeCrosshairVisible(true);

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
                renderer.setBaseShapesVisible(true);
                renderer.setBaseShapesFilled(true);

                NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
                numberAxis.setRange(new Range(0, maximo * 1.2));
                Font font = new Font("Dialog", Font.PLAIN, 9);
                numberAxis.setTickLabelFont(font);
                numberAxis.setLabelFont(font);

                DateAxis axis = (DateAxis) plot.getDomainAxis();
                axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
                axis.setAutoTickUnitSelection(false);
                axis.setVerticalTickLabels(true);

                axis.setTickLabelFont(font);
                axis.setLabelFont(font);

                LegendTitle leyendaChart = chart.getLegend();
                leyendaChart.setItemFont(font);

                Font fontTitulo = new Font("Dialog", Font.BOLD, 12);
                TextTitle tituloChart = chart.getTitle();
                tituloChart.setFont(fontTitulo);

                ChartPanel CP = new ChartPanel(chart);
                Dimension D = new Dimension(330, 300);
                CP.setPreferredSize(D);
                CP.setVisible(true);
                c.gridx = 0;
                c.gridy = 2;
                c.gridwidth = 1;
                c.insets = new Insets(10, 0, 0, 0);
                panelDialogo.add(CP, c);

                c.gridx = 0;
                c.gridy = 3;
                c.gridwidth = 1;
                c.anchor = GridBagConstraints.WEST;
                c.insets = new Insets(10, 30, 0, 0);

                JButton botonCerrar = new JButton("Cerrar");
                botonCerrar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialogoEditar.dispose();
                    }
                });
                panelDialogo.add(botonCerrar, c);

                JButton botonGenerarPDF = new JButton("Guardar archivo");
                botonGenerarPDF.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.guardarDocumentoDialogo(dialogoEditar, listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 100, 0, 0);

                panelDialogo.add(botonGenerarPDF, c);

                JButton botonImprimir = new JButton("Imprimir");
                botonImprimir.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.imprimirFlujo(listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 230, 0, 0);

                panelDialogo.add(botonImprimir, c);
                dialogoEditar.add(panelDialogo);

                dialogoEditar.setVisible(true);

            } else {
                JOptionPane.showMessageDialog(this,
                        "El cliente no registra movimientos en el rango de fechas seleccionado");
            }

        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe seleccionar un da inicial y final de fechas");
    }

}

From source file:studio.ui.LineChart.java

public static JFreeChart createDataset(KTableModel table) {
    TimeZone tz = TimeZone.getTimeZone("GMT");

    XYDataset ds = null;//from w  ww  . j a v  a2 s . c o m

    if (table.getColumnCount() > 0) {
        Class klass = table.getColumnClass(0);

        if ((klass == K.KTimestampVector.class) || (klass == K.KTimespanVector.class)
                || (klass == K.KDateVector.class) || (klass == K.KTimeVector.class)
                || (klass == K.KMonthVector.class) || (klass == K.KMinuteVector.class)
                || (klass == K.KSecondVector.class) || (klass == K.KDatetimeVector.class)) {
            TimeSeriesCollection tsc = new TimeSeriesCollection(tz);

            for (int col = 1; col < table.getColumnCount(); col++) {
                TimeSeries series = null;

                try {
                    if (klass == K.KDateVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Day.class);
                        K.KDateVector dates = (K.KDateVector) table.getColumn(0);

                        for (int row = 0; row < dates.getLength(); row++) {
                            K.KDate date = (K.KDate) dates.at(row);
                            Day day = new Day(date.toDate(), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(day, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KTimeVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Millisecond.class);

                        K.KTimeVector times = (K.KTimeVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.KTime time = (K.KTime) times.at(row);
                            Millisecond ms = new Millisecond(time.toTime(), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(ms, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KTimestampVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Day.class);
                        K.KTimestampVector dates = (K.KTimestampVector) table.getColumn(0);

                        for (int row = 0; row < dates.getLength(); row++) {
                            K.KTimestamp date = (K.KTimestamp) dates.at(row);
                            Day day = new Day(new java.util.Date(date.toTimestamp().getTime()), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(day, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KTimespanVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Millisecond.class);

                        K.KTimespanVector times = (K.KTimespanVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.KTimespan time = (K.KTimespan) times.at(row);
                            Millisecond ms = new Millisecond(time.toTime(), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(ms, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KDatetimeVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Millisecond.class);
                        K.KDatetimeVector times = (K.KDatetimeVector) table.getColumn(0);

                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.KDatetime time = (K.KDatetime) times.at(row);
                            Millisecond ms = new Millisecond(time.toTimestamp(), tz);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(ms, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KMonthVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Month.class);
                        K.KMonthVector times = (K.KMonthVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.Month time = (K.Month) times.at(row);
                            int m = time.i + 24000;
                            int y = m / 12;
                            m = 1 + m % 12;

                            Month month = new Month(m, y);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(month, ((ToDouble) o).toDouble());
                        }
                    } else if (klass == K.KSecondVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Second.class);
                        K.KSecondVector times = (K.KSecondVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.Second time = (K.Second) times.at(row);
                            Second second = new Second(time.i % 60, time.i / 60, 0, 1, 1, 2001);

                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(second, ((ToDouble) o).toDouble());

                        }
                    } else if (klass == K.KMinuteVector.class) {
                        series = new TimeSeries(table.getColumnName(col), Minute.class);
                        K.KMinuteVector times = (K.KMinuteVector) table.getColumn(0);
                        for (int row = 0; row < table.getRowCount(); row++) {
                            K.Minute time = (K.Minute) times.at(row);
                            Minute minute = new Minute(time.i % 60, time.i / 60, 1, 1, 2001);
                            Object o = table.getValueAt(row, col);
                            if (o instanceof K.KBase)
                                if (!((K.KBase) o).isNull())
                                    if (o instanceof ToDouble)
                                        series.addOrUpdate(minute, ((ToDouble) o).toDouble());
                        }
                    }
                } catch (SeriesException e) {
                    System.err.println("Error adding to series");
                }

                if (series.getItemCount() > 0)
                    tsc.addSeries(series);
            }

            ds = tsc;
        } else if ((klass == K.KDoubleVector.class) || (klass == K.KFloatVector.class)
                || (klass == K.KShortVector.class) || (klass == K.KIntVector.class)
                || (klass == K.KLongVector.class)) {
            XYSeriesCollection xysc = new XYSeriesCollection();

            for (int col = 1; col < table.getColumnCount(); col++) {
                XYSeries series = null;

                try {
                    series = new XYSeries(table.getColumnName(col));

                    for (int row = 0; row < table.getRowCount(); row++) {
                        double x = ((ToDouble) table.getValueAt(row, 0)).toDouble();
                        double y = ((ToDouble) table.getValueAt(row, col)).toDouble();
                        series.add(x, y);
                    }
                } catch (SeriesException e) {
                    System.err.println("Error adding to series");
                }

                if (series.getItemCount() > 0)
                    xysc.addSeries(series);
            }

            ds = xysc;
        }
    }

    if (ds != null) {
        boolean legend = false;

        if (ds.getSeriesCount() > 1)
            legend = true;

        if (ds instanceof XYSeriesCollection)
            return ChartFactory.createXYLineChart("", "", "", ds, PlotOrientation.VERTICAL, legend, true, true);
        else if (ds instanceof TimeSeriesCollection)
            return ChartFactory.createTimeSeriesChart("", "", "", ds, legend, true, true);
    }

    return null;
}

From source file:org.atomserver.testutils.plot.PerfDataSet.java

public XYDataset getXYDataSet(boolean normalizeTimes, List methodNamesToPlot, String methodNameSuffix,
        boolean computeMovingAverage, int numPointsInAvg, boolean plotTPM) {
    long lMinDate = 0L;
    if (normalizeTimes) {
        lMinDate = minDate.getTime();/*from   w  w  w.  j  av  a2s.  co  m*/
    }
    TimeSeriesCollection tsc = new TimeSeriesCollection();

    for (Map.Entry<String, List<PerfData>> entry : dataSet.entrySet()) {
        String methodName = entry.getKey();

        if (methodNamesToPlot != null) {
            if (!methodNamesToPlot.contains(methodName))
                continue;
        }

        if (methodNameSuffix != null) {
            methodName += " " + methodNameSuffix;
        }

        TimeSeries series = new TimeSeries(methodName, Second.class);

        List<PerfData> perfDataList = entry.getValue();
        for (PerfData perfData : perfDataList) {
            Date datetime = perfData.getDateTime();
            Double value = 0.0;
            if (plotTPM)
                value = perfData.getTPM();
            else
                value = perfData.getAvgResp();

            if (normalizeTimes) {
                long lDatetime = datetime.getTime();
                long lNormalizedTime = lDatetime - lMinDate;
                datetime = new Date(lNormalizedTime);
                if (log.isTraceEnabled())
                    log.trace("[ " + lDatetime + ", " + lMinDate + ", " + lNormalizedTime
                            + "] normalized time = " + datetime);
            }

            series.add(new Second(datetime), value);
        }

        if (computeMovingAverage) {
            TimeSeries movingAvg = MovingAverage.createPointMovingAverage(series,
                    methodName + " moving average", numPointsInAvg);
            tsc.addSeries(movingAvg);
        } else {
            tsc.addSeries(series);
        }

    }
    return tsc;
}

From source file:org.yccheok.jstock.charting.TechnicalAnalysis.java

/**
 * Returns SMA time series for charting purpose.
 *
 * @param chartDatas list of chart data/*from  w ww  .ja v  a 2 s.c  o  m*/
 * @param name name for the time series
 * @param period the duration period
 * @return SMA time series for charting purpose
 */
public static TimeSeries createSMA(List<ChartData> chartDatas, String name, int period) {
    if (period <= 0) {
        throw new java.lang.IllegalArgumentException("period must be greater than 0");
    }

    final TimeSeries series = new TimeSeries(name);
    final int num = chartDatas.size();

    final Core core = new Core();
    final int allocationSize = num - core.smaLookback(period);
    if (allocationSize <= 0) {
        return series;
    }
    final double[] last = new double[num];
    // Fill up last array.
    for (int i = 0; i < num; i++) {
        last[i] = chartDatas.get(i).lastPrice;
    }

    final double[] output = new double[allocationSize];
    final MInteger outBegIdx = new MInteger();
    final MInteger outNbElement = new MInteger();

    core.sma(0, last.length - 1, last, period, outBegIdx, outNbElement, output);

    for (int i = 0; i < outNbElement.value; i++) {
        series.add(new Day(new Date(chartDatas.get(i + outBegIdx.value).timestamp)), output[i]);
    }

    return series;
}

From source file:org.yccheok.jstock.charting.TechnicalAnalysis.java

public static MACD.ChartResult createMACD(List<ChartData> chartDatas, String name, MACD.Period period) {
    final int num = chartDatas.size();
    final Core core = new Core();
    final int allocationSize = num - core.macdLookback(period.fastPeriod, period.slowPeriod, period.period);
    if (allocationSize <= 0) {
        return null;
    }// www  . ja  v a 2s  .  com

    final double[] last = new double[num];
    // Fill up last array.
    for (int i = 0; i < num; i++) {
        last[i] = chartDatas.get(i).lastPrice;
    }

    final double[] outMACD = new double[allocationSize];
    final double[] outMACDSignal = new double[allocationSize];
    final double[] outMACDHist = new double[allocationSize];
    final MInteger outBegIdx = new MInteger();
    final MInteger outNbElement = new MInteger();

    core.macd(0, last.length - 1, last, period.fastPeriod, period.slowPeriod, period.period, outBegIdx,
            outNbElement, outMACD, outMACDSignal, outMACDHist);

    final TimeSeries macdTimeSeries = new TimeSeries(name);
    final TimeSeries macdSignalTimeSeries = new TimeSeries(name);
    final TimeSeries macdHistTimeSeries = new TimeSeries(name);

    for (int i = 0; i < outNbElement.value; i++) {
        Day day = new Day(new Date(chartDatas.get(i + outBegIdx.value).timestamp));
        macdTimeSeries.add(day, outMACD[i]);
        macdSignalTimeSeries.add(day, outMACDSignal[i]);
        macdHistTimeSeries.add(day, outMACDHist[i]);
    }

    return MACD.ChartResult.newInstance(new TimeSeriesCollection(macdTimeSeries),
            new TimeSeriesCollection(macdSignalTimeSeries), new TimeSeriesCollection(macdHistTimeSeries));
}

From source file:org.yccheok.jstock.charting.TechnicalAnalysis.java

/**
 * Returns EMA time series for charting purpose.
 *
 * @param chartDatas list of chart data/*w  w  w .  ja  va 2 s .co m*/
 * @param name name for the time series
 * @param period the duration period
 * @return EMA time series for charting purpose
 */
public static TimeSeries createEMA(List<ChartData> chartDatas, String name, int period) {
    if (period <= 0) {
        throw new java.lang.IllegalArgumentException("period must be greater than 0");
    }

    final TimeSeries series = new TimeSeries(name);
    final int num = chartDatas.size();

    final Core core = new Core();
    final int allocationSize = num - core.emaLookback(period);
    if (allocationSize <= 0) {
        return series;
    }
    final double[] last = new double[num];
    // Fill up last array.
    for (int i = 0; i < num; i++) {
        last[i] = chartDatas.get(i).lastPrice;
    }

    final double[] output = new double[allocationSize];
    final MInteger outBegIdx = new MInteger();
    final MInteger outNbElement = new MInteger();

    core.ema(0, last.length - 1, last, period, outBegIdx, outNbElement, output);

    for (int i = 0; i < outNbElement.value; i++) {
        series.add(new Day(new Date(chartDatas.get(i + outBegIdx.value).timestamp)), output[i]);
    }

    return series;
}

From source file:org.yccheok.jstock.charting.TechnicalAnalysis.java

/**
 * Returns CCI XYDataset for charting purpose.
 *
 * @param chartDatas list of chart data//from w ww.  j a v  a2s.c  om
 * @param name name for the XYDataset
 * @param period the duration period
 * @return CCI XYDataset for charting purpose
 */
public static XYDataset createCCI(List<ChartData> chartDatas, String name, int period) {
    if (period <= 0) {
        throw new java.lang.IllegalArgumentException("period must be greater than 0");
    }

    final TimeSeries series = new TimeSeries(name);
    final int num = chartDatas.size();

    final Core core = new Core();
    final int allocationSize = num - core.cciLookback(period);
    if (allocationSize <= 0) {
        return new TimeSeriesCollection(series);
    }

    final double[] high = new double[num];
    final double[] low = new double[num];
    final double[] close = new double[num];
    // Fill up last array.
    for (int i = 0; i < num; i++) {
        high[i] = chartDatas.get(i).highPrice;
        low[i] = chartDatas.get(i).lowPrice;
        close[i] = chartDatas.get(i).lastPrice;
    }

    final double[] output = new double[allocationSize];
    final MInteger outBegIdx = new MInteger();
    final MInteger outNbElement = new MInteger();

    core.cci(0, num - 1, high, low, close, period, outBegIdx, outNbElement, output);

    for (int i = 0; i < outNbElement.value; i++) {
        series.add(new Day(new Date(chartDatas.get(i + outBegIdx.value).timestamp)), output[i]);
    }

    return new TimeSeriesCollection(series);
}

From source file:org.yccheok.jstock.charting.TechnicalAnalysis.java

/**
 * Returns RSI XYDataset for charting purpose.
 *
 * @param chartDatas list of chart data//from  www.  jav a  2  s .c  o m
 * @param name name for the XYDataset
 * @param period the duration period
 * @return RSI XYDataset for charting purpose
 */
public static XYDataset createRSI(List<ChartData> chartDatas, String name, int period) {
    if (period <= 0) {
        throw new java.lang.IllegalArgumentException("period must be greater than 0");
    }

    final TimeSeries series = new TimeSeries(name);
    final int num = chartDatas.size();

    final Core core = new Core();
    final int allocationSize = num - core.rsiLookback(period);
    if (allocationSize <= 0) {
        return new TimeSeriesCollection(series);
    }

    final double[] last = new double[num];
    // Fill up last array.
    for (int i = 0; i < num; i++) {
        last[i] = chartDatas.get(i).lastPrice;
    }

    final double[] output = new double[allocationSize];
    final MInteger outBegIdx = new MInteger();
    final MInteger outNbElement = new MInteger();

    core.rsi(0, last.length - 1, last, period, outBegIdx, outNbElement, output);

    for (int i = 0; i < outNbElement.value; i++) {
        series.add(new Day(new Date(chartDatas.get(i + outBegIdx.value).timestamp)), output[i]);
    }

    return new TimeSeriesCollection(series);
}