def test_delete(self):
		"""
		Testing deletion of stock.
		"""
		result = Portfolio()
		result.add_stock("AA", 10, 50, "2010-04-03")
		self.assertTrue(result.delete_stock("AA"), True)
Exemple #2
0
def train(train_end):
    # Load data
    stock1_df = DataReader(const.STOCK1_FILE).get_df()
    stock2_df = DataReader(const.STOCK2_FILE).get_df()

    # Initialize parameters
    iterations = const.ITER
    alpha = const.ALPHA
    discount = const.DISCOUNT
    epsilon = const.EPSILON

    # Initialize learning agent
    agent = QLearningAgent(alpha, discount, epsilon)

    # Initialize starting portfolio state
    init_price = [stock1_df.iloc[0]['Open'], stock2_df.iloc[0]['Open']]
    init_weights = const.WEIGHTS
    init_share_dist = const.SHARE_DIST
    init_pf = Portfolio(init_price, init_weights, init_share_dist)

    print("------------------------TRAINING START------------------------")

    print("------------------------INITIAL VALUES------------------------")
    print(str(init_pf))
    prev_pf = init_pf
    print()

    # Update Q Values for a fixed number of iterations
    for i in range(iterations):
        print("------------------------ITERATION " + str(i) +
              "------------------------")

        # Update Q values for each day in the training period
        for idx in range(1, train_end):
            # Select best action based on Q values
            action = agent.get_action(prev_pf.id)

            # Update stock price
            next_price = [
                stock1_df.iloc[idx]['Open'], stock2_df.iloc[idx]['Open']
            ]

            # Generate next portfolio state
            curr_pf = prev_pf.next_state(action, next_price)

            # Update Q value for previous state
            # Reward = curr_pf.value - prev_pf.value
            agent.update(prev_pf.id, action, curr_pf.id,
                         curr_pf.value - prev_pf.value)

            print("Action : ", action)
            print(str(curr_pf))
            print()

            prev_pf = curr_pf

        print()

    print("------------------------TRAINING END------------------------")
    return agent
Exemple #3
0
    def botCreatePortfolio(self, numberOfAssets=None, portfolioname=None):
        # initiate empty Portfolio
        portfolio = Portfolio()
        if portfolioname is not None:
            if not self.portfolioList.keys().__contains__(portfolioname):
                self.portfolioList[portfolioname] = portfolio
            else:
                self.sendNameTakenMsg(portfolioname)
        else:
            self.portfolioList[self.portfolioList.__len__()] = portfolio

        self.createPortfolio(portfolio, numberOfAssets=numberOfAssets)
    def setUp(self):
        self.DEBUG = True
        assets = ['a', 'b', 'c', 'd', 'e']
        position = [-10, -5, 3, 2, 1]
        price = [1, 2, 10/3, 5, 10]
        factor_value = [-1, 0, 1, 2, 3]
        sector_id = [1, 1, 2, 2, 1]

        self.portfolio_df = pd.DataFrame(index=assets,
                                         data={'position': position,
                                               'price': price,
                                               'factor_value': factor_value,
                                               'sector_id': sector_id})

        self.pf = Portfolio.from_dataframe(dataframe=self.portfolio_df)
	def test_update(self):
		"""
		Testing portfolio creation. initialisation and add stock.
		"""
		if DataHandler.check_portfolio_exists():
			result = Portfolio()
			self.assertIsInstance(result.portfolio, dict)
		else:
			result = Portfolio()
			result.add_stock("AA", 10, 50, "2010-04-03")
			data = StockDataReader.get_data("AA")
			last_price = StockDataReader.last_price(data)
			result.update_stock("AA", data)
			if last_price == result.portfolio['AA']['Last Price $']:
				assertion = True
			else:
				assertion = False
			self.assertTrue(assertion, True)
	def test_portfolio(self):
		"""
		Testing portfolio creation. initialisation and add stock.
		"""
		if DataHandler.check_portfolio_exists():
			result = Portfolio()
			self.assertIsInstance(result.portfolio, dict)
		else:
			result = Portfolio()
			result.add_stock("AA", 10, 50, "2010-04-03")
			self.assertTrue(result.portfolio['AA'], True)
