Esempio n. 1
0
def create_a_loading_plan(rootFolderName):
    loadingPlan = LoadingPlan(barSize='1 min',
                              goBack='1 day',
                              rootFolderName=rootFolderName)
    loadingPlan.add(
        Plan(security=symbol('CASH,EUR,USD'), fileName='testData.csv'))
    loadingPlan.add(
        Plan(security=symbol('CASH,USD,JPY'), fileName='testData.csv'))
    return loadingPlan
Esempio n. 2
0
def _fromTDInstrumentToIBridgePySecurity(instrument, _log=None):
    secType = str(instrument['assetType'])
    if secType == 'CASH_EQUIVALENT':
        # TD has a position called CASH_EQUIVALENT, which means TD save pure case into a fund to gain high interest
        # The symbol of it is MMDA1
        security = superSymbol(secType='CASH_EQUIVALENT',
                               symbol=str(instrument['symbol']))
    elif secType == 'OPTION':
        fullName = str(instrument['symbol'])
        str_expiry = fullName.split('_')[1]
        month = str_expiry[:2]
        date = str_expiry[2:4]
        year = str_expiry[4:6]
        security = superSymbol(secType='OPT',
                               symbol=fullName,
                               right=str(instrument['putCall'])[0],
                               expiry='20' + year + month + date,
                               strike=float(str_expiry[7:]))
    elif secType == 'EQUITY':
        security = symbol(str(instrument['symbol']))
    else:
        if _log:
            _log.info(__name__ +
                      '::reqPositionsWrapper: cannot handle instrument=%s' %
                      (instrument, ))
        security = None
    return security
Esempio n. 3
0
 def reqPositionsWrapper(self):
     ans = self._robinhoodClient.get_all_positions()
     # ans = [{'symbol':'SPY', 'quantity':100, 'average_buy_price':99.9}]
     for position in ans:
         security = symbol(str(position['symbol']))
         contract = from_security_to_contract(security)
         self.position(self._accountCode, contract,
                       int(float(position['quantity'])),
                       float(position['average_buy_price']))
     self.simulatePositionEnd()
Esempio n. 4
0
    def fromRBtoIBOpenOrder(rbOrder, idConverter, accountCode):
        # IBCpp.Order().orderId must be an integer so that an integer orderId has to be created
        originalTdOrderId = str(rbOrder['id'])
        int_orderId = idConverter.fromBrokerToIB(originalTdOrderId)

        security = symbol(str(rbOrder['symbol']))
        contract = from_security_to_contract(security)
        orderStatus = OrderStatusConverter().fromRBtoIB(str(rbOrder['state']))
        quantity = int(float(rbOrder['quantity']))

        orderState = IBCpp.OrderState()
        orderState.status = orderStatus

        ibOrder = IBCpp.Order()
        ibOrder.orderId = int_orderId
        ibOrder.account = accountCode
        ibOrder.action = OrderActionConverter().fromRBtoIB(
            str(rbOrder['side']))  # _robinhoodClient side : buy, sell
        ibOrder.totalQuantity = quantity
        ibOrder.orderType = OrderTypeConverter().fromRBtoIB(
            str(rbOrder['type']).lower(),
            str(rbOrder['trigger']).lower())
        ibOrder.tif = OrderTifConverter().fromRBtoIB(
            str(rbOrder['time_in_force']))
        if ibOrder.orderType == OrderType.LMT:
            ibOrder.lmtPrice = float(str(rbOrder['price']))
        elif ibOrder.orderType == OrderType.STP:
            ibOrder.auxPrice = float(str(rbOrder['stop_price']))
        elif ibOrder.orderType == OrderType.STP_LMT:
            ibOrder.lmtPrice = float(str(rbOrder['price']))
            ibOrder.auxPrice = float(str(rbOrder['stop_price']))
        elif ibOrder.orderType == OrderType.MKT:
            pass
        else:
            print(__name__ +
                  '::reqOneOrderWrapper: EXIT, cannot handle orderType=%s' %
                  (ibOrder.orderType, ))
            exit()
        return int_orderId, contract, ibOrder, orderState, security
Esempio n. 5
0
####
# The backtesting time period is defined by two variables: endTime and startTime, default timezone = 'US/Eastern'
####

# As a demo, endTime is Dec 24th 2020 because the ingested historical data ends on that date.
# IBridgePy automatically sets endTime.second to 0 because the default mode of IBridgePy backtester is designed to
# backtest strategies minutely and the second must be zero.
endTime = dt.datetime(2020, 12, 24)

