#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Portfolio optimization using metaheuristics
# p.optimize('pso', opts={"pop": 20, 'c1':1.4, 'c2':1.5, 'w':0.6, 'iterations': 100})
__author__="Martin Haviar"
__date__ ="$18 Mar 2013 10:40:30 PM$"


from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
import pandas as pd
import pandas.io.data as web
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import timeit
from scipy import stats
from pandas.io.pytables import HDFStore
from datetime import datetime
from Data import Data
from Portfolio import Portfolio
from Selector import Selector
from Simulator import Simulator
from Selector import Selector
import dist
import experiments

import seaborn as sns
sns.set_context("paper") # , rc={"lines.linewidth": 1.5}
sns.set_style("whitegrid")


data = Data()

options = {'type':'pso', 'opts':{'iterations':1000, 'verbose':True}} # , 'pop':None, 'speed_factor':None
sim = Simulator(data, date=datetime(2008,1,4), periods=24, window=30*6, iwindow=30, maxAssets=10, options=options, selector="includeVix", repeatopt=3)
# sim.load('results/sim50d50p0.1slowGuidedCostPenalty.h5')
# sim.plot()
sim.run()

# exp_name = "results/vix1.h5"
# print exp_name

# # data.close()
# df = pd.HDFStore(exp_name)
# df['e'] = sim.result
# df['s'] = sim.s
# df.close()


# # --- DPT experiment ----
# # d, p, t, u = experiments.particles_dimensions(data)
# sns.set_style("whitegrid")
# fig = plt.figure()
# # ax = fig.gca(projection='3d')
# ax = fig.add_subplot(111, projection='3d')
# # ax.plot_wireframe(d, p, t, cmap=cm.jet, linewidth=0.2)
# ax.plot_trisurf(d.flatten(), p.flatten(), u.flatten(), cmap=cm.jet, linewidth=0.1)
# plt.xlabel('dimensions')
# plt.ylabel('particles')
# ax.set_zlabel('time     ')
# plt.show()


# p = Portfolio(pd.Series(data.assetList), data, date=datetime(2012, 1, 1), window=365*2, maxAssets=5 ) #data.assetList
# p.optimize('pso', opts={"pop": 20})
# e = experiments.saturation(p)
# print p
# p.optimize('pso', opts={"pop": 50})
# print p

# -- experiment particlesCount ----
# e = experiments.particlesCount(p)
# e.plot()
# plt.set_ylabel('utility')
# plt.set_xlabel('iteration')
# plt.show()

# -- experiment pso_c ----
# e = experiments.pso_c(p)
# h = e.pivot("c1", "c2", "y").apply(lambda x: np.round(x, decimals=3))    
# sns.heatmap(h, annot=True, fmt='-')
# plt.gca().invert_yaxis()
# plt.show()


# sns.set_palette(sns.color_palette("BuGn_d"))
# e.plot()
# plt.show()

# p.optimize('pso', window=12*30, opts={"pop": 100})
# print p

# # p.returns.cumsum().plot()  
# months = 2
# iterations = 5

# r = p.getNormalizedReturns(days=30*months)
# r.plot(label="Equally balanced")
# print p.returns['A']
# print p.sortino()

# print p.getReturns()
# p.getReturns().hist(bins=15).plot()
# plt.show()

# print p.getNormalizedReturns(days=60)
# print p.sortino(p.returns['A'])

# p.optimize('basinhopping', window=12*30, opts={"niter":iterations})
# p.optimize('pso', window=6*30)
# print p
# r = p.getNormalizedReturns(days=30)

# for i in range(months-1):
#   p.shift(30)
#   # p.optimize('basinhopping', opts={"niter":iterations})
#   p.optimize('pso', window=6*30)
#   new = p.getNormalizedReturns(days=30) * r.iloc[-1]
#   r = r.append(new, verify_integrity=False) 


# r.plot(label="Particle swarm")
# r = p.getNormalizedReturns(days=30) 

# for i in range(months-1):
#   p.shift(30)
#   p.optimize('basinhopping', opts={"niter":iterations})  
#   new = p.getNormalizedReturns(days=30) * r.iloc[-1]
#   r = r.append(new, verify_integrity=False) 


# r.plot(label="Sim. annealing")



# plt.legend(loc='best')

# plt.show()

# portfolio selection
# p2 = Portfolio(pd.Series(data.assetList), data, date=datetime(2013, 10, 1), window=10,  maxAssets=50 ) #data.assetList
# print p2.assets

# print timeit.Timer(p.sharpe).timeit(number=100)
# print timeit.Timer(p.calculatePortfolioSharpe).timeit(number=100)




# p.sharpe()

def assetsPlot():
    rets = pd.DataFrame()
    for symbol in p.portfolio.index:
        rets[symbol] = (p.returns[symbol].cumsum() + 1)

    rets.plot(colormap='jet', linewidth=2.0).legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.style.use('ggplot')

    plt.show()


