Package: qfinuwa
QFIN's Algorithmic Backtester (QFAB)GitHub PageSetupTo install on your system, use pip:pip install qfinuwaAPI ClassTo pull market data ensure you have a text file with the API key and callAPI.fetch_stocks:fromqfinuwaimportAPIpath_to_API='API_key.txt'download_folder='./data'API.fetch_stocks(['AAPL','GOOG','TSLA'],path_to_API,download_folder)Indicator ClassMulti-IndicatorsA multi-indicator takes in a single signal (price of an arbitary stock) and outputs a transformation of that stock.It is calledMultiIndicatorbecause the indicator will have multiple values (one for each stock)# ExampleclassCustomIndicators(Indicators):@Indicators.MultiIndicatordefbollinger_bands(self,stock:pd.DataFrame):BOLLINGER_WIDTH=2WINDOW_SIZE=100mid_price=(stock['high']+stock['low'])/2rolling_mid=mid_price.rolling(WINDOW_SIZE).mean()rolling_std=mid_price.rolling(WINDOW_SIZE).std()return{"upper_bollinger":rolling_mid+BOLLINGER_WIDTH*rolling_std,"lower_bollinger":rolling_mid-BOLLINGER_WIDTH*rolling_std}Single-IndicatorsSimilar toMultiIndicator,SingleIndicatoris implemented as a function that takes in stock data and returns an indicator or indicators.It is calledSingleIndicatorbecause there is only a single signal.# ExampleclassCustomIndicators(Indicators):@Indicators.SingleIndicatordefetf(self,stock:dict):apple=0.2tsla=0.5goog=0.3return{'etf':apple*stock['AAPL']+tsla*stock['TSLA']+goog*stock['GOOG']}Manually TestingYou can manually test you indicators as follows:stock_a=pd.from_csv('stockA.csv')stock_b=pd.from_csv('stockA.csv')# multi-indicator for stockA (returns dict of dict of pd.Series)output_a=CustomIndicators.bollinger(stockA)# multi-indicator for stockB (returns dict of dict of pd.Series)output_b=CustomIndicators.bollinger(stockA)# single-indicator for stockA + stockB (returns dict of pd.Series)output=CustomIndicators.etf({'stockA':stock_a,'stockB':stock_b})Hyper-parametersEach function you implement can be thought of as a hyperparameter "group" that bundles the indicator it returns (the keys to the dictionary the indicator function returns).The backtester can change hyperparameters for you, but to do so you need to give each one a name, in the form ofkwargs.Thekwargsmust include a default value which will be used if you do not specify a value.classCustomIndicators(Indicators):@Indicators.MultiIndicatordefbollinger_bands(self,stock:pd.DataFrame,BOLLINGER_WIDTH=2,WINDOW_SIZE=100):mid_price=(stock['high']+stock['low'])/2rolling_mid=mid_price.rolling(WINDOW_SIZE).mean()rolling_std=mid_price.rolling(WINDOW_SIZE).std()return{"upper_bollinger":rolling_mid+BOLLINGER_WIDTH*rolling_std,"lower_bollinger":rolling_mid-BOLLINGER_WIDTH*rolling_std}@Indicators.SingleIndicatordefetf(self,stock:dict,apple=0.2,tsla=0.5,goog=0.3):return{'etf':apple*stock['AAPL']+tsla*stock['TSLA']+goog*stock['GOOG']}Strategy ClassTo define your strategy extendqfin.Strategyto inherit its functionalities. Implement your ownon_datafunction.Youron_datafunction will be expected to take 4 positional arguments.self: reference to this objectprices: a dictionary of numpy arrays of historical pricesportfolio: object that manages positionsSimilar toqfin.Indicators, you can define hyperparameters for your model in__init__.# Example StrategyclassBasicBollinger(Strategy):def__init__(self,quantity=5):self.quantity=quantityself.n_failed_orders=0defon_data(self,prices,indicators,portfolio):# If current price is below lower Bollinger Band, enter a long positionforstockinportfolio.stocks:if(prices['close'][stock][-1]<indicators['lower_bollinger'][stock][-1]):order_success=portfolio.order(stock,quantity=self.quantity)ifnotorder_success:self.n_failed_orders+=1# If current price is above upper Bollinger Band, enter a short positionif(prices['close'][stock][-1]>indicators['upper_bollinger'][stock][-1]):order_success=portfolio.order(stock,quantity=-self.quantity)ifnotorder_success:self.n_failed_orders+=1defon_finish(self):# Added to results object - access using result.on_finishreturnself.n_failed_ordersAdditionally, you can specify a functionon_finishthat will run on the completion of a run, if you want to save your own data. Whatever this function returns will can be accessed in the results (seeSingleRunResults.on_finish).Backtester ClassTheBacktesterclass asks for a custom strategy, custom indicators and data from the user. Once created, it can run multiple backtests without having to recalculate the indicators - when used in a Notebook environment the backtester object can persist and incrementally updated with new values.Creating a BacktesterSeeqfinuwa.Backtesterdocstrings for specifics.fromqfinuwaimportBacktesterbacktester=Backtester(CustomStrategy,CustomIndicators,data=r'\data',days=90,delta_limits=1000,fee=0.01)Updating Indicator ParametersUpdate Parametersbacktester.indicators.update_params(dict_of_updates)Get Current Parametersbacktester.indicators.paramsGet Defaultsbacktester.indicators.defaultsUpdating Classbacktester.indicators=NewIndicatorClassUpdating Strategy ParametersUpdate Parametersbacktester.strategy.update_params(dict_of_updates)Get Current Parametersbacktester.strategy.paramsGet Defaultsbacktester.strategy.defaultsUpdating  Classbacktester.strategy=NewStrategyClassRunning a BacktesterTime Complexity AnalysisMIT LicenseCopyright (c) 2022 Isaac Bergl, QFIN UWAPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.