import numpy as np
import pandas as pd
import pandas.io.data as web
import matplotlib.pyplot as plt
from pandas.io.pytables import HDFStore
from datetime import datetime


class Data:
  dataFileName = "data.h5"
  assetsFileName = 'constituents.csv'
  start = datetime(2005,1,1)
  end = datetime(2015,1,1)
  maxAssets = 500
  # assets 
  # assetList = assetList - market + ^VIX
  # market = S&P 500
   

  def __init__(self):
    self.getAssets()

  def getAssets(self):
    self.assets = pd.HDFStore(self.dataFileName)    
    constituents = pd.read_csv('constituents.csv').sort(columns="Symbol")    

    # add vix as hedging asset    
    self.assetList = pd.DataFrame([
        {'Symbol': '^VIX', 'Name': 'VOLATILITY S&P 500', 'Sector':'ETF Index'},
        # {'Symbol': '^GSPC', 'Name': 'S&P 500', 'Sector':'ETF Market Index'},
        # {'Symbol': '^TYX', 'Name': 'Treasury Yield 30 Years', 'Sector':'Bonds'},
        ]).append(constituents)
    self.assetList = self.assetList['Symbol'][:self.maxAssets]    

    keys = self.assets.keys()
    for symbol in self.assetList:    
      if ("".join(["/", symbol]) not in keys):
        print "Downloading", symbol
        s = web.DataReader(symbol,  "yahoo", self.start, self.end)                
        s["pct_daily_ret"] = s["Adj Close"].pct_change()    
        s["excess_daily_ret"] = s["pct_daily_ret"] - 0.03/252
        self.assets.put(symbol, s)        
      # else:
      #   print "Loading", symbol #, "sharpe ratio", annualised_sharpe (data[symbol]['excess_daily_ret'])
   
    print "Loaded", self.assetList.count(), "assets"

    # remove market from assets
    # self.assetList = self.assetList.drop(self.assetList.index[[1]])



  def close( self ):
    self.assets.close()