/*
 * StockEvaluator.java
 *
 * Created on October 31, 2007, 12:54 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package uc2;

import java.util.*;
import java.math.*;
import java.sql.*;

import uc2.BaseStats.*;
import uc2.SingleIndexModel.*;

public class StockEvaluator {

	/** Creates a new instance of StockEvaluator */
	public StockEvaluator() {
	}

	double alpha = 0.0;
	double beta = 0.0;
	double residue = 0.0;
        double exp_return = 0.0;
        double variance = 0.0;
        double sharpe_ratio = 0.0;

        ArrayList<String> allStockList = new ArrayList<String>();
        
	void getStockHistory(String symbol) {
		ResultSet rs = null;
		int recCount = 0;
                double basePrice = 0;
                StockReturn stockRet;
		DatabaseCommunicator.connect();
		try {
			String query = "SELECT price FROM stock_history where symbol = '" + symbol + "';";
			rs = DatabaseCommunicator.query(query);
			while(rs.next()) {
                                stockRet = (StockReturn) MarketEvaluator.marketHistory.get(recCount);
                                if(recCount == 0)
                                    basePrice = rs.getDouble("price");
                                stockRet.roi = rs.getDouble("price")/basePrice - 1.0;
				recCount++;
			} 
			DatabaseCommunicator.close();
		}
		catch (Exception e) {
			System.err.println("Exception: " + e.toString());
		}
	}

	/* void getMarketHistory() {
		ResultSet rs = null;
		DatabaseCommunicator.connect();
		try {
			String query = "SELECT price FROM stock_history where symbol = 'DJI';";  // Dow Jones Industrial Average
			rs = DatabaseCommunicator.query(query);
			while(rs.next()) {
                                StockReturn stockRet = new StockReturn();
                                stockRet.roi = 0;
                                stockRet.tick = rs.getDouble("price");
                                allHistory.add(stockRet);
			} 
			DatabaseCommunicator.close();
		}
		catch (Exception e) {
			System.err.println("Exception: " + e.toString());
		}
	} X data */
        
	public void computeStockParameters(String symbol){
            //getMarketHistory();
            getStockHistory(symbol);
            double coef[] = SingleIndexModel.SIM(SingleIndexModel.marketMatrix(MarketEvaluator.marketHistory), symbol);
            alpha = coef[0];
            beta = coef[1];
            residue = SingleIndexModel.residue;
            exp_return = BaseStats.computeExpectedReturn(MarketEvaluator.marketHistory);
            variance = BaseStats.computeVariance(MarketEvaluator.marketHistory);
            sharpe_ratio = (exp_return - MarketEvaluator.risk_free_rate)/Math.pow(variance, 0.5);
	}

	public void updateStockParameters(String symbol) {
            // Connect to DatabaseCommunicator and use symbol as a key
            // to find the stock and update its risk parameters
            DatabaseCommunicator.connect();
            try {
                // Update stock parameters in table stock.
                String query1 = "UPDATE stock SET alpha = " + alpha + " WHERE symbol = '" + symbol + "';";
                DatabaseCommunicator.query(query1);
                String query2 = "UPDATE stock SET beta = " + beta + " WHERE symbol = '" + symbol + "';";
                DatabaseCommunicator.query(query2);
                String query3 = "UPDATE stock SET residue = " + residue + " where symbol = '" + symbol + "';";
                DatabaseCommunicator.query(query3);
                String query4 = "UPDATE stock SET exp_return = " + exp_return + " where symbol = '" + symbol + "';";
                DatabaseCommunicator.query(query4);
                String query5 = "UPDATE stock SET variance = " + variance + " where symbol = '" + symbol + "';";
                DatabaseCommunicator.query(query5);
                String query6 = "UPDATE stock SET sharpe_ratio = " + sharpe_ratio + " where symbol = '" + symbol + "';";
                DatabaseCommunicator.query(query6);
                DatabaseCommunicator.close();
            }
            catch (Exception e) {
                System.err.println("Exception: " + e.toString());
            }
	}        

    void getAllStocks() {
        // Connect to DatabaseCommunicator
        ResultSet rs = null;
        DatabaseCommunicator.connect();
        try {
            String query = "SELECT symbol FROM stock;";
            rs = DatabaseCommunicator.query(query);
            // System.out.println(rs.getFetchSize());
            while(rs.next())
                allStockList.add(rs.getString("symbol"));
            DatabaseCommunicator.close();
        }
        catch (Exception e) {
            System.err.println("Exception: " + e.toString());
        }
    }
    
    public void updateAllAvailableStocks() {
        getAllStocks();
        for(int i=0; i < allStockList.size(); i++) {
            if(EvaluatedStockSet.notInStockComputedSet(allStockList.get(i))) {
                if(allStockList.get(i).equals("DJI") == false) {
                    computeStockParameters(allStockList.get(i));
                    updateStockParameters(allStockList.get(i));
                }
            }
        }
    }
}