Exemple #7
0
def test(test_start, trained_agent):
    # Initialize data
    stock1_df = DataReader(const.STOCK1_FILE).get_df()
    stock2_df = DataReader(const.STOCK2_FILE).get_df()

    # Initialize starting portfolio state
    init_price = [
        stock1_df.iloc[test_start]['Open'], stock2_df.iloc[test_start]['Open']
    ]
    init_weights = const.WEIGHTS
    init_share_dist = const.SHARE_DIST
    init_pf = Portfolio(init_price, init_weights, init_share_dist)

    prev_pf = init_pf

    print("------------------------TESTING START------------------------")
    # Test model for duration of the test period
    for idx in range(test_start + 1, stock1_df.shape[0]):
        # Get best action based on Q values
        action = trained_agent.get_policy(prev_pf.id)

        # Update stock price
        next_price = [stock1_df.iloc[idx]['Open'], stock2_df.iloc[idx]['Open']]

        # Generate next portfolio state
        curr_pf = prev_pf.next_state(action, next_price)

        print("Action : ", action)
        print(str(curr_pf))
        print()

        prev_pf = curr_pf

    # Calculate profit at the end of testing
    print("PROFIT: " + str(prev_pf.value - init_pf.value))
    print("SCORE: " + str(prev_pf.evaluate()))
    def test_dollar_neutral_top_selection(self):

        def trade_portfolio(buy_low=True):
            if buy_low:
                # liquidate not wanted longs
                for stock in pf1.longs().index:
                    if signal[stock] >= 0:
                        pf1.trade(asset=stock, amount=-pf1.position(stock),
                                  price=1, factor_value=signal[stock],
                                  sector_id=1)

                # liquidate not wanted shorts
                for stock in pf1.shorts().index:
                    if signal[stock] <= 0:
                        pf1.trade(asset=stock, amount=-pf1.position(stock),
                                  price=1, factor_value=signal[stock],
                                  sector_id=1)

                # order new longs and shorts
                for stock in new_pos['new_longs']:
                    pf1.trade(asset=stock, amount=10-pf1.position(stock),
                              price=1, factor_value=signal[stock], sector_id=1)

                for stock in new_pos['new_shorts']:
                    pf1.trade(asset=stock, amount=-10-pf1.position(stock),
                              price=1, factor_value=signal[stock], sector_id=1)
            else:
                # liquidate not wanted longs
                for stock in pf1.longs().index:
                    if signal[stock] <= 0:
                        pf1.trade(asset=stock, amount=-pf1.position(stock),
                                  price=1, factor_value=signal[stock],
                                  sector_id=1)

                # liquidate not wanted shorts
                for stock in pf1.shorts().index:
                    if signal[stock] >= 0:
                        pf1.trade(asset=stock, amount=-pf1.position(stock),
                                  price=1, factor_value=signal[stock],
                                  sector_id=1)

                # order new longs and shorts
                for stock in new_pos['new_longs']:
                    pf1.trade(asset=stock, amount=10-pf1.position(stock),
                              price=1, factor_value=signal[stock], sector_id=1)

                for stock in new_pos['new_shorts']:
                    pf1.trade(asset=stock, amount=-10-pf1.position(stock),
                              price=1, factor_value=signal[stock], sector_id=1)

        signal = pd.Series(data={'a': -2, 'b': 0, 'c': 1, 'd': 2, 'e': 3,
                                 'f': -6, 'g': 9, 'h': -10, 'i': 10})
        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1e-8,
                                               short_quantile=1e-8,
                                               min_th=1e-8,
                                               buy_low=True)
        self.assertEqual(new_pos['new_longs'], ['h'])
        self.assertEqual(new_pos['new_shorts'], ['i'])
        self.assertEqual(new_pos['long_th'], signal['h'])
        self.assertEqual(new_pos['short_th'], signal['i'])
        self.assertEqual(new_pos['current_longs_incr'], [])
        self.assertEqual(new_pos['current_shorts_incr'], [])

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio()

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), ['h'])
        self.assertEqual(pf1.shorts().index.tolist(), ['i'])

        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1,
                                               short_quantile=1,
                                               min_th=1e-8,
                                               buy_low=True)
        self.assertEqual(new_pos['new_longs'], ['h', 'f', 'a'])
        self.assertEqual(new_pos['new_shorts'], ['i', 'g', 'e'])
        self.assertEqual(new_pos['long_th'], -1e-8)
        self.assertEqual(new_pos['short_th'], 1e-8)
        self.assertEqual(new_pos['current_longs_incr'], [])
        self.assertEqual(new_pos['current_shorts_incr'], [])

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio()

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), ['h', 'f', 'a'])
        self.assertEqual(pf1.shorts().index.tolist(), ['i', 'g', 'e'])

        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1e-8,
                                               short_quantile=1e-8,
                                               min_th=1e-8,
                                               buy_low=False)
        self.assertEqual(new_pos['new_longs'], [])
        self.assertEqual(new_pos['new_shorts'], ['h'])
        self.assertEqual(new_pos['long_th'], 10)
        self.assertEqual(new_pos['short_th'], -10)
        self.assertEqual(new_pos['current_longs_incr'], [])
        self.assertEqual(new_pos['current_shorts_incr'], [])

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio(buy_low=False)

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), ['c', 'd', 'e'])
        self.assertEqual(pf1.shorts().index.tolist(), ['a', 'h'])

        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1,
                                               short_quantile=1,
                                               min_th=1e-8,
                                               buy_low=False)
        self.assertEqual(new_pos['new_longs'], [])
        self.assertEqual(new_pos['new_shorts'], ['h', 'f'])
        self.assertEqual(new_pos['long_th'], 1e-8)
        self.assertEqual(new_pos['short_th'], -1e-8)

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio(buy_low=False)

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), ['c', 'd', 'e'])
        self.assertEqual(pf1.shorts().index.tolist(), ['a', 'h', 'f'])

        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=0.5,
                                               short_quantile=0.5,
                                               min_th=1e-8,
                                               buy_low=True)
        self.assertEqual(new_pos['new_longs'], ['h', 'f', 'a'])
        self.assertEqual(new_pos['new_shorts'], ['i', 'g', 'e'])
        self.assertEqual(new_pos['long_th'], -1e-8)
        self.assertEqual(new_pos['short_th'], 1)

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio()

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), ['h', 'f', 'a'])
        self.assertEqual(pf1.shorts().index.tolist(), ['i', 'g', 'e'])

        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=0.5,
                                               short_quantile=0.5,
                                               min_th=1e-8,
                                               buy_low=False)
        self.assertEqual(new_pos['new_longs'], [])
        self.assertEqual(new_pos['new_shorts'], ['h', 'f'])
        self.assertEqual(new_pos['long_th'], 1)
        self.assertEqual(new_pos['short_th'], -1e-8)

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio(buy_low=False)

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), ['c', 'd', 'e'])
        self.assertEqual(pf1.shorts().index.tolist(), ['a', 'h', 'f'])

        signal = pd.Series(data={'b': 0, 'c': 1, 'd': 2, 'e': 3, 'a': -20,
                                 'f': -6, 'g': -9, 'h': -10, 'i': -10})
        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1e-8,
                                               short_quantile=1e-8,
                                               min_th=1e-8,
                                               buy_low=False)
        self.assertEqual(new_pos['new_longs'], [])
        self.assertEqual(new_pos['new_shorts'], [])
        self.assertEqual(new_pos['long_th'], 3)
        self.assertEqual(new_pos['short_th'], -20)
        self.assertEqual(new_pos['current_longs_incr'], ['e'])
        self.assertEqual(new_pos['current_shorts_incr'], ['a'])

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio(buy_low=False)

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), ['c', 'd', 'e'])
        self.assertEqual(pf1.shorts().index.tolist(), ['a'])

        signal = pd.Series(data={'b': 0, 'c': 1, 'd': 2, 'e': 3,
                                 'a': -2, 'f': -6, 'g': -9,
                                 'h': -10, 'i': -10})
        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1,
                                               short_quantile=1,
                                               min_th=1e-8,
                                               buy_low=False)
        self.assertEqual(new_pos['new_longs'], [])
        self.assertEqual(new_pos['new_shorts'], ['i', 'h'])
        self.assertEqual(new_pos['long_th'], 1e-8)
        self.assertEqual(new_pos['short_th'], -1e-8)

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio(buy_low=False)

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), ['c', 'd', 'e'])
        self.assertEqual(pf1.shorts().index.tolist(), ['a', 'i', 'h'])

        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1,
                                               short_quantile=1,
                                               min_th=11,
                                               buy_low=False)
        self.assertEqual(new_pos['new_longs'], [])
        self.assertEqual(new_pos['new_shorts'], [])
        self.assertEqual(new_pos['long_th'], 11)
        self.assertEqual(new_pos['short_th'], -11)

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio(buy_low=False)

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), ['c', 'd', 'e'])
        self.assertEqual(pf1.shorts().index.tolist(), ['a'])

        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1,
                                               short_quantile=1,
                                               min_th=11,
                                               buy_low=True)
        self.assertEqual(new_pos['new_longs'], [])
        self.assertEqual(new_pos['new_shorts'], [])
        self.assertEqual(new_pos['long_th'], -11)
        self.assertEqual(new_pos['short_th'], 11)

        pf1 = Portfolio.from_dataframe(dataframe=self.portfolio_df)

        trade_portfolio(buy_low=True)

        if self.DEBUG:
            print(pf1.longs(), '\n', pf1.shorts())

        self.assertEqual(pf1.longs().index.tolist(), [])
        self.assertEqual(pf1.shorts().index.tolist(), [])

        signal = pd.Series(data={'a': -2, 'f': 2, 'g': np.nan, 'h': -9,
                                 'i': -10, 'j': 3})
        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1,
                                               short_quantile=1,
                                               min_th=1e-8,
                                               buy_low=True)
        self.assertEqual(new_pos['new_longs'], [])
        self.assertEqual(new_pos['new_shorts'], ['j', 'f'])
        self.assertEqual(new_pos['long_th'], -1e-8)
        self.assertEqual(new_pos['short_th'], 1e-8)

        signal = pd.Series(data={'a': np.nan, 'f': np.nan,
                                 'g': np.nan, 'h': np.nan,
                                 'i': 10, 'j': np.nan})
        new_pos = dollar_neutral_top_selection(self.pf, signal,
                                               long_quantile=1,
                                               short_quantile=1,
                                               min_th=1e-8,
                                               buy_low=True)
        self.assertEqual(new_pos['new_longs'], [])
        self.assertEqual(new_pos['new_shorts'], ['i'])
        self.assertEqual(new_pos['long_th'], -1e-8)
        self.assertEqual(new_pos['short_th'], 10)
