def subscribe_ticker(self, ticker):
        """
        Subscribes the price handler to a new ticker symbol.
        """
        if ticker not in self.tickers:
            try:
                self._open_ticker_price_csv(ticker)
                dft = self.tickers_data[ticker]
                row0 = dft.iloc[0]

                close = PriceParser.parse(row0["Close"])
                adj_close = PriceParser.parse(row0["Adj Close"])

                ticker_prices = {
                    "close": close,
                    "adj_close": adj_close,
                    "timestamp": dft.index[0]
                }
                self.tickers[ticker] = ticker_prices
            except OSError:
                print("Could not subscribe ticker %s "
                      "as no data CSV found for pricing." % ticker)
        else:
            print("Could not subscribe ticker %s "
                  "as is already subscribed." % ticker)
 def _create_event(self, index, ticker, row):
     """
     Obtain all elements of the bar a row of dataframe
     and return a TickEvent
     """
     bid = PriceParser.parse(row["Bid"])
     ask = PriceParser.parse(row["Ask"])
     tev = TickEvent(ticker, index, bid, ask)
     return tev
Exemple #3
0
 def update(self, timestamp, portfolio_handler):
     """
     Update equity curve and benchmark equity curve that must be tracked
     over time.
     """
     self.equity[timestamp] = PriceParser.display(
         self.portfolio_handler.portfolio.equity)
     if self.benchmark is not None:
         self.equity_benchmark[timestamp] = PriceParser.display(
             self.price_handler.get_last_close(self.benchmark))
Exemple #4
0
 def _create_event(self, index, ticker, row):
     """
     Obtain all elements of the bar a row of dataframe
     and return a TickEvent
     """
     try:
         bid = PriceParser.parse(row["Bid"])
         ask = PriceParser.parse(row["Ask"])
         tev = TickEvent(ticker, index, bid, ask)
         return tev
     except ValueError:
         raise EmptyTickEvent("row %s %s %s can't be convert to TickEvent" %
                              (index, ticker, row))
 def _create_event(self, index, period, ticker, row):
     """
     Obtain all elements of the bar from a row of dataframe
     and return a BarEvent
     """
     open_price = PriceParser.parse(row["Open"])
     high_price = PriceParser.parse(row["High"])
     low_price = PriceParser.parse(row["Low"])
     close_price = PriceParser.parse(row["Close"])
     adj_close_price = PriceParser.parse(row["Adj Close"])
     volume = int(row["Volume"])
     bev = BarEvent(ticker, index, period, open_price, high_price,
                    low_price, close_price, volume, adj_close_price)
     return bev
 def calculate_ib_commission(self, quantity, fill_price):
     """
     Calculate the Interactive Brokers commission for
     a transaction. This is based on the US Fixed pricing,
     the details of which can be found here:
     https://www.interactivebrokers.co.uk/en/index.php?f=1590&p=stocks1
     """
     commission = min(0.5 * fill_price * quantity,
                      max(1.0, 0.005 * quantity))
     return PriceParser.parse(commission)
Exemple #7
0
    def _create_event(self, index, period, ticker, row):
        """
        Obtain all elements of the bar from a row of dataframe
        and return a BarEvent
        """
        try:
            open_price = PriceParser.parse(row["Open"])
            high_price = PriceParser.parse(row["High"])
            low_price = PriceParser.parse(row["Low"])
            close_price = PriceParser.parse(row["Close"])
            adj_close_price = PriceParser.parse(row["Adj Close"])
            volume = int(row["Volume"])

            # Create the tick event for the queue
            bev = BarEvent(ticker, index, period, open_price, high_price,
                           low_price, close_price, volume, adj_close_price)
            return bev
        except ValueError:
            raise EmptyBarEvent(
                "row %s %s %s %s can't be convert to BarEvent" %
                (index, period, ticker, row))
Exemple #8
0
    def calculate_signals(self, event, agent=None):
        if event.type in [EventType.TICK, EventType.BAR]:
            # Format the event for human display
            if event.type == EventType.BAR:
                event.open_price = PriceParser.display(event.open_price)
                event.high_price = PriceParser.display(event.high_price)
                event.low_price = PriceParser.display(event.low_price)
                event.close_price = PriceParser.display(event.close_price)
                event.adj_close_price = PriceParser.display(
                    event.adj_close_price)
            else:  # event.type == EventType.TICK
                event.bid = PriceParser.display(event.bid)
                event.ask = PriceParser.display(event.ask)

            if self.i % self.n == 0 and self.i != 0:
                print(s_speed(event, self.i, self.t0))
                print("")
            if self.i % self.n in range(self.n_window):
                print("%d %s" % (self.i, event))
            self.i += 1
