Пример #1
0
def create_portfolio(data):
    print("CREATING PORTFOLIO")
    pf = Portfolio()

    for index, row in data.iterrows():
        ticker = row['Verdipapir']
        amount = float(row['Antall'].replace(',', '.').replace(' ', ''))
        kurs = float(row['Kurs'].replace(',', '.').replace(' ', ''))
        vekslingskurs = float(row['Vekslingskurs'].replace(',', '.').replace(
            ' ', ''))
        transaksjonstype = row['Transaksjonstype']
        belop = float(row['Beløb'].replace(',', '.').replace(' ', ''))

        # Deposit and withdraw cash
        if transaksjonstype == 'INNSKUDD' or transaksjonstype == 'UTTAK INTERNET':
            if transaksjonstype == 'INNSKUDD':
                pf.deposit(belop)
            if transaksjonstype == 'UTTAK INTERNET':
                pf.withdraw(belop)

        if transaksjonstype == 'KJØPT' or transaksjonstype == 'SALG':
            a = Asset(ticker)
            pf.buy(a, amount,
                   (kurs * vekslingskurs)) if belop < 0 else pf.sell(
                       a, amount, (kurs * vekslingskurs))

    return pf
Пример #2
0
    def test_update_befor_trade(self):
        p = Portfolio(
            buy_commission_rate=0.001,
            sell_commission_rate=0.0015,
            min_commission=5.0, round_lot=100)
        p.buy(price=10.0, volume=1000)
        p.update_before_trade(divide_rate=1.0)
        self.assertEqual(1000, p.sellable)
        self.assertEqual(0, p.frozen_volume)
        self.assertEqual(0, p.transaction_cost)

        p = Portfolio(
            buy_commission_rate=0.001,
            sell_commission_rate=0.0015, min_commission=5.0, round_lot=100,
            divide_rate_threshold=1.005)
        p.buy(price=10.0, volume=1000)
        p.update_before_trade(divide_rate=1.1)
        self.assertEqual(1100, p.volume)
        self.assertEqual(1100, p.sellable)
        # 有拆分
        p.update_before_trade(divide_rate=1.006)
        self.assertEqual(1106, p.volume)
        self.assertEqual(1106, p.sellable)
        # 没有拆分
        p.update_before_trade(divide_rate=1.005)
        self.assertEqual(1106, p.volume)
        self.assertEqual(1106, p.sellable)
Пример #3
0
def trade_thresholds(prices_o, coins, start_amt, start_t, end_t, min_buy = -np.inf,
                     max_buy = np.inf, min_sell = -np.inf, max_sell = np.inf, fee = 0):
    # buy/sell if change above/below some threshold % change
    #
    # input:
    # prices : dataframe of price history
    # coins : list of coins (by symbol) available to buy
    # start_amt : initial investment amount
    # choices : list of chosen coins by rank
    # start_t, end_t : start and ending indices in price
    # lag : the number of periods to look back to determine % gain (default 1)
    # fee : trading fee as a fraction of total transaction (default 0)
    #
    # output:
    # list with total value and amount of each coin held for each time t
    
    pct_chg = pd.DataFrame(index = prices_o.index, columns = prices_o.columns)
    for c in prices_o.columns:
        pct_chg[c] = prices_o[c] / prices_o[c].shift(1) - 1
    
    prices = prices_o.loc[start_t:end_t]
    pct_chg = pct_chg.loc[start_t:end_t]
    
    p = Portfolio(start_amt, coins, 0)
    c_held = []
    
    for i in range(len(prices.index)):
        a = pct_chg.iloc[i]
        a = a[a != np.inf]
        a = a[~pd.isnull(a)]
        
        for c in a.index:
            p.update_price(c, pct_chg.iloc[i][c])
        
        c_buy = [c for c in a.index if a[c] <= max_buy and a[c] >= min_buy]
        c_sell = [c for c in a.index if a[c] <= max_sell and a[c] >= min_sell]
        c_held = [c for c in set(c_held+c_buy) if c not in c_sell]
        
        #print(c_buy, c_sell, c_held, a)
        for c in c_sell:
            p.sell(c, p.held[c])
            
        if len(c_held) > 0:
            amt_each = p.value() / len(c_held)
            #print(p.value(), p.cash, amt_each)
            
            for c in c_held:
                if p.held[c] > amt_each:
                    p.sell(c, p.held[c] - amt_each)
            
            for c in c_held:
                if p.held[c] < amt_each:
                    p.buy(c, amt_each - p.held[c])
        
        p.snapshot(i)
    
    return p.hist