Exemple #9
0
    def __init__(self):
        self.portfolio = {}
        self.p = Portfolio()
        self.s = Spreadsheet(self.portfolio)

        self.main()
Exemple #10
0
class StockBot:
    def __init__(self):
        self.portfolio = {}
        self.p = Portfolio()
        self.s = Spreadsheet(self.portfolio)

        self.main()

    def getPortfolio(self):
        self.p = Portfolio()
        self.portfolio = self.p.GetPortfolio()

    def generateSpreadsheet(self):
        self.getPortfolio()
        self.s = Spreadsheet(self.portfolio)
        self.s.FillSpreadsheet()

    def buy(self, ticker, shares, price):
        portfolio = ""
        with open("data/portfolio.json", "r") as f:
            portfolio = f.read()
        portfolio = json.loads(portfolio)

        order = {ticker: {"buyPrice": str(price), "shares": shares}}

        portfolioCopy = portfolio
        portfolioCopy.update(order)

        with open("data/portfolio.json", "w") as f:
            json.dump(portfolioCopy, f, sort_keys=True, indent=4)

        return "Bought " + str(
            shares) + " shares of " + ticker + " for $" + str(price) + "."

    def sell(self, ticker, shares):
        portfolio = ""
        with open("data/portfolio.json", "r") as f:
            portfolio = f.read()
        portfolio = json.loads(portfolio)

        if not (ticker in portfolio):
            return "You don't own any " + ticker + "."

        currentShares = int(portfolio[ticker]["shares"])

        if currentShares < shares:
            return "You don't own enough shares to sell " + str(shares) + "."

        if (currentShares - shares) == 0:
            portfolioCopy = portfolio
            portfolioCopy.pop(ticker)
        else:
            order = {
                ticker: {
                    "buyPrice": portfolio[ticker]["buyPrice"],
                    "shares": currentShares - int(shares)
                }
            }

            portfolio.update(order)

        with open("data/portfolio.json", "w") as f:
            json.dump(portfolioCopy, f, sort_keys=True, indent=4)

        buyPrice = float(portfolio[ticker]["buyPrice"])
        sellPrice = round((float(
            self.p.getStockData(ticker)[ticker.upper()]["currentPrice"][1:])),
                          2)
        profit = round(((sellPrice - buyPrice) * shares), 2)

        message = "Sold " + str(
            shares) + " shares of " + ticker + " for $" + str(
                sellPrice) + ".\n"
        message += "You made $" + str(profit) + "."
        return message

    def main(self):
        buffer = "Welcome to StockBot v1.0!\nOptions:"
        while True:
            os.system("clear")
            print(buffer)
            buffer = ""

            print("[1] Generate a report")
            print("[2] Buy")
            print("[3] Sell")
            print("[E] Exit")

            command = input("> ").lower()
            if command == "1":
                self.generateSpreadsheet()
                buffer = "Spreadsheet has been generated."

            elif command == "2":
                print("What is the ticker?")
                ticker = input("> ")

                shares = 0
                print("How many shares to buy?")
                try:
                    shares = int(input("> "))
                except ValueError:
                    buffer = "That is not a valid amount of shares."
                    continue

                price = 0.0
                print("Price to buy at?")
                try:
                    price = float(input("> "))
                except ValueError:
                    buffer = "That is not a valid price."
                    continue

                buffer = self.buy(ticker, shares, price)

            elif command == "3":
                print("What is the ticker?")
                ticker = input("> ")

                shares = 0
                print("How many shares to sell?")
                try:
                    shares = int(input("> "))
                except ValueError:
                    buffer = "That is not a valid amount of shares."
                    continue
                buffer = self.sell(ticker, shares)

            elif command == "e":
                print("Thank you for using StockBot!")
                sys.exit(-1)

            else:
                buffer = "Unknown command."