Exemple #9
0
 def x(p):
     return PriceParser.display(p)
Exemple #10
0
    def __init__(self, env, context, config, indicators, strategiesDict, instanceDict) :

        #testing, filename,
           #QQQ benchmark, ticker_weights, title_str, equity):


        super(AgentFactory, self).__init__(env)

        self.context = context

        ticketWeights = instanceDict["tickerWeights"]
        start_date = instanceDict["startDate"]
        end_date = instanceDict["endDate"]
        strategy = instanceDict["strategy"]
        benchmark = instanceDict["benchmark"]
        equity = instanceDict["equity"]

        start_date = parser.parse(start_date)
        end_date = parser.parse(end_date)

        print strategiesDict, start_date, end_date

        positionSizer   = strategiesDict['positionSizer']
        riskManager     = strategiesDict['riskManager']
        portfolioHandler =   strategiesDict['portfolioHandler']
        complianceHandler = strategiesDict['complianceHandler']
        executionHandler = strategiesDict['executionHandler']
        tearsheetStatistics = strategiesDict['tearsheetStatistics']
        displayStrategy = strategiesDict['displayStrategy']
        learningHandler = strategiesDict['learningHandler']
        strategyHandler = strategiesDict['strategyHandler']
        title = strategiesDict['title']

        tmpArray = learningHandler.split(".")
        learningClass = getattr(importlib.import_module("action." + tmpArray[0]), "Action")
        self.learningHandler = learningClass(self.context,instanceDict)

        self.totalActions = 0.0
        self.totalRewards = 0.0

        #self.config = settings.from_file(config, testing)
        self.tickers = [t for t in ticketWeights.keys()]

        # Set up variables needed for backtest
        self.events_queue = queue.Queue()

        self.csv_dir = config.CSV_DATA_DIR
        self.initial_equity = PriceParser.parse(equity)

        # Use Yahoo Daily Price Handler
        self.price_handler = YahooDailyCsvBarPriceHandler(
            self.csv_dir, self.events_queue, self.tickers,
            start_date=start_date, end_date=end_date
        )

        tmpArray=strategyHandler.split(".")
        # Use the monthly liquidate and rebalance strategy
        strategyClass = getattr(importlib.import_module("smarttrader.strategy."+tmpArray[0]), "Strategy")
        displayClass  = getattr(importlib.import_module("smarttrader.strategy.display"), displayStrategy)

        self.strategy = strategyClass(self.tickers, self.events_queue)
        strategy = Strategies(self.strategy, displayClass())

        # Use the liquidate and rebalance position sizer
        # with prespecified ticker weights
        tmpArray = positionSizer.split(".")
        rebalancingClass = getattr(importlib.import_module("smarttrader.position_sizer."+tmpArray[0]), tmpArray[1])
        self.position_sizer = rebalancingClass(ticketWeights)


        # Use an example Risk Manager
        tmpArray = riskManager.split(".")
        riskManagerClass = getattr(importlib.import_module("smarttrader.risk_manager."+tmpArray[0]), tmpArray[1])
        self.risk_manager = riskManagerClass()

        # Use the default Portfolio Handler
        tmpArray = portfolioHandler.split(".")
        portHandlerClass = getattr(importlib.import_module("smarttrader.portfolio."+tmpArray[0]), tmpArray[1])
        self.portfolio_handler = portHandlerClass(self.initial_equity, self.events_queue, self.price_handler,
          self.position_sizer, self.risk_manager)

        # Use the ExampleCompliance component
        tmpArray = complianceHandler.split(".")
        complianceClass = getattr(importlib.import_module("smarttrader.compliance."+tmpArray[0]), tmpArray[1])
        self.compliance = complianceClass(config)

        # Use a Indicator component
        self.indicator_list = list()
        self.indicator_dict = dict()
        for indicator, value in indicators.iteritems():
            print indicator, value
            tmpArray = value['indicator'].split(".")
            indicatorClass = getattr(importlib.import_module("smarttrader.indicators."+tmpArray[0]), tmpArray[1])
            instance = indicatorClass(self.tickers, self.events_queue,value)
            self.indicator_list.append(instance)
            self.indicator_dict[value['indicator']] = instance


        # Use a simulated IB Execution Handler
        tmpArray = executionHandler.split(".")
        execHandlerClass = getattr(importlib.import_module("smarttrader.execution_handler." + tmpArray[0]), tmpArray[1])
        self.execution_handler = execHandlerClass(self.events_queue, self.price_handler, self.compliance)


        # Use the default Statistics
        self.title = [title]
        tmpArray = tearsheetStatistics.split(".")
        statClass = getattr(importlib.import_module("smarttrader.statistics."+tmpArray[0]), tmpArray[1])
        self.statistics = statClass(config, self.portfolio_handler, self.title, benchmark)
