コード例 #1
0
ファイル: test_market_data.py プロジェクト: martyw/finance
 def setUp(self) -> None:
     self.market_data = MarketData()
     self.symbol = "TEST"
     self.timestamp = datetime.now()
     self.last = 3.1415926
     self.open = 2.71828
     self.volume = 123456
コード例 #2
0
ファイル: test_market_data.py プロジェクト: martyw/finance
class TestMarketData(unittest.TestCase):
    """
    Test Curve class
    """
    def setUp(self) -> None:
        self.market_data = MarketData()
        self.symbol = "TEST"
        self.timestamp = datetime.now()
        self.last = 3.1415926
        self.open = 2.71828
        self.volume = 123456

    def test_data(self):
        """test last, timestamp"""
        last_tick = self.market_data.get_existing_tick_data(self.symbol)
        self.assertEqual(0.0, last_tick.last_price)
        self.assertEqual(0.0, last_tick.open_price)
        self.assertEqual(0, last_tick.total_volume)

        self.market_data.add_last_price(self.timestamp, self.symbol, self.last,
                                        123456)
        last_tick = self.market_data.get_existing_tick_data(self.symbol)
        self.assertEqual(self.last, last_tick.last_price)
        self.assertEqual(0.0, last_tick.open_price)
        self.assertEqual(self.timestamp, last_tick.timestamp)

        self.market_data.add_open_price(self.timestamp, self.symbol, self.open)

        open_price = self.market_data.get_open_price(self.symbol)
        self.assertEqual(open_price, self.open)
        last = self.market_data.get_last_price(self.symbol)
        self.assertEqual(last, self.last)
        time = self.market_data.get_timestamp(self.symbol)
        self.assertEqual(time, self.timestamp)
コード例 #3
0
ファイル: stg1.py プロジェクト: chenhq/BackTest
def stks_info_calculate(months, start_date='20000101', end_date='20500101'):
    stks_info = StockInfo()
    stks = stks_info.list_date_filter(end_date='20151001').get_data()
    stks_result = pd.DataFrame()

    for stk in stks['ticker']:
        all_read_datas = pd.DataFrame()
        try:
            for month in months:
                month_data = md.get_kline_1day(stk=stk, str_month=month)
                all_read_datas = pd.concat([all_read_datas, month_data])
        except Exception as e:
            pass
        if len(all_read_datas) > 0:
            all_read_datas['turnover_10day_mean'] = all_read_datas['turnover'].rolling(10).mean().shift(1)
            all_read_datas['turnover_1day'] = all_read_datas['turnover'].shift(1)

            all_read_datas['ma5'] = all_read_datas['close'].rolling(5).mean().shift(1)
            all_read_datas['ma10'] = all_read_datas['close'].rolling(10).mean().shift(1)
            all_read_datas['ma20'] = all_read_datas['close'].rolling(20).mean().shift(1)
            all_read_datas['ma60'] = all_read_datas['close'].rolling(60).mean().shift(1)

            stk_result = all_read_datas[start_date:end_date]
            stks_result = pd.concat([stks_result, stk_result])
    return stks_result
コード例 #4
0
ファイル: strategy_executor.py プロジェクト: martyw/finance
    def market_data_tick(self, prices: MarketData):
        self.current_prices = prices

        orders = self.strategy.market_data_tick(prices)
        trades = self.send_order_to_market(orders)

        close_price = prices.get_last_price(self.symbol)
        position = self.update_filled_position(trades, close_price)

        self.update_pnl(position)
        self.strategy.long_short = position.long_short
コード例 #5
0
    def testReverting(self):
        self.assertEqual(self.symbol, "AAPL")
        time_stamp = None
        for time_stamp in self.prices:
            md = MarketData()
            md.add_last_price(time=time_stamp,
                              symbol=self.symbol,
                              price=self.prices[time_stamp].last_price,
                              volume=self.volume)
            md.add_open_price(time=time_stamp,
                              symbol=self.symbol,
                              price=self.prices[time_stamp].open_price)
            orders = self.algo.market_data_tick(md)
            if orders:
                break

        self.assertEqual(time_stamp, datetime(2014, 2, 27))

        our_quote = {
            "type": "limit",
            "dealer_or_broker_id": OUR_CPTY,
            "symbol": self.symbol,
            "side": "ask",
            "quantity": self.volume,
            "price": 75.381432
        }
        self.assertEqual(orders, [our_quote])