Exemple #11
0
 def getPortfolio(self):
     self.p = Portfolio()
     self.portfolio = self.p.GetPortfolio()
Exemple #12
0
'''
Daxiang trading robot main entry
'''
from src.portfolio import Portfolio
from src.strategy import Strategy
from src.data import Data
from src.web import Web
import src.settings as s
from time import time, sleep

if __name__ == '__main__':
    data = Data()
    strategy = Strategy()
    portfolio = Portfolio(strategy, data)
    web = Web(portfolio)
    try:
        while True:
            sleep(0.5)
    except KeyboardInterrupt:
        data.close()
            if evaluation is None:
                break

        evaluation_sum: Decimal = ZERO
        analysis_funds: List[Decimal] = []
        table_number: int = len(tables)
        for i in range(table_number):
            analysis_number: int = i + 1
            statistic_name: str = 'statistic analysis{}'.format(
                analysis_number)
            statistic: StatisticBO = StatisticBO(statistic_name)
            broker: BrokerBO = BrokerBO(cash, fee)
            AnalyserBO.analyse(tables[i], StrategyBO.counter_cyclical, broker,
                               statistic, evaluation_attempt)
            evaluation_sum += broker.funds()
            analysis_funds.append(broker.funds().normalize())
            if analysis_number == table_number and evaluation_sum > optimise_sum:
                EvaluationDAO.create(evaluation_sum,
                                     ','.join(map(str, analysis_funds)),
                                     evaluation_attempt)

    @staticmethod
    def start(portfolio: List[str], number: int, group_number: int) -> None:
        group_size: int = int(number / group_number)
        groups: Tuple[Tuple[str]] = Utils.group(group_size, portfolio[:number])
        OptimizationBO.optimise(IntradayDAO.dataframe_group(groups))