# As a demo, startTime is 50 days ago from the current time.
startTime = endTime - dt.timedelta(days=50)

# "histIngestionPlan" is a reserved word in IBridgePy to store the historical data ingestion plan that describes what historical data
# are needed during backtesting and IBridgePy backtester will fetch these data before backtesting to speed up the whole backtesting process.
# "histIngestionPlan" is not required for backtesting but it will make backtest much faster.
# "histIngestionPlan" is an instance of HistIngestionPlan.
histIngestionPlan = HistIngestionPlan()

# dataSourceName='simulatedByDailyBars' means to simulate minute bar data by daily bar data when it is needed.
# The default is to use "close" price of the daily bar to simulate minute price. It can be configured in settings.py --> PROJECT --> useColumnNameWhenSimulatedByDailyBar
histIngestionPlan.add(
    Plan(security=symbol('SPY'),
         barSize='1 min',
         dataSourceName='simulatedByDailyBars')
)  # "histIngestionPlan.add" is used to add more Ingestion Plans
histIngestionPlan.add(
    Plan(security=symbol('SPY'), barSize='1 day', fileName='SPY_1day_55D.csv')
)  # "histIngestionPlan.add" is used to add more Ingestion Plans

test_me(fileName, globals())
Esempio n. 6
0
# Backtest with hist ingestion https://youtu.be/XnpxAVU4ogY
# Backtest with hist from local files https://youtu.be/UR_7_F8wPL0
# Speed up backtest by designating spot times https://youtu.be/bVE59nZ02ig
# Convert hist data format https://youtu.be/hYL6SYgy7wE
fileName = 'demo_buy_low_sell_high.py'

accountCode = 'dummyAccountCode'  # IBridgePy needs a dummyAccountCode to simulate transactions when dataProviderName = 'LOCAL_FILE'
dataProviderName = 'LOCAL_FILE'  # RANDOM, IB, LOCAL_FILE, TD, ROBINHOOD, IBRIDGEPY

# "histIngestionPlan" is a reserved word in IBridgePy to store the historical data ingestion plan that describes what historical data
# are needed during backtesting and IBridgePy backtester will fetch these data before backtesting to speed up the whole backtesting process.
# "histIngestionPlan" is not required for backtesting but it will make backtest much faster.
# "histIngestionPlan" is an instance of HistIngestionPlan.
histIngestionPlan = HistIngestionPlan()
histIngestionPlan.add(
    Plan(security=symbol('SPY'),
         barSize='1 min',
         fileName='STK,SPY,USD_1 min_40 D.csv')
)  # "histIngestionPlan.add" is used to add more Ingestion Plans
histIngestionPlan.add(
    Plan(security=symbol('SPY'),
         barSize='1 day',
         fileName='STK,SPY,USD_1 day_55 D.csv')
)  # "histIngestionPlan.add" is used to add more Ingestion Plans

# In CUSTOM mode, user can specify each spot time to backtest with any data provider.
# customSpotTimeList is an IBridgePy reserved key word. Its type is List.
# User can append each spot time into customSpotTimeList to backtest at these spot times.
timeGeneratorType = 'CUSTOM'
customSpotTimeList = []
import pandas as pd
# Backtest with hist ingestion https://youtu.be/XnpxAVU4ogY
# Backtest with hist from local files https://youtu.be/UR_7_F8wPL0
# Speed up backtest by designating spot times https://youtu.be/bVE59nZ02ig
# Convert hist data format https://youtu.be/hYL6SYgy7wE
# Backtest using IBridgePy data center https://youtu.be/0FPgtmUpTI0
fileName = 'demo_buy_low_sell_high.py'

accountCode = 'dummyAccountCode'  # IBridgePy needs a dummyAccountCode to simulate transactions when dataProviderName = 'LOCAL_FILE'
dataProviderName = 'LOCAL_FILE'  # RANDOM, IB, LOCAL_FILE, TD, ROBINHOOD, IBRIDGEPY

# "histIngestionPlan" is a reserved word in IBridgePy to store the historical data ingestion plan that describes what historical data
# are needed during backtesting and IBridgePy backtester will fetch these data before backtesting to speed up the whole backtesting process.
# "histIngestionPlan" is not required for backtesting but it will make backtest much faster.
# "histIngestionPlan" is an instance of HistIngestionPlan.
histIngestionPlan = HistIngestionPlan()
histIngestionPlan.add(Plan(security=symbol('SPY'), barSize='1 min', fileName='SPY_1min_40D.csv'))  # "histIngestionPlan.add" is used to add more Ingestion Plans
histIngestionPlan.add(Plan(security=symbol('SPY'), barSize='1 day', fileName='SPY_1day_55D.csv'))  # "histIngestionPlan.add" is used to add more Ingestion Plans