コード例 #6
0
    def market_simulation(self):
        expire_after = datetime.timedelta(days=365)
        session = CachedSession(cache_name='cache',
                                backend='sqlite',
                                expire_after=expire_after)

        data = web.DataReader(self.ticker,
                              data_source=self.source,
                              start=self.start,
                              end=self.end,
                              session=session)
        for time, row in data.iterrows():
            market_data = MarketData()
            market_data.add_last_price(time, self.ticker, row["Close"],
                                       row["Volume"])
            market_data.add_open_price(time, self.ticker, row["Open"])
            yield market_data
コード例 #7
0
 def store_prices(self, market_data: MarketData):
     timestamp = market_data.get_timestamp(self.symbol)
     self.prices.loc[timestamp, "close"] = \
         market_data.get_last_price(self.symbol)
     self.prices.loc[timestamp, "open"] = \
         market_data.get_open_price(self.symbol)
コード例 #8
0
ファイル: run_backtest.py プロジェクト: yuzhucu/AlgoBacktest
def main():

    parser = argparse.ArgumentParser(description='Backtest an algorithm.')
    # parser.add_argument("-a", "--algo", dest="algo", required=True, help="algorithm identifier")
    parser.add_argument("-l",
                        "--log-level",
                        dest="log_level",
                        choices=['DEBUG', 'INFO', 'WARN'],
                        default="INFO",
                        help="logging level")
    parser.add_argument("-p",
                        "--show-progress",
                        dest="show_progress",
                        action='store_true',
                        help="log progress")

    global args
    args = parser.parse_args()

    level = logging.INFO
    if args.log_level == 'DEBUG':
        level = logging.DEBUG
    elif args.log_level == 'INFO':
        level = logging.INFO
    elif args.log_level == 'WARN':
        level = logging.WARN
    logging.basicConfig(level=level)

    config = Config("config.conf")

    data_provider = config.data_provider
    venue_connection = Broker(data_provider)

    orderbook_persist = BacktestOrderbookPersist()
    order_book = OrderBook(venue_connection, orderbook_persist)
    market_data = MarketData(venue_connection)

    containers = []
    #    containers.append(Container(Algo(25, 10, 10), 10000, order_book, market_data))
    containers.append(
        Container(NakedBigShadow(7, 10, 50, MarketDataPeriod.HOUR_4), 10000,
                  order_book, market_data))
    containers.append(
        Container(NakedBigShadow(7, 10, 50, MarketDataPeriod.DAY), 10000,
                  order_book, market_data))
    containers.append(
        Container(NakedBigShadow(7, 10, 60, MarketDataPeriod.DAY), 10000,
                  order_book, market_data))
    containers.append(
        Container(NakedBigShadow(7, 10, 70, MarketDataPeriod.DAY), 10000,
                  order_book, market_data))
    containers.append(
        Container(NakedBigShadow(7, 10, 80, MarketDataPeriod.DAY), 10000,
                  order_book, market_data))
    containers.append(
        Container(NakedBigShadow(7, 10, 90, MarketDataPeriod.DAY), 10000,
                  order_book, market_data))
    containers.append(
        Container(NakedBigShadow(7, 10, 100, MarketDataPeriod.DAY), 10000,
                  order_book, market_data))
    # containers.append(Container(Algo(15, 50, 100), 100000, order_book, market_data))

    if args.show_progress is True:
        progress_bar = ProgressBar(data_provider.expected_result_count,
                                   label='Backtest')
        data_provider.set_progress_callback(lambda x: progress_bar.set(x))
        venue_connection.start()
        progress_bar.complete()
    else:
        venue_connection.start()

    for container in containers:
        display_results(container)