Пример #4
0
def hold_rebalance(prices_o, coins, start_amt, start_t, end_t, rebal_rate=1, fee=0):
    # distribute cash evenly across available coins
    #
    # input:
    # prices : dataframe of price history
    # coins : list of coins (by symbol) available to buy
    # start_amt : initial investment amount
    # start_t, end_t : start and ending indices in price
    # fee : trading fee as a fraction of total transaction (default 0)
    #
    # output:
    # list with total value and amount of each coin held for each time t
    
    pct_chg = pd.DataFrame(index = prices_o.index, columns = prices_o.columns)
    for c in prices_o.columns:
        pct_chg[c] = prices_o[c] / prices_o[c].shift(1) - 1
    
    prices = prices_o.loc[start_t:end_t]
    pct_chg = pct_chg.loc[start_t:end_t]
    
    p = Portfolio(start_amt, coins, 0)
    
    for i in range(len(prices.index)):
        a = pct_chg.iloc[i]
        a = a[a != np.inf]
        a = a[~pd.isnull(a)]
        
        for c in a.index:
            p.update_price(c, pct_chg.iloc[i][c])
        
        if i % rebal_rate == 0:
            amt_each = p.value() / np.sum(prices.iloc[i] > 0)
            
            for c in a.index:
                if p.held[c] > amt_each:
                    p.sell(c, p.held[c] - amt_each)
        
            for c in a.index:
                if p.held[c] < amt_each:
                    p.buy(c, amt_each - p.held[c])
                
        p.snapshot(i)
        
    # confirm via averages
    cash = [start_amt]
    for i in range(1, len(prices.index)):
        a = pct_chg.iloc[i]
        a = a[a != np.inf]
        a = a[~pd.isnull(a)]
        avg_chg = np.average(a)
        new_amt = cash[-1] * (avg_chg+1)
        cash.append(new_amt)
    
    return p.hist
Пример #5
0
class Simulator:
    def __init__(self,
                 num_coins_per_order=1,
                 portfolio_cash=1000.0,
                 coin=Coin("ethereum"),
                 features=[
                     "rolling_mean", "rolling_std", "sharpe_ratio",
                     "bollinger_upper", "bollinger_lower"
                 ]):
        self.num_coins_per_order = num_coins_per_order
        self.coin = coin
        self.portfolio = Portfolio(portfolio_cash=portfolio_cash, coin=coin)
        self.features = features

    def get_current_state(self):
        return self.portfolio.getCurrentState(self.features)

    def get_current_holdings(self):
        return self.portfolio.getCurrentHoldings()

    def get_ran_action(self):
        return Action(randint(0, 2))

    def act_and_step(self, action):
        #print 'Taking action:', action
        if action == Action.BUY:
            self.portfolio.buy(self.num_coins_per_order)
        elif action == Action.SELL:
            self.portfolio.sell(self.num_coins_per_order)

        state = self.get_current_state()
        reward = self.portfolio.getReturnsPercent()

        if self.portfolio.step() is False:
            return [state, reward, True]

        return [state, reward, False]

    def reset(self):
        self.portfolio.reset()

    def get_state_size(self):
        return len(self.get_current_state())

    def get_action_size(self):
        return len(Action)

    def plot_coin_price(self):
        self.coin.plot()
Пример #6
0
 def test_buy(self):
     p = Portfolio(
         buy_commission_rate=0.001,
         sell_commission_rate=0.0015,
         min_commission=5.0, round_lot=100)
     self.assertEqual((-10010.0, 10.0, 1000),
                      p.buy(price=10.0, volume=1000))
     self.assertEqual(10.0, p.transaction_cost)
     self.assertEqual(10.01, p.avg_price)
     self.assertEqual(10.0, p._price)
     self.assertEqual(1000, p.volume)
     self.assertEqual(1000, p.frozen_volume)
     self.assertEqual(10.0, p.all_transaction_cost)
     self.assertEqual((-10010.0, 10.0, 1000),
                      p.buy(price=10.0, volume=1000))
     self.assertEqual(20.0, p.transaction_cost)
     self.assertEqual(10.01, p.avg_price)
     self.assertEqual(10.0, p._price)
     self.assertEqual(2000, p.volume)
     self.assertEqual(2000, p.frozen_volume)
     self.assertEqual(20.0, p.all_transaction_cost)