# In CUSTOM mode, user can specify each spot time to backtest with any data provider.
# customSpotTimeList is an IBridgePy reserved key word. Its type is List.
# User can append each spot time into customSpotTimeList to backtest at these spot times.
timeGeneratorType = 'CUSTOM'
customSpotTimeList = []
# The goal is to backtest from 2020-10-30 to 2020-12-24 and only allow the datetime of 15:59:00 Eastern go through the to-be-tested strategy
# because "demo_close_price_reversion.py" only makes trading decisions at 15:59:00 Eastern on every trading day.
# pd.date_range is used to create a list of dates that have hour=0 and minute=0.
dateRange = pd.date_range(dt.datetime(2020, 10, 30), dt.datetime(2020, 12, 24), freq='1D', tz=pytz.timezone('US/Eastern'))
for aDate in dateRange:
    a = aDate.replace(hour=15, minute=59)  # datetime(2020, 10, 30, 0, 0) --> datetime(2020, 10, 30, 15, 59)
    customSpotTimeList.append(a)
Esempio n. 8
0
fileName = 'demo_buy_low_sell_high.py'

accountCode = 'DU1868499'  # IB accountCode is needed to retrieve historical data from IB server.
dataProviderName = 'IB'  # RANDOM, IB, LOCAL_FILE, TD, ROBINHOOD, IBRIDGEPY

####
# The backtesting time period is defined by two variables: endTime and startTime, default timezone = 'US/Eastern'
####

# As a demo, endTime is the current time.
# IBridgePy automatically sets endTime.second to 0 because the default mode of IBridgePy backtester is designed to
# backtest strategies minutely and the second must be zero.
endTime = dt.datetime.now()

# As a demo, startTime is 50 days ago from the current time.
startTime = endTime - dt.timedelta(days=50)

# "histIngestionPlan" is a reserved word in IBridgePy to store the historical data ingestion plan that describes what historical data
# are needed during backtesting and IBridgePy backtester will fetch these data before backtesting to speed up the whole backtesting process.
# "histIngestionPlan" is not required for backtesting but it will make backtest much faster.
# "histIngestionPlan" is an instance of HistIngestionPlan.
histIngestionPlan = HistIngestionPlan()
histIngestionPlan.add(
    Plan(security=symbol('SPY'), barSize='1 min', goBack='40 D')
)  # "histIngestionPlan.add" is used to add more Ingestion Plans
histIngestionPlan.add(
    Plan(security=symbol('SPY'), barSize='1 day', goBack='55 D')
)  # "histIngestionPlan.add" is used to add more Ingestion Plans

test_me(fileName, globals())
Esempio n. 9
0
####
# The backtesting time period is defined by two variables: endTime and startTime, default timezone = 'US/Eastern'
####

# As a demo, endTime is Dec 24th 2020 because the ingested historical data ends on that date.
# IBridgePy automatically sets endTime.second to 0 because the default mode of IBridgePy backtester is designed to
# backtest strategies minutely and the second must be zero.
endTime = dt.datetime(2020, 12, 24)

# As a demo, startTime is 50 days ago from the current time.
startTime = endTime - dt.timedelta(days=50)

# "histIngestionPlan" is a reserved word in IBridgePy to store the historical data ingestion plan that describes what historical data
# are needed during backtesting and IBridgePy backtester will fetch these data before backtesting to speed up the whole backtesting process.
# "histIngestionPlan" is not required for backtesting but it will make backtest much faster.
# "histIngestionPlan" is an instance of HistIngestionPlan.
histIngestionPlan = HistIngestionPlan()

# Default folder to load hist files is ibridgepyRoot/Input
# User can designate the loading folder by "histIngestionPlan = HistIngestionPlan(defaultFolderName=xxx)"
# "histIngestionPlan.add" is used to add more Ingestion Plans
# The full path of the file is ibridgepyRoot/Input/SPY_1min_40D.csv
histIngestionPlan.add(
    Plan(security=symbol('SPY'), barSize='1 min', fileName='SPY_1min_40D.csv'))
histIngestionPlan.add(
    Plan(security=symbol('SPY'), barSize='1 day',
         fileName='SPY_1day_55D.csv'))  # Add more plans as needed.

test_me(fileName, globals())