Package: dxlib
dxlib - a Quantitative Analysis Frameworkdxliboffers a rich set of tools tailored for traders, researchers, and quantitative analysts, covering everything from basic statistical methods to comprehensive trading simulations.
It emphasizes a unified interface for fetching and analyzing data, ensuring consistent and predictable outputs irrespective of data sources.InstallationUse the package managerpipto install dxlib.pipinstalldxlibModules OverviewInterfacesEncapsulates a series of financial data api, allowing static data requests, data streaming and websocket creation.
Currently available APIs endpoints are:Alpaca MarketsAlpha VantageYahoo! FinanceUnified data-fetching methods, ensuring consistent data structures.
To use the individual API endpoints, simply load the respective API module:fromdxlib.interfaces.apiimportAlpacaMarketsAPIapi=AlpacaMarketsAPI("<api_key>","<api_secret>")# If a local cache/ directory is used, no API key is neededtop_symbols=api.get_symbols(n=100)historical_bars=api.get_historical_bars(top_symbols["symbol"].values)print(top_symbols)print(historical_bars)symbol    trade_count        volume
0    MCOM          86713     146651863
1    EBET          33428      83560053
...
98   FNGD           9886       5580585
99   OPEN          13278       5528415Fields                  Close                   ...       VWAP      Volume            
Ticker                  AAL      AAPL   ABCM    ...       XPEV         XLF        XPEV
Time                                            ...                                   
2022-08-29 04:00:00     13.51  160.43  14.99    ... 
...
2023-08-25 04:00:00     NaN      NaN     NaN    ...  17.149326  37520857.0  19358445.0Simulation ModuleHarnessdxlibto simulate trading strategies:importdxlibasdxfromdxlibimportStrategyManager,Portfoliofromdxlib.interfaces.apiimportYFinanceAPIdata=YFinanceAPI().get_historical_bars(["AAPL","MSFT","GOOGL","AMZN"],start="2022-01-01",end="2022-12-31")portfolio=Portfolio().add_cash(1e4)my_strategy=StrategyManager(dx.strategies.RsiStrategy())my_strategy.register(portfolio)historical_signals=my_strategy.run(data["Close"])Highlight: Built-in ServerThe simulation manager features an embedded server that serves requests related to the simulation process. This allows for real-time monitoring and potential interaction with running simulations. Check out theServerclass in thesimulationmodule for more details.Start the server withsimulation_manager.start_server(). Check the logs for server activity and exception handling.importdxlibasdxfromdxlib.interfaces.serversimportSimulationManagerdata=dx.api.YFinanceAPI().get_historical_bars(["AAPL","MSFT","GOOGL","AMZN"],start="2022-01-01",end="2022-12-31")my_strategy=dx.strategies.RsiStrategy()logger=dx.info_logger("simulation_manager")my_manager=SimulationManager(my_strategy,use_server=True,port=5000,logger=logger)my_manager.start()try:whilemy_manager.server.is_alive():withmy_manager.server.exceptionsasexceptions:ifexceptions:logger.exception(exceptions)exceptKeyboardInterrupt:passfinally:my_manager.stop_server()$pythonservers.py2023-08-1504:11:37,417-INFO-Serverstartingonport5000(http_server.py:308)2023-08-1504:11:37,422-INFO-Serverstartedonport5000.PressCtrl+Ctostop(http_server.py:292)127.0.0.1--[15/Aug/202304:12:01]"GET / HTTP/1.1"200-127.0.0.1--[15/Aug/202304:12:09]"GET / HTTP/1.1"200-127.0.0.1--[15/Aug/202304:13:35]"GET / HTTP/1.1"200-127.0.0.1--[15/Aug/202304:14:18]"POST /add_cash HTTP/1.1"200-127.0.0.1--[15/Aug/202304:15:38]"GET /portfolio HTTP/1.1"200-Trading Modulefromdxlib.strategiesimportRandomForestStrategyasrfsfromdxlib.dataimportDataLoaderfeatures,labels=DataLoader(data["Close"])x_train,y_train,x_test,y_test=train_test_split(features,labels,0.5)clf=rfs().fit(x_train,y_train)y_pred=rfs.predict(x_test)print(f"Returns:{sum(y_pred-y_test}")HistoryClassDescription:TheHistoryclass is a robust stock market data handler, offering a suite of utilities and technical indicators for market analysis.Data Management: Seamlessly manage your stock price data. Easily add new symbols or rows of data.Timeseries Indicators: Common indicators and timeseries methods:Moving AveragesExponential Moving AveragesLogarithmic ChangesVolatility MeasurementsTechnical Indicators: Enjoy a rich suite of built-in technical indicators, such as (Convert your History to JSON format with a single call to theto_jsonmethod):RSISharpe RatioBollinger BandsBetaDrawdown ComputationsExtendability: Extend theHistoryclass with more technical indicators or data analysis tools as per your requirements.Here's a quick start guide to using theHistoryclass:fromdxlibimportHistoryimportpandasaspd# Sample datadata=pd.DataFrame({'AAPL':[150,151,152],'MSFT':[300,301,302]})history=History(data)# Adding a new stock tickerhistory.add_security('TSLA',[650,651,652])# Calculating moving averagesmoving_average=history.indicators.sma(window=2)print(moving_average)ContributionsWe welcome improvements and extensions:Fork the repository.Make your enhancements.Submit a pull request.Ensure thorough testing of all changes. Your contributions will makedxlibeven better!