if __name__ == '__main__':
    OptimizationBO.start(Portfolio.test_portfolio(), 100, 4)
Exemple #14
0
from src.portfolio import Portfolio
from src.rest import RestQueries
import json

pf = Portfolio()

ourpf = pf.getportfolio(1830)
with open('portfolio.txt', 'w') as outfile:
    json.dump(ourpf, outfile, indent=4)

pfref = pf.getportfolio(2201)
with open('ref.txt', 'w') as outfile:
    json.dump(pfref, outfile, indent=4)

ratio = RestQueries.get("ratio")
with open('ratio.txt', 'w') as outfile:
    json.dump(ratio, outfile, indent=4)

body = {
    "ratio": [12],
    "asset": [1860, 1900],
    "start_date": "2012-01-02",
    "end_date": "2020-11-24"
}
sharpes = RestQueries.post('ratio/invoke', body)
with open('sharpelist.txt', 'w') as outfile:
    json.dump(sharpes, outfile, indent=4)
Exemple #15
0
 def test_constructor_user_defined(self):
     portfolio = Portfolio(self.port_two_name, self.port_three_buy_power,
                           self.port_two_stocks)
     self.assertEqual(portfolio.name, 'two')
     self.assertEqual(portfolio.buy_power, 150000)
     self.assertEqual(portfolio.stocks, {'msft': 100})