Пример #7
0
def buy_and_hold(prices_o, coins, start_amt, start_t, end_t, fee=0):
    # invest an equal amount in each coin and hodl
    #
    # input:
    # prices_o : dataframe of price history
    # coins : list of coins (by symbol) available to buy
    # start_amt : initial investment amount
    # start_t, end_t : start and ending indices in price
    # fee : trading fee as a fraction of total transaction (default 0)
    #
    # output:
    # list with total value and amount of each coin held for each time t

    
    pct_chg = pd.DataFrame(index = prices_o.index, columns = prices_o.columns)
    for c in prices_o.columns:
        pct_chg[c] = prices_o[c] / prices_o[c].shift(1) - 1
    
    prices = prices_o.loc[start_t:end_t]
    pct_chg = pct_chg.loc[start_t:end_t]

    p = Portfolio(start_amt, coins, fee)
    amt_each = start_amt / len(coins)
    
    for c in coins:
        if prices.iloc[0][c] > 0:
            p.buy(c, amt_each, 0)
    p.snapshot(0)
    
    for i in range(1, len(prices.index)):
        for c in coins:
            if prices.iloc[i-1][c] > 0:
                p.update_price(c, pct_chg.iloc[i][c])
            elif prices.iloc[i][c] > 0:
                p.buy(c, amt_each, 0)
        p.snapshot(i)
    
    return p.hist
Пример #8
0
 def test_sell(self):
     p = Portfolio(
         buy_commission_rate=0.001,
         sell_commission_rate=0.0015, min_commission=5.0, round_lot=100)
     self.assertEqual((-10010.0, 10.0, 1000),
                      p.buy(price=10.0, volume=1000))
     p.update_before_trade(divide_rate=1.0)
     p.sell(price=11, volume=500)
     self.assertEqual(8.25, p.transaction_cost)
     self.assertEqual(9.0365, p.avg_price)
     self.assertEqual(11.0, p._price)
     self.assertEqual(500, p.volume)
     self.assertEqual(500, p.sellable)
     self.assertEqual(18.25, p.all_transaction_cost)
     p.sell(price=11, volume=500)
     self.assertEqual(16.5, p.transaction_cost)
     self.assertEqual(0, p.avg_price)
     self.assertEqual(11, p._price)
     self.assertEqual(0, p.volume)
     self.assertEqual(0, p.sellable)
     self.assertEqual(26.5, p.all_transaction_cost)
 def test_buy_two_stock(self):
     p = Portfolio()
     p.buy('IBM',100, 176.48)
     p.buy('HPQ',100, 36.15)
     assert p.cost() == 21263.0
 def test_buy_two_stock(self):
     p = Portfolio()
     p.buy('IBM',100, 176.48)
     p.buy('HPQ',100, 36.15)
     assert p.cost() == 21263.0
 def test_buy_two_stock(self):
     p = Portfolio()
     p.buy('IBM',100, 176.48)
     p.buy('HPQ',100, 36.15)
     self.assertEqual(p.cost(),21263.0)
Пример #12
0
 def test_buy_two_stock(self):
     p = Portfolio()
     p.buy('IBM', 100, 176.48)
     p.buy('HPQ', 100, 36.15)
     self.assertEqual(p.cost(), 21263.0)
Пример #13
0
def trade_top_n_except(prices_o, coins, start_amt, choices, start_t, end_t, bear_thresh=-0.1, lag = 1, hold_for = 1, fee=0):
    # distribute investment across coins by rank in % gain
    #
    # input:
    # prices : dataframe of price history
    # coins : list of coins (by symbol) available to buy
    # start_amt : initial investment amount
    # choices : list of chosen coins by rank
    # start_t, end_t : start and ending indices in price
    # lag : the number of periods to look back to determine % gain (default 1)
    # fee : trading fee as a fraction of total transaction (default 0)
    #
    # output:
    # list with total value and amount of each coin held for each time t
        
    pct_chg = pd.DataFrame(index = prices_o.index, columns = prices_o.columns)
    for c in prices_o.columns:
        pct_chg[c] = prices_o[c] / prices_o[c].shift(1) - 1
    
    prices = prices_o.loc[start_t:end_t]
    pct_chg = pct_chg.loc[start_t:end_t]
    
    p = Portfolio(start_amt, coins, 0)
    if lag > 1:
        for i in range(lag-1):
            p.snapshot(i)
    
    amt_each = p.value() / len(choices)
    a = pct_chg.iloc[0]
    a = a[a != np.inf]
    a = a[~pd.isnull(a)]
    
    cnt = 0
    avg = np.average(a)
    #print(avg)
    
    c_choose = []
    if avg < bear_thresh:
        cnt += 1
        for c in choices:
            c_choose.append(a.sort_values(ascending=True).index[c])
        #print(a.sort_values(ascending=True))
    else:
        for c in choices:
            c_choose.append(a.sort_values(ascending=False).index[c])
        #print(a.sort_values(ascending=False))
    
    for c in c_choose:
        p.buy(c, amt_each, 0)
    p.snapshot(lag-1)
    
    for i in range(lag, len(prices.index)):
        a = [1 for x in pct_chg.iloc[i]]
        for j in range(lag):
            a *= 1 + pct_chg.iloc[i-j]
                
        a = a[a != np.inf]
        a = a[~pd.isnull(a)]
        
        avg = np.average(a)
        #print(avg)
        
        c_choose = []
        if avg < 1+bear_thresh:
            cnt += 1
            for c in choices:
                c_choose.append(a.sort_values(ascending=True).index[c])
            #print(a.sort_values(ascending=True))
        else:
            for c in choices:
                c_choose.append(a.sort_values(ascending=False).index[c])
            #print(a.sort_values(ascending=False))
        
        for c in a.index:
            p.update_price(c, pct_chg.iloc[i][c])
        
        if i % hold_for != 0:
            p.snapshot(i)
            continue
        
        amt_each = p.value() / len(choices)
        
        for c in a.index:
            if c not in c_choose:
                p.sell(c)
            elif p.held[c] > amt_each:
                p.sell(c, p.held[c] - amt_each)
        
        for c in c_choose:
            if p.held[c] < amt_each:
                p.buy(c, amt_each - p.held[c])
        
        p.snapshot(i)
    
    #print(cnt)
    
    return p.hist
    
    
    
    
    
    
    
    
