Coder Social home page Coder Social logo

auquan / auquantoolbox Goto Github PK

View Code? Open in Web Editor NEW
109.0 6.0 43.0 17.71 MB

Backtesting toolbox for trading strategies

Home Page: https://toolbox.auquan.com/

License: Apache License 2.0

Python 100.00%
toolbox quant trading-strategies backtesting-trading-strategies backtesting-frameworks time-series-analysis time-series auquan-toolbox

auquantoolbox's People

Contributors

chandinijain avatar gandharv42 avatar kanavarora avatar sagarchoudhary96 avatar shashank-auquan avatar shubham1217 avatar teamauquan avatar vaibhavnaagar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

auquantoolbox's Issues

Question about the error when run the startTrading() function

I tried to test the new strategy and when I run the code of results = tradingSystem.startTrading(), It prompts out the error message.

I am not going to post the full code here because it is quite long. I would like to know which direction should I go for solving the problem. If there is really a need for the full code, please let me know. Thank you for your help.

The following is the error message:

Processing data for stock: AAPL
Processing data for stock: MSFT
20% done...
40% done...
60% done...
80% done...
Logging all the available market metrics in tensorboard
Logging all the available instrument metrics in tensorboard
2017-01-02 00:00:00
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-c0f85326750e> in <module>()
      2 tsParams = MyTradingParams(tf)
      3 tradingSystem = TradingSystem(tsParams)
----> 4 results = tradingSystem.startTrading()

6 frames
/root/.local/lib/python3.7/site-packages/backtester/trading_system.py in startTrading(self, onlyAnalyze, shouldPlot, makeInstrumentCsvs, createResultDict, logFileName)
    142                 except StopIteration:
    143                     isClose = True
--> 144                 self.updateFeaturesAndExecute(currentTimeUpdate, isClose, onlyAnalyze, global_step=global_step)
    145 
    146             if not onlyAnalyze and self.portfolioValue < 0:

/root/.local/lib/python3.7/site-packages/backtester/trading_system.py in updateFeaturesAndExecute(self, timeOfUpdate, isClose, onlyAnalyze, global_step)
     83         print(timeOfUpdate)
     84         self.totalUpdates = self.totalUpdates + 1
---> 85         self.updateFeatures(timeOfUpdate)
     86         if not onlyAnalyze:
     87             start = time.time()

/root/.local/lib/python3.7/site-packages/backtester/trading_system.py in updateFeatures(self, timeOfUpdate)
    109         # if self.totalUpdates > 0:
    110         # Dont call for the first time
--> 111         self.instrumentManager.updateFeatures(timeOfUpdate)
    112         end = time.time()
    113         diffms = (end - start) * 1000

/root/.local/lib/python3.7/site-packages/backtester/instruments_manager.py in updateFeatures(self, timeOfUpdate)
    237 
    238     def updateFeatures(self, timeOfUpdate):
--> 239         self.updateInstrumentFeatures(timeOfUpdate)
    240 
    241         currentMarketFeatures = {}

/root/.local/lib/python3.7/site-packages/backtester/instruments_manager.py in updateInstrumentFeatures(self, timeOfUpdate)
    229                                                          featureParams=featureParams,
    230                                                          featureKey=featureKey,
--> 231                                                          instrumentManager=self)
    232             self.__lookbackInstrumentFeatures.addFeatureValueForAllInstruments(timeOfUpdate, featureKey, featureVal)
    233             end = time.time()

/root/.local/lib/python3.7/site-packages/backtester/features/profitloss_feature.py in computeForInstrument(cls, updateNum, time, featureParams, featureKey, instrumentManager)
     22         currentPrice = priceDict.iloc[-1]
     23         changeInPosition = currentPosition - previousPosition
---> 24         tradePrice = pd.Series([instrumentManager.getInstrument(x).getLastTradePrice() for x in priceDict.columns], index=priceDict.columns)
     25         tradeLoss = pd.Series([instrumentManager.getInstrument(x).getLastTradeLoss() for x in priceDict.columns], index=priceDict.columns)
     26         pnl = (previousPosition * (currentPrice - previousPrice)) + (changeInPosition * (currentPrice - tradePrice)) - fees - tradeLoss

/root/.local/lib/python3.7/site-packages/backtester/features/profitloss_feature.py in <listcomp>(.0)
     22         currentPrice = priceDict.iloc[-1]
     23         changeInPosition = currentPosition - previousPosition
