package eecs1022; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; import javax.swing.JOptionPane; public class StockAnalyzer { public static void main(String[] args) { try { // get the stock symbol from the user String symbol = JOptionPane.showInputDialog("Enter stock symbol"); // get today's date Date today = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("MMM+d+yyyy"); String todayString = formatter.format(today); // set up to read from the website String name = "http://www.google.com/finance/historical?q=" + symbol + "&histperiod=daily&startdate=Jan+1+1970&enddate=" + todayString + "&output=csv"; URL url = new URL(name); InputStream stream = url.openStream(); Scanner input = new Scanner(stream); // skip the first line input.nextLine(); // initialize double maxHigh = 0.0; Date maxDate = null; double minLow = Double.MAX_VALUE; Date minDate = null; formatter = new SimpleDateFormat("d-MMM-yy"); while (input.hasNextLine()) { String line = input.nextLine(); String[] part = line.split(","); String dateString = part[0]; Date date = formatter.parse(dateString); String highString = part[2]; double high = Double.parseDouble(highString); String lowString = part[3]; double low = Double.parseDouble(lowString); if (high > maxHigh) { maxHigh = high; maxDate = date; } if (low < minLow) { minLow = low; minDate = date; } } input.close(); formatter = new SimpleDateFormat("d/MM/yy"); String maxString = formatter.format(maxDate); String minString = formatter.format(minDate); if (maxDate.before(minDate)) { // loss double percentage = (maxHigh - minLow) / maxHigh * 100; System.out.printf("If I had bought gts shares on %s\n", maxString); System.out.printf("and sold them on %s\n", minString); System.out.printf("I would have made a %.2f%% loss", percentage); } else { // gain double percentage = (maxHigh - minLow) / minLow * 100; System.out.printf("If I had bought gts shares on %s\n", minString); System.out.printf("and sold them on %s\n", maxString); System.out.printf("I would have made a %.2f%% gain", percentage); } } catch (MalformedURLException e) { System.out.println("Google Finance changed their URLs."); e.printStackTrace(); } catch (IOException e) { System.out.println("Google Finance is currently unavailable"); } catch (ParseException e) { System.out.println("Google Finance changed their date pattern."); e.printStackTrace(); } } }