Exemple #16
0
 def get_portfolio_three(self):
     return Portfolio(self.port_three_name, self.port_three_buy_power,
                      dict(self.port_three_stocks))
Exemple #17
0
 def get_portfolio_two(self):
     return Portfolio(self.port_two_name, self.port_two_buy_power,
                      dict(self.port_two_stocks))
Exemple #18
0
 def get_portfolio_one(self):
     return Portfolio(self.port_one_name)
Exemple #19
0
assets = ['a', 'b', 'c', 'd', 'e']
position = [-10, -5, 3, 2, 1]
price = [1, 2, 10 / 3, 5, 10]
factor_value = [-1, 0, 1, 2, 3]
sector_id = [1, 1, 2, 2, 1]

portfolio_df = pd.DataFrame(index=assets,
                            data={
                                'position': position,
                                'price': price,
                                'factor_value': factor_value,
                                'sector_id': sector_id
                            })

pf = Portfolio.from_dataframe(dataframe=portfolio_df)
print(pf)
print(pf.sector_net_exposures())
pf.trade(asset='a', amount=10, price=1.1)
print(pf)
print(pf.sector_net_exposures())

print('longs', pf.longs())
print('shorts', pf.shorts())

signal = pd.Series(data={'a': -2, 'f': -6, 'g': 9, 'h': -10, 'i': 10})
new_pos = dollar_neutral_top_selection(pf,
                                       signal,
                                       long_quantile=1,
                                       short_quantile=1,
                                       min_th=0,
Exemple #20
0
                        level=logging.INFO)
    log = logging.getLogger("main")

    parser = argparse.ArgumentParser(description="Hanna main program.")
    parser.add_argument("--online",
                        required=False,
                        default=False,
                        action="store_true")
    parser.add_argument("--logging",
                        required=False,
                        default=False,
                        action="store_true")

    args = parser.parse_args()

    portfolio = Portfolio()
    config = os.path.join(os.getcwd(), "config", "portfolio.json")
    portfolio.load_configuration(json.load(open(config, "r")))

    if args.online:
        c: Credentials = load_credentials()
        client = r.login(c.get_username(), c.get_password())

    portfolio.refresh(args.online, args.logging)
    # deposit = portfolio.plan_deposit(portfolio.get_cash())
    # portfolio.make_deposit(deposit, args.online)
    # portfolio.refresh(args.online, args.logging)

    if args.online:
        r.logout()