---> 24         tradePrice = pd.Series([instrumentManager.getInstrument(x).getLastTradePrice() for x in priceDict.columns], index=priceDict.columns)
     25         tradeLoss = pd.Series([instrumentManager.getInstrument(x).getLastTradeLoss() for x in priceDict.columns], index=priceDict.columns)
     26         pnl = (previousPosition * (currentPrice - previousPrice)) + (changeInPosition * (currentPrice - tradePrice)) - fees - tradeLoss

AttributeError: 'NoneType' object has no attribute 'getLastTradePrice

Yahoo data source seems to not be working - any idea how to rectify this?

Any idea how to rectify the below?

Processing data for stock: SCT.L
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-41-c0f85326750e> in <module>
      1 tf = MyTradingFunctions()
      2 tsParams = MyTradingParams(tf)
----> 3 tradingSystem = TradingSystem(tsParams)
      4 results = tradingSystem.startTrading()

~\Anaconda3\envs\Portfolio 2\lib\site-packages\backtester\trading_system.py in __init__(self, tsParams)
     33         self.executionSystem = None
     34         self.orderPlacer = None
---> 35         self.dataParser = self.tsParams.getDataParser()
     36         self.executionSystem = self.tsParams.getExecutionSystem()
     37         self.orderPlacer = self.tsParams.getOrderPlacer()

