/*
 * MarketEvaluator.java
 *
 * Created on October 31, 2007, 3:51 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.SingleIndexModel.*;
import uc2.BaseStats.*;

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

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

    static ArrayList<StockReturn> marketHistory = new ArrayList<StockReturn>();
    static void getMarketHistory(String symbol) 
    {
        int recCount = 0;
        ResultSet rs = null;
        double basePrice = 0;
        DatabaseCommunicator.connect();
        try 
        {
            String query1 = "SELECT price FROM stock_history where symbol = '" + symbol + "';";
            rs = DatabaseCommunicator.query(query1);
            marketHistory.clear();
            while(rs.next()) 
            {
                SingleIndexModel.StockReturn stockReturn = new StockReturn();
                if(recCount == 0)
                    basePrice = rs.getDouble("price");
                stockReturn.roi = rs.getDouble("price")/basePrice - 1.0;
                stockReturn.tick = (double) recCount;
                marketHistory.add(stockReturn);
                recCount++;
            }
            rs.close();
            
            String query2 = "SELECT risk_free_rate FROM market_info WHERE index_symbol = '" + symbol + "';";
            rs = DatabaseCommunicator.query(query2);
            rs.next();
            risk_free_rate = (double) rs.getDouble("risk_free_rate");
            rs.close();
            DatabaseCommunicator.close();
        }
        catch (Exception e) 
        {
            System.err.println("Exception: " + e.toString());
        }
    }

    public static void computeMarketParameters(String symbol) 
    {
        double coef[] = SingleIndexModel.SIM(SingleIndexModel.marketMatrix(marketHistory), symbol);
        alpha = coef[0];
        beta = coef[1];
        residue = (double) SingleIndexModel.residue;
    }

    public static void updateMarketParameters(String symbol) 
    {
        // Need to update Market's alpha, beta and risk
        DatabaseCommunicator.connect();
        try 
        {
            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);
            DatabaseCommunicator.close();
        }
        catch (Exception e) 
        {
            System.err.println("Exception: " + e.toString());
        }
    }

    public static void updateMarketSharpeRatio(String symbol) 
    {
        // Need to update Market's Sharpe_Ratio
        DatabaseCommunicator.connect();
        try 
        {
            String query1 = "UPDATE stock SET sharpe_ratio = " + sharpe_ratio + " WHERE symbol = '" + symbol + "';";
            DatabaseCommunicator.query(query1);
            DatabaseCommunicator.close();
        }
        catch (Exception e)
        {
            System.err.println("Exception: " + e.toString());
        }
    }
    
    static void moveMarketHistoryData() 
    {
        StockReturn stockRet;
        for(int recCount = 0; recCount < marketHistory.size(); recCount++) 
        {
            stockRet = (StockReturn) MarketEvaluator.marketHistory.get(recCount);
            stockRet.tick = stockRet.roi;
            stockRet.roi = 0;
        }
    }

    public static void updateMarketDispersion(String symbol) 
    {
        // Need to update the portfolio alpha, beta and risk in investor's profile
        DatabaseCommunicator.connect();
        try 
        {
            String query1 = "UPDATE market_info SET exp_return = " + exp_return + " WHERE index_symbol = '" + symbol + "';";
            DatabaseCommunicator.query(query1);
            String query2 = "UPDATE market_info SET variance = " + variance + " WHERE index_symbol = '" + symbol + "';";
            DatabaseCommunicator.query(query2);
            String query3 = "UPDATE stock SET exp_return = " + exp_return + " WHERE symbol = '" + symbol + "';";
            DatabaseCommunicator.query(query3);
            String query4 = "UPDATE stock SET variance = " + variance + " WHERE symbol = '" + symbol + "';";
            DatabaseCommunicator.query(query4);
            DatabaseCommunicator.close();
        }
        catch (Exception e) 
        {
            System.err.println("Exception: " + e.toString());
        }
    }
    
    public static void refreshMarketParameters(String symbol) 
    {
        getMarketHistory(symbol);
        computeMarketParameters(symbol);
        updateMarketParameters(symbol);
        exp_return = BaseStats.computeExpectedReturn(MarketEvaluator.marketHistory);
        variance = BaseStats.computeVariance(MarketEvaluator.marketHistory);
        sharpe_ratio = (exp_return-risk_free_rate)/Math.pow(variance, 0.5);
        updateMarketDispersion(symbol);
        moveMarketHistoryData();
    }
}