'''
(c) 2011, 2012 Georgia Tech Research Corporation
This source code is released under the New BSD license.  Please see
http://wiki.quantsoftware.org/index.php?title=QSTK_License
for license details.


Created on September, 12, 2011

@author:Drew Bratcher
@contact: dbratcher@gatech.edu
@summary: Contains tutorial for backtester and report.

'''


#
# tutorial5.py
#
# @summary: Uses the quicksim backtester and OneStock strategy to create
# and back test an allocation. Displays the result using the report module.
#
# @author: Drew Bratcher
#
#

#python imports
import os
import pandas as pand
import datetime as dt
import random as rgen

#qstk imports
import qstksim
import qstkutil.DataAccess as da
import qstkutil.qsdateutil as du
from Bin import report
from Bin import csv2fund
        
startday = dt.datetime(2008, 1, 1)
endday = dt.datetime(2012, 2, 1)

l_symbols = ['AAPL','GOOG']

#Get desired timestamps
timeofday = dt.timedelta(hours = 16)
ldt_timestamps = du.getNYSEdays(startday, endday, timeofday)

dataobj = da.DataAccess('Yahoo')
df_close = dataobj.get_data( \
                ldt_timestamps, l_symbols, "close", verbose=False)

df_alloc = pand.DataFrame(index=[dt.datetime(2008, 2, 1)], data=[[0.5,0.5]], columns=l_symbols)

for day in ldt_timestamps:
    randomfloat=rgen.random()
    df_alloc = df_alloc.append( \
             pand.DataFrame(index=[day], \
                              data=[[randomfloat, 1-randomfloat]], columns=l_symbols))
    

df_alloc['_CASH'] = 0

''' Tests tradesim buy-on-open functionality '''
(df_funds, ts_leverage, f_commision, f_slippage) = qstksim.tradesim( df_alloc, df_close, 1000000, 1, True, 0.02, 5, 0.02, log="transactions.csv")
df_aapl = pand.DataFrame(index=df_funds.index, data=df_funds.values, columns=["FUND"])
l_symbols = ['GOOG','MSFT']

#Get desired timestamps
timeofday = dt.timedelta(hours = 16)
ldt_timestamps = du.getNYSEdays(startday, endday, timeofday)

dataobj = da.DataAccess('Yahoo')
df_close = dataobj.get_data( \
                ldt_timestamps, l_symbols, "close", verbose=False)

df_alloc = pand.DataFrame(index=[dt.datetime(2008, 2, 1)], data=[[0.5,0.5]], columns=l_symbols)

for day in ldt_timestamps:
    randomfloat=rgen.random()
    df_alloc = df_alloc.append( \
             pand.DataFrame(index=[day], \
                              data=[[randomfloat, 1-randomfloat]], columns=l_symbols))
    

df_alloc['_CASH'] = 0

''' Tests tradesim buy-on-open functionality '''
(df_funds, ts_leverage, f_commision, f_slippage) = qstksim.tradesim( df_alloc, df_close, 1000000, 1, True, 0.02, 5, 0.02, log="transactions2.csv")
df_goog = pand.DataFrame(index=df_funds.index, data=df_funds.values, columns=["FUND"])

ls_hedge_params={"Weight of Hedge" : 0.5, \
"Target Beta" : 1,\
"Type of Hedge" : "Long and Short",\
"Rebalancing" : "Weekly",\
"Number of equities" : 30, \
"Lookback period" : "365 days"}
report.print_stats(df_aapl, ["$SPX","MSFT"], "AAPL", s_fund_name="Test Portfolio", original=df_goog, s_original_name="UnHedged", d_trading_params={"Number of trades":200,"Trading Period":"Weekly"},d_hedge_params=ls_hedge_params, s_comments="This is a sample report generated by tutorial 5.", commissions=f_commision, slippage=f_slippage, directory="./AAPL/")
#print "Analyzing Transactions..."
#csv2fund.analyze_transactions("transactions.csv","AAPL")
print "Done"