Exemple #21
0
class ProcessManager:
    TARGET: str = 'target'
    ARGS: str = 'args'

    CONFIGURATION: Dict[str, Dict[str, Tuple[Any, ...]]] = {
        'update-table-stock': {
            TARGET: StockDAO.update,
            ARGS: (Portfolio.test_prod_portfolio(),)
        },
        'update-table-intraday': {
            TARGET: IntradayBO.update,
            ARGS: (Portfolio.test_prod_portfolio(),)
        },
        'schedule': {
            TARGET: Scheduler.start,
            ARGS: []
        },
        'optimize': {
            TARGET: OptimizationBO.start,
            ARGS: (Portfolio.test_portfolio(), 100, 4)
        },
        'forward': {
            TARGET: ForwardBO.start,
            ARGS: []
        }
    }

    @staticmethod
    def start(name: str) -> bool:
        if name in ProcessManager.CONFIGURATION.keys():
            configuration: Dict[str, Tuple[Any, ...]] = ProcessManager.CONFIGURATION.get(name)
            process: Process = ProcessManager.__find(name)
            if process is None or not process.is_alive():
                process = multiprocessing.Process(name=name, target=configuration.get(ProcessManager.TARGET),
                                                  args=configuration.get(ProcessManager.ARGS))
                process.start()
                return True
        return False

    @staticmethod
    def stop(name: str) -> bool:
        if name in ProcessManager.CONFIGURATION.keys():
            process: Process = ProcessManager.__find(name)
            if process is not None:
                process.terminate()
                process.join()
                return True
        return False

    @staticmethod
    def running() -> bool:
        return len(multiprocessing.active_children()) > 0

    @staticmethod
    def get_active_names() -> List[str]:
        return sorted(list(map(lambda p: p.name, list(multiprocessing.active_children()))))

    @staticmethod
    def get_inactive_names() -> List[str]:
        return sorted(list(filter(lambda p: p not in ProcessManager.get_active_names(),
                                  ProcessManager.CONFIGURATION.keys())))

    @staticmethod
    def __find(name: str) -> Optional[Process]:
        return next(iter(filter(lambda p: p.name == name, multiprocessing.active_children())), None)
from src.utils import DataHandler
from src.portfolio import Portfolio


class MakeMenu:
    def __init__(self):
        pass


class ThreadHandler:
    @classmethod
    def spawn_thread(cls, data):
        pass


latest_portfolio = Portfolio()
print(latest_portfolio.portfolio)
DataHandler.save_portfolio(latest_portfolio.portfolio)

main_msg = """
What would you like to do?
1: Add stock to portfolio
2: View portfolio
3: Overall performance
4: Update portfolio
5: Delete stock from portfolio
9: Exit
"""

while True:
    print(main_msg)