Example #1
0
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
    print df_alloc
Example #2
0
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
    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)
    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)
    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)
Example #6
0
    dataobj = da.DataAccess('Yahoo')
    ls_symbols = dataobj.get_symbols_from_list('sp5002012')
    #ls_symbols = ['GOOG','IBM']
    ls_symbols.append('SPY')
    ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']
    ldf_data = dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys)
    d_data = dict(zip(ls_keys, ldf_data))
    for s_key in ls_keys:
        d_data[s_key] = d_data[s_key].fillna(method='ffill')
        d_data[s_key] = d_data[s_key].fillna(method='bfill')
        d_data[s_key] = d_data[s_key].fillna(1.0)

    df_events = find_events(ls_symbols, d_data)

    print "Simulating Study"
    (ts_funds, ts_leverage, f_commission, f_slippage,
     f_borrow_cost) = qstksim.tradesim(df_alloc,
                                       df_close,
                                       f_start_cash=1000000,
                                       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='simbb.csv')
'''
http://wiki.quantsoftware.org/index.php?title=CompInvesti_Homework_7
'''
Example #7
0
    
total_return_factor = pd.DataFrame(np.ones(shape=(8, noa)), \
                                      index=dates, columns=symbols)
trade_volume = pd.DataFrame(np.random.randint(100, 500, size=(8, noa)), \
                                      index=dates, columns=symbols)
exec_price_return = pd.DataFrame(np.random.randint(low=5,size=(8, noa)), \
                                      index=dates, columns=symbols)
initial_holding = pd.DataFrame([[100, 100, 500, 600, 800, 10000],[100, 100, 500, 600, 800, 10000]], \
                                      index=dates[:2], columns=symbols_and_cash)
#initial_holding = 1000
target_portfolio_wgt = pd.DataFrame()
for i in range(8):
    weights = np.random.random(noa)
    weights /= np.sum(weights)
    target_portfolio_wgt = target_portfolio_wgt.append(pd.DataFrame(weights).T)
target_portfolio_wgt.index = dates
target_portfolio_wgt.columns = symbols
target_portfolio_wgt['Cash'] = 0
# List of symbols
ls_symbols = ['A', 'B', 'C', 'D', 'E']

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

(ts_funds, ts_leverage, f_commission, f_slippage, f_borrow_cost) = qstksim.tradesim(target_portfolio_wgt,
                    market_to_market_price, 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")