Search code examples
javayahoo-apiyahoo-finance

java.io.FileNotFoundException when using Yahoo API


I was trying to get a list of historical stock data of APPL but was unable to do so.

My function is as below:

public void StockDownloader(String symbol, GregorianCalendar start, GregorianCalendar end  ){

        dates = new ArrayList<GregorianCalendar>();
        opens = new ArrayList<Double>();
        highs = new ArrayList<Double>();
        lows = new ArrayList<Double>();
        closes = new ArrayList<Double>();
        volume = new ArrayList<Integer>();
        adjcloses = new ArrayList<Double>();

        String url = "http://real-chart.finance.yahoo.com/table.csv?s="+symbol+
                "&a="+start.get(Calendar.MONTH) + 
                "&b="+start.get(Calendar.DAY_OF_MONTH) + 
                "&c="+start.get(Calendar.YEAR) + 
                "&d="+end.get(Calendar.MONTH) + 
                "&e="+end.get(Calendar.DAY_OF_MONTH) + 
                "&f="+end.get(Calendar.YEAR) + 
                "&g=d&ignore=.csv";

        try{
            URL yahoofinance = new URL(url);
            URLConnection data = yahoofinance.openConnection();
            Scanner input = new Scanner(data.getInputStream());
            if(input.hasNext()){
                input.nextLine();
            }
            while(input.hasNextLine()){
                String line = input.nextLine();
                System.out.println(line);
            }
        }catch(Exception e){
            System.err.println(e);

        }

And this is how I call the function:

GregorianCalendar start = new GregorianCalendar(2000, 12, 12);
        GregorianCalendar end = new GregorianCalendar(2013, 12, 2);
        StockDownloader("APPL",start,end);

The error I got was :

java.io.FileNotFoundException: http://real-chart.finance.yahoo.com/table.csv?s=APPL&a=0&b=12&c=2001&d=0&e=2&f=2014&g=d&ignore=.csv

Do notice that the error in the URL is different from my parameters. I have requested data from the year 2000 but in the return URL it says 2001.

What's wrong with my code and how should I fix this ? Thanks in advance.


Solution

  • Everything is fine...except the month that starts with 0, So to start from december use 11 not 12.

    GregorianCalendar start = new GregorianCalendar(2000, 11, 12);
    GregorianCalendar end = new GregorianCalendar(2013, 11, 2);