Пример #14
0
 def test_buy_two_stock(self):
     p = Portfolio()
     p.buy('IBM', 100, 176.48)
     p.buy('HPQ', 100, 36.15, 'blah')
     self.assertCostEqual(p, 21263.0)
Пример #15
0
 def test_buy_one_stock(self):
     p = Portfolio()
     p.buy('IBM', 100, 176.48)
     self.assertEqual(p.cost(), 17648.0)
Пример #16
0
                selected_portfolio = Strategies.embedding_classification(
                    PORTFOLIO_SIZE, model, embedding_matrix, embedding_list)

                # print("=============================================================================================")
                # print("Stock Network: {}".format(NETWORK_NAME))
                # print("\nselected_portfolio: ", selected_portfolio)
                # print("\nBuy at: {}, Sell at {}".format(BUY_DATE, SELL_DATE))
                # print("\nCurrent cash: {}".format(STOCK_PORTFOLIO.cash))
                # print("number of node: {}".format(len(STOCK_NETWORK)))
                ## Buy assets
                for asset in selected_portfolio:
                    stock = asset[0]
                    weight = asset[1]
                    date_index = get_date_index(STOCK_MAP, stock, BUY_DATE)
                    price = STOCK_MAP[stock]['price'][date_index]
                    STOCK_PORTFOLIO.buy(stock, price, weight)

                ## Sell assets
                for asset in selected_portfolio:
                    stock = asset[0]
                    date_index = get_date_index(STOCK_MAP, stock, SELL_DATE)
                    price = STOCK_MAP[stock]['price'][date_index]
                    STOCK_PORTFOLIO.sell(stock, price)

                PORTFOLIO_VALUE.append(STOCK_PORTFOLIO.cash)

                ## Buy assets
                _index_portfolio = [('SPY', 1)]
                for asset in _index_portfolio:
                    stock = asset[0]
                    weight = asset[1]
from portfolio import Portfolio

p = Portfolio()
print("Empty portfolio cost: {}".format(p.cost()))
p.buy('IBM', 100, 176.48)
print("With 100 IBM @ 176.48: {}".format(p.cost()))
p.buy("HPQ", 100, 36.15)
print("With 100 HPQ @ 36.15: {}".format(p.cost()))
 def test_buy_one_stock(self):
     p = Portfolio()
     p.buy('IBM',100, 176.48)
     self.assertEqual(p.cost(),17648.0)
Пример #19
0
 def test_buy_two_stocks(self):
     p = Portfolio()
     p.buy("IBM", 100, 176.48)
     p.buy("HPQ", 100,  36.15)
     assert p.cost() == 21263.0
Пример #20
0
 def test_buy_one_stock(self):
     p = Portfolio()
     p.buy("IBM", 100, 176.48)
     assert p.cost() == 17648.0
from portfolio import Portfolio

p = Portfolio()
print("Empty portfolio cost: {}, should be 0.0".format(p.cost()))
assert p.cost() == 0
p.buy('IBM', 100, 176.48)
print("With 100 IBM @ 176.48: {}, should be 17648.0".format(p.cost()))
assert p.cost() == 17648.0
p.buy("HPQ", 100, 36.15)
print("With 100 HPQ @ 36.15: {}, should be 21263.0".format(p.cost()))
assert p.cost() == 21263.0
 def test_buy_one_stock(self):
     p = Portfolio()
     p.buy('IBM',100, 176.48)
     assert p.cost() == 17648.0
 def test_buy_two_stock(self):
     p = Portfolio()
     p.buy('IBM',100, 176.48)
     p.buy('HPQ',100, 36.15, 'blah')
     self.assertCostEqual(p,21263.0)