Wednesday, March 28, 2012

Lab 20: Stock Plot

In Java, like in most programming languages, reading data from a URL is nearly identical to reading from a file, or reading from the keyboard. Java uses the URL class for reading data from a URL, as shown in this example.

Google provides us with historical price information for all the stocks. Specifically, if you go to the url http://www.google.com/finance/historical?q=AAPL&output=csv you will get a text file, in CSV format, for the prices of AAPL (Apple Computer) stock for the last year. To get a different stock simply replace AAPL in that url with the sticker symbol for your desired stock (try GOOG, GE, INTC).

For this lab you will start with the code below:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class PlotStock extends JPanel {

  /**
   * Initial Screen size.
   */
  public static final int WIDTH = 640;
  public static final int HEIGHT = 400;


  /**
   * Fetches stock data from google and prints it out to the
   * console.
   */
  private void getData(){
    try {
      //Get data on AAPL (Apple Computer) stock.
      //To get data on other sticker symbols simply replace AAPL with your
      // desired symbol, like GOOG.
      URL data = new URL("http://www.google.com/finance/historical?q=AAPL&output=csv");
      BufferedReader in = new BufferedReader(
        new InputStreamReader(data.openStream()));
      String inputLine;
      //TODO: rather than printing them out, we need to pick out the
      //  closing prices and save them for later plotting.
      while ((inputLine = in.readLine()) != null){
        System.out.println(inputLine);
      }
    }
    catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("Uh Oh, I cannot reach the Internet.");
    }
   }

  /**
   * This method gets called when the class first gets create and also whenever the
   * window needs to be redraw, like when the user changes its size, de-iconifies it,
   * moves it, etc.
   */
  public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.black);
    getData();
    //Draw a line from 10,10 to the bottom right of the window.
    //TODO: draw the line graph of the closing prices instead.
    g2.drawLine(10,10, getWidth(), getHeight());
    //Notice that getWidth() and getHeight() can be used to give us
    // the width and height of the current window (which might be 
    // different from the original because the user changed it).
  }

  public static void main(String[] args) {
    String symbol = JOptionPane.showInputDialog("Enter Ticker Symbol:");
    if (symbol == null) System.exit(0); //quit if user hit Cancel
    JFrame frame = new JFrame("Window"); //frame is the window
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    PlotStock panel = new PlotStock(); //panel is the graphics area where we can draw
    frame.add(panel); //put the panel inside the window
    frame.setSize(WIDTH,HEIGHT); //set the window size to 640x400 pixels
    frame.setVisible(true); 
  }
}


When you run it you will notice that it first opens up a window asking you for a ticker symbol (try AAPL) and then prints out the prices for that stock on the console and pops up a graphic window with just a line.

For this lab you will change this program so that instead of printing out to the console it will draw a line chart of the closing prices of the given stock. Notice that the closing price is one of the columns on the give CSV file. You can ignore all the other columns. Your final plot should look something like the figure shown.

TIP: String.split(",",0) is very useful for parsing the CSV file.

Once you get it working, try re-sizing the window with your mouse: drag a corner to make the window bigger. Did your plot grow with the window? If not, that is OK, it is good enough for this lab.

However, if you want a fun little challenge (definitely doable within the lab time), try to make it so your plot stretches to fit the window. Note that you can get the current size of the window using getWidth() and getHeight(), as shown in the code. The rest is just a little bit of programming. You will need to find the max and min closing prices, and number of days of data, then scale these to fit the current window.

As always, turn it in at the dropbox.cse.sc.edu.



No comments: