Esempio n. 1
0
def alloc_backtest(alloc, start):
    """
    @summary: Back tests an allocation from a pickle file. Uses a starting
              portfolio value of start.
    @param alloc: Name of allocation pickle file. Pickle file contains a
                  DataMatrix with timestamps as indexes and stock symbols as
                  columns, with the last column being the _CASH symbol,
                  indicating how much
    of the allocation is in cash.
    @param start: integer specifying the starting value of the portfolio
    @return funds: List of fund values indicating the value of the portfolio
                   throughout the back test.
    @rtype timeSeries
    """

    #read in alloc table from command line arguements
    alloc_input_file = open(alloc, "r")
    alloc = cPickle.load(alloc_input_file)

    # Get the data from the data store
    dataobj = da.DataAccess('Norgate')
    startday = alloc.index[0] - dt.timedelta(days=10)
    endday = alloc.index[-1]

    # Get desired timestamps
    timeofday = dt.timedelta(hours=16)
    timestamps = du.getNYSEdays(startday, endday, timeofday)
    historic = dataobj.get_data(timestamps, list(alloc.columns[0:-1]), "close")
    #backtestx
    [fund, leverage, commissions, slippage] = qs.tradesim(alloc, historic, int(start), 1, True, 0.02, 5, 0.02)

    return [fund, leverage, commissions, slippage]
Esempio n. 2
0
def alloc_backtest(alloc, start):
    """
    @summary: Back tests an allocation from a pickle file. Uses a starting 
              portfolio value of start.
    @param alloc: Name of allocation pickle file. Pickle file contains a 
                  DataMatrix with timestamps as indexes and stock symbols as
                  columns, with the last column being the _CASH symbol, 
                  indicating how much
    of the allocation is in cash.
    @param start: integer specifying the starting value of the portfolio
    @return funds: List of fund values indicating the value of the portfolio 
                   throughout the back test.
    @rtype timeSeries
    """

    #read in alloc table from command line arguements
    alloc_input_file = open(alloc, "r")
    alloc = pickle.load(alloc_input_file)

    # Get the data from the data store
    dataobj = da.DataAccess('Norgate')
    startday = alloc.index[0] - dt.timedelta(days=10)
    endday = alloc.index[-1]

    # Get desired timestamps
    timeofday = dt.timedelta(hours=16)
    timestamps = du.getNYSEdays(startday, endday, timeofday)
    historic = dataobj.get_data(timestamps, list(alloc.columns[0:-1]), "close")
    #backtestx
    [fund, leverage, commissions,
     slippage] = qs.tradesim(alloc, historic, int(start), 1, True, 0.02, 5,
                             0.02)

    return [fund, leverage, commissions, slippage]
def main():
    '''Main Function'''

    # List of symbols
    ls_symbols = ["AAPL", "GOOG"]

    # Start and End date of the charts
    dt_start = dt.datetime(2008, 1, 1)
    dt_end = dt.datetime(2010, 12, 31)

    # We need closing prices so the timestamp should be hours=16.
    dt_timeofday = dt.timedelta(hours=16)

    # Get a list of trading days between the start and the end.
    ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)

    # Creating an object of the dataaccess class with Yahoo as the source.
    c_dataobj = da.DataAccess('Yahoo')

    # Reading just the close prices
    df_close = c_dataobj.get_data(ldt_timestamps, ls_symbols, "close")

    # Creating the allocation dataframe
    # We offset the time for the simulator to have atleast one
    # datavalue before the allocation.
    df_alloc = pd.DataFrame(np.array([[0.5, 0.5]]),
                index=[ldt_timestamps[0] + dt.timedelta(hours=5)],
                columns=ls_symbols)

    dt_last_date = ldt_timestamps[0]
    # Looping through all dates and creating monthly allocations
    for dt_date in ldt_timestamps[1:]:
        if dt_last_date.month != dt_date.month:
            # Create allocation
            na_vals = np.random.randint(0, 1000, len(ls_symbols))
            na_vals = na_vals / float(sum(na_vals))
            na_vals = na_vals.reshape(1, -1)
            # Append to the dataframe
            df_new_row = pd.DataFrame(na_vals, index=[dt_date],
                                        columns=ls_symbols)
            df_alloc = df_alloc.append(df_new_row)
        dt_last_date = dt_date

    # Adding cash to the allocation matrix
    df_alloc['_CASH'] = 0.0

    # Running the simulator on the allocation frame
    (ts_funds, ts_leverage, f_commission, f_slippage, f_borrow_cost) = qstksim.tradesim(df_alloc,
                    df_close, f_start_cash=10000.0, i_leastcount=1, b_followleastcount=True,
                    f_slippage=0.0005, f_minimumcommision=5.0, f_commision_share=0.0035,
                    i_target_leverage=1, f_rate_borrow=3.5, log="transaction.csv")

    print "Simulated Fund Time Series : "
    print ts_funds
    print "Transaction Costs : "
    print "Commissions : ", f_commission
    print "Slippage : ", f_slippage
    print "Borrowing Cost : ", f_borrow_cost
Esempio n. 4
0
    def test_buy_close(self):
        ''' Tests tradesim buy-on-open functionality '''
        (df_funds, ts_leverage, f_commision, f_slippage, f_borrow) = \
              qstksim.tradesim( self.df_alloc, self.df_close, 10000, 1, True, 0.02,
                           5, 0.02)

        print 'Commision Costs : ' + str(f_commision)
        print 'Slippage : ' + str(f_slippage)
        print 'Short Borrowing Cost : ' + str(f_borrow)
        print 'Leverage : '	
        print ts_leverage
        np.testing.assert_approx_equal(df_funds[-1], \
             10000 * self.i_open_result, significant = 3)
        self.assertTrue(True)
Esempio n. 5
0
    def test_buy_close(self):
        ''' Tests tradesim buy-on-open functionality '''
        (df_funds, ts_leverage, f_commision, f_slippage, f_borrow) = \
              qstksim.tradesim( self.df_alloc, self.df_close, 10000, 1, True,
                                0.02, 5, 0.02)

        print 'Commision Costs : ' + str(f_commision)
        print 'Slippage : ' + str(f_slippage)
        print 'Short Borrowing Cost : ' + str(f_borrow)
        print 'Leverage : '	
        print ts_leverage
        np.testing.assert_approx_equal(df_funds[-1], \
             10000 * self.i_open_result, significant = 3)
        self.assertTrue(True)
Esempio n. 6
0
                          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( \
Esempio n. 7
0
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()