<ipython-input-37-8cd4a1c6cc78> in getDataParser(self)
     14         '''
     15         instrumentIds = self.__tradingFunctions.getSymbolsToTrade()
---> 16         return YahooStockDataSource(
     17             cachedFolderName = 'historicalData/',
     18             dataSetId = self.__dataSetId,

~\Anaconda3\envs\Portfolio 2\lib\site-packages\backtester\dataSource\yahoo_data_source.py in __init__(self, cachedFolderName, dataSetId, instrumentIds, startDateStr, endDateStr, event, adjustPrice, downloadId, liveUpdates, pad)
    117         self.event = event
    118         if liveUpdates:
--> 119             self._allTimes, self._groupedInstrumentUpdates = self.getGroupedInstrumentUpdates()
    120             self.processGroupedInstrumentUpdates()
    121             self._bookDataFeatureKeys = self.__bookDataByFeature.keys()

~\Anaconda3\envs\Portfolio 2\lib\site-packages\backtester\dataSource\data_source.py in getGroupedInstrumentUpdates(self)
     65             print('Processing data for stock: %s' % (instrumentId))
     66             fileName = self.getFileName(instrumentId)
---> 67             if not self.downloadAndAdjustData(instrumentId, fileName):
     68                 continue
     69             with open(fileName) as f:

~\Anaconda3\envs\Portfolio 2\lib\site-packages\backtester\dataSource\yahoo_data_source.py in downloadAndAdjustData(self, instrumentId, fileName)
    131     def downloadAndAdjustData(self, instrumentId, fileName):
    132         if not os.path.isfile(fileName):
--> 133             if not downloadFileFromYahoo(self._startDate, self._endDate, instrumentId, fileName):
    134                 logError('Skipping %s:' % (instrumentId))
    135                 return False

~\Anaconda3\envs\Portfolio 2\lib\site-packages\backtester\dataSource\data_source_utils.py in downloadFileFromYahoo(startDate, endDate, instrumentId, fileName, event)
     28 def downloadFileFromYahoo(startDate, endDate, instrumentId, fileName, event='history'):
     29     logInfo('Downloading %s' % fileName)
---> 30     cookie, crumb = getCookieForYahoo(instrumentId)
     31     start = int(mktime(startDate.timetuple()))
     32     end = int(mktime(endDate.timetuple()))

~\Anaconda3\envs\Portfolio 2\lib\site-packages\backtester\dataSource\data_source_utils.py in getCookieForYahoo(instrumentId)
     15     req = requests.get(url)
     16     txt = req.content
---> 17     cookie = req.cookies['B']
     18     pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}')
     19 

~\Anaconda3\envs\Portfolio 2\lib\site-packages\requests\cookies.py in __getitem__(self, name)
    326         .. warning:: operation is O(n), not O(1).
    327         """
--> 328         return self._find_no_duplicates(name)
    329 
    330     def __setitem__(self, name, value):

~\Anaconda3\envs\Portfolio 2\lib\site-packages\requests\cookies.py in _find_no_duplicates(self, name, domain, path)
    397         if toReturn:
    398             return toReturn
--> 399         raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
    400 
    401     def __getstate__(self):

KeyError: "name='B', domain=None, path=None"

Small outdated code preventing backtesting runs

  1. pip install auquan_toolkit fails because setup.py mentions sklearn instead of the more recent name scikit-learn. There is a workaround by setting environment variable SKLEARN_ALLOW_DEPRECATED_SKLEARN_PACKAGE_INSTALL=True but may be better to set the new name into setup.py
  2. reference to outdated pandas call to Dataframe.iteritems() which has been deprecated and removed in favor of Dataframe.items() in backtester/executionSystem/simple_execution_system.py

I pip installed locally with -e and made these changes, and it makes TradingSystem.startTrading() run without error.

KeyError: "name='B', domain=None, path=None"

Hi, trying to run this lab from the course.
https://github.com/GoogleCloudPlatform/training-data-analyst/blob/master/courses/ai-for-finance/solution/momentum_backtest_losing_money.ipynb

And I get this error:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/tmp/ipykernel_21116/1996377170.py in <module>
      1 tf = MyTradingFunctions()
      2 tsParams = MyTradingParams(tf)
----> 3 tradingSystem = TradingSystem(tsParams)
      4 results = tradingSystem.startTrading()

~/.local/lib/python3.7/site-packages/backtester/trading_system.py in __init__(self, tsParams)
     33         self.executionSystem = None
     34         self.orderPlacer = None
---> 35         self.dataParser = self.tsParams.getDataParser()
     36         self.executionSystem = self.tsParams.getExecutionSystem()
     37         self.orderPlacer = self.tsParams.getOrderPlacer()

/tmp/ipykernel_21116/1453009385.py in getDataParser(self)
     19             instrumentIds = instrumentIds,
     20             startDateStr = self.__startDate,
---> 21             endDateStr = self.__endDate,
     22         )
     23 

~/.local/lib/python3.7/site-packages/backtester/dataSource/yahoo_data_source.py in __init__(self, cachedFolderName, dataSetId, instrumentIds, startDateStr, endDateStr, event, adjustPrice, downloadId, liveUpdates, pad)
    117         self.event = event
    118         if liveUpdates:
--> 119             self._allTimes, self._groupedInstrumentUpdates = self.getGroupedInstrumentUpdates()
    120             self.processGroupedInstrumentUpdates()
    121             self._bookDataFeatureKeys = self.__bookDataByFeature.keys()

~/.local/lib/python3.7/site-packages/backtester/dataSource/data_source.py in getGroupedInstrumentUpdates(self)
     65             print('Processing data for stock: %s' % (instrumentId))
     66             fileName = self.getFileName(instrumentId)
---> 67             if not self.downloadAndAdjustData(instrumentId, fileName):
     68                 continue
     69             with open(fileName) as f:

~/.local/lib/python3.7/site-packages/backtester/dataSource/yahoo_data_source.py in downloadAndAdjustData(self, instrumentId, fileName)
    131     def downloadAndAdjustData(self, instrumentId, fileName):
    132         if not os.path.isfile(fileName):
--> 133             if not downloadFileFromYahoo(self._startDate, self._endDate, instrumentId, fileName):
    134                 logError('Skipping %s:' % (instrumentId))
    135                 return False

~/.local/lib/python3.7/site-packages/backtester/dataSource/data_source_utils.py in downloadFileFromYahoo(startDate, endDate, instrumentId, fileName, event)
     28 def downloadFileFromYahoo(startDate, endDate, instrumentId, fileName, event='history'):
     29     logInfo('Downloading %s' % fileName)
---> 30     cookie, crumb = getCookieForYahoo(instrumentId)
     31     start = int(mktime(startDate.timetuple()))
     32     end = int(mktime(endDate.timetuple()))

~/.local/lib/python3.7/site-packages/backtester/dataSource/data_source_utils.py in getCookieForYahoo(instrumentId)
     15     req = requests.get(url)
     16     txt = req.content
---> 17     cookie = req.cookies['B']
     18     pattern = re.compile('.*"CrumbStore":\{"crumb":"(?P<crumb>[^"]+)"\}')
     19 

/opt/conda/lib/python3.7/site-packages/requests/cookies.py in __getitem__(self, name)
    326         .. warning:: operation is O(n), not O(1).
    327         """
--> 328         return self._find_no_duplicates(name)
    329 
    330     def __setitem__(self, name, value):

/opt/conda/lib/python3.7/site-packages/requests/cookies.py in _find_no_duplicates(self, name, domain, path)
    397         if toReturn:
    398             return toReturn
--> 399         raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
    400 
    401     def __getstate__(self):

KeyError: "name='B', domain=None, path=None"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.