Exemple #11
0
 def _create_event(self, data):
     ticker = data["name"]
     index = pd.to_datetime(data["values"]["UPDATE_TIME"])
     bid = PriceParser.parse(data["values"]["BID"])
     ask = PriceParser.parse(data["values"]["OFFER"])
     return TickEvent(ticker, index, bid, ask)
Exemple #12
0
    def __init__(self, config, strategyDict, instanceDict):

        print instanceDict
        ticketWeights = instanceDict["tickerWeights"]
        start_date = instanceDict["startDate"]
        end_date = instanceDict["endDate"]
        strategy = instanceDict["strategy"]
        benchmark = instanceDict["benchmark"]
        equity = instanceDict["equity"]

        start_date = datetime.datetime(2007, 12, 4)
        end_date = datetime.datetime(2016, 10, 12)

        self.color = 'red'
        self.qTable = LearningAgentQTable(alpha=0.5, gamma=0.3, epsilon=0.5)
        self.totalActions = 0.0
        self.totalRewards = 0.0

        # self.config = settings.from_file(config, testing)
        self.tickers = [t for t in ticketWeights.keys()]

        # Set up variables needed for backtest
        self.events_queue = queue.Queue()

        self.csv_dir = config.CSV_DATA_DIR
        self.initial_equity = PriceParser.parse(500000.00)

        # Use Yahoo Daily Price Handler
        self.price_handler = YahooDailyCsvBarPriceHandler(
            self.csv_dir,
            self.events_queue,
            self.tickers,
            start_date=start_date,
            end_date=end_date)

        # Use the monthly liquidate and rebalance strategy

        self.strategy = BuyAndHoldStrategy(self.tickers, self.events_queue)
        strategy = Strategies(self.strategy, DisplayStrategy())

        #strategyClass = getattr(importlib.import_module("qstrader.strategy.buy_and_hold"), "BuyAndHoldStrategy")
        #displayClass  = getattr(importlib.import_module("qstrader.strategy.display"), "DisplayStrategy")
        #strategy = strategyClass(self.strategy, displayClass())

        # Use the liquidate and rebalance position sizer
        # with prespecified ticker weights
        self.position_sizer = LiquidateRebalancePositionSizer(ticketWeights)
        #rebalancingClass = getattr(importlib.import_module("qstrader.position_sizer.rebalance"), "LiquidateRebalancePositionSizer")
        #strategy = rebalancingClass(ticketWeights)

        # Use an example Risk Manager
        self.risk_manager = ExampleRiskManager()
        #riskManagerClass = getattr(importlib.import_module("qstrader.risk_manager.example"), "ExampleRiskManager")
        #self.risk_manager = riskManagerClass()

        # Use the default Portfolio Handler
        self.portfolio_handler = PortfolioHandler(self.initial_equity,
                                                  self.events_queue,
                                                  self.price_handler,
                                                  self.position_sizer,
                                                  self.risk_manager)
        #portHandlerClass = getattr(importlib.import_module("qstrader.portfolio.portfolio_handler"), "PortfolioHandler")
        #strategy = portHandlerClass(self.initial_equity, self.events_queue, self.price_handler,
        #   self.position_sizer, self.risk_manager)

        # Use the ExampleCompliance component
        self.compliance = ExampleCompliance(config)
        #complianceClass = getattr(importlib.import_module("qstrader.compliance.example"), "ExampleCompliance")
        #self.compliance = complianceClass(config)

        # Use a simulated IB Execution Handler
        self.execution_handler = IBSimulatedExecutionHandler(
            self.events_queue, self.price_handler, self.compliance)
        #execHandlerClass = getattr(importlib.import_module("qstrader.execution_handler.ib_simulated"), "IBSimulatedExecutionHandler")
        #self.execution_handler = execHandlerClass(self.events_queue, self.price_handler, self.compliance)

        # Use the default Statistics
        self.title = [strategyDict.get('title')]
        self.statistics = TearsheetStatistics(config, self.portfolio_handler,
                                              self.title, benchmark)