def foo(config): print('Running...') asset = EURUSD(generate_data(100000)) account = Account(initial_balance=1000) slow_period = 45 fast_period = 35 sma = np.zeros((asset.data.shape[0],2)) sma[(slow_period-1):,0] = moving_average(asset.data[:,1],slow_period) sma[(fast_period-1):,1] = moving_average(asset.data[:,1],fast_period) risk_man = ConstantRate(config['lot_size'],on='free_margin') strategy = MACross(RiskManagement=risk_man,rate=config['rate']) strategy = asset.register(strategy) result = BackTest(account,strategy).run(assets=asset,exog=sma) tune.track.log(mean_accuracy=result.Account.balance)
if stock not in selected.index: self.selected_to_close.append(stock) del self.past_data[0] return order.asset_id in self.selected_to_close # close if the order is selected for close else: return False else: return order.asset_id in self.selected_to_close # close if the order is selected for close def decide_short_close(self, order, spot_price, timestamp, Account, exog): return False stocks = [ Stock(generate_data(10000, freq='1h'), name=f'stock_{i}', short_name=f'STCK_{i}') for i in range(20) ] # randomly generate stock prices account = Account( initial_balance=1000) # initialize an account with 1000 USD balance risk_man = ConstantRate(0.05) # constant lot size with 5% of balance each time strategy = CustomAllocation(RiskManagement=risk_man, id=45450, name='custom_buyer') for stock in stocks: strategy = stock.register( strategy) # allow strategy to use all of them, either one or multiple sim = BackTest(Account=account, Strategy=strategy).run(stocks) print(sim.Account.balances)
if __name__ == "__main__": path = "../data/market/" stocks = [] for symbol in os.listdir(path): print(symbol) tmp = pd.read_csv(os.path.join(path, symbol), parse_dates=True)[["Adj Close", "Date"]] tmp.columns = ["close", "timestamp"] tmp["timestamp"] = pd.to_datetime(tmp["timestamp"]) tmp = tmp.dropna(how="any", axis=0) if tmp.shape[0] > 252 * 9: stocks.append(Stock(price=tmp.values, base=symbol.strip(".csv"))) # initialize an account with 1M USD balance account = Account() # set equal weights for all stocks risk_man = EqualWeight() # initialize the strategy strategy = CustomAllocation(RiskManagement=risk_man, name="momentum_factor") # allow strategy to use all assets for stock in stocks: strategy = stock.register(strategy) sim = BackTest(Account=account, Strategy=strategy).run(stocks) sim.Strategy.save("momentum.strt") print(sim.Account.balances)
import pandas as pd sys.path.insert(0, "../") from strategy_tester.account import Account from strategy_tester.asset import Stock from strategy_tester.strategy import Strategy from strategy_tester.risk_management import ConstantLots from strategy_tester.simulate import BackTest from strategy_tester.utils import generate_data, ROI, sharpe_ratio import numpy as np import time aapl = Stock(price=generate_data(100000), base="AAPL") account = Account(max_allowed_risk=None, max_n_orders=10) risk_man = ConstantLots(0.1) strategy = Strategy(RiskManagement=risk_man, id=23030, name="noise_trader") strategy = aapl.register(strategy) sim = BackTest( Account=account, Strategy=strategy, track=[ROI, sharpe_ratio] ).run(aapl) # print(sim.tracked_results) # print(sim.Account.balances) # print(sim.Account.equities) # print(sim.Account.free_margins) # print(sim.Account.navs) # print(sim.Account.n_inactive_orders) # print(sim.Account.max_n_active_orders)
import sys import numpy as np import pandas as pd sys.path.insert(0, '../') from strategy_tester.account import Account from strategy_tester.asset import AAPL from strategy_tester.strategy import Strategy from strategy_tester.risk_management import ConstantLots from strategy_tester.simulate import BackTest from strategy_tester.utils import generate_data, ROI, sharpe_ratio import numpy as np import time aapl = AAPL(generate_data(100000)) account = Account(initial_balance=1000, max_allowed_risk=None, max_n_orders=10) risk_man = ConstantLots(0.1) strategy = Strategy(RiskManagement=risk_man, id=23030, name='noise_trader') strategy = aapl.register(strategy) start = time.time() sim = BackTest(Account=account, Strategy=strategy, track=[ROI, sharpe_ratio]).run(aapl) end = time.time() print(f'{end-start} seconds elapsed.') print(sim.tracked_results) # print(sim.Account.balances) # print(sim.Account.equities) # print(sim.Account.free_margins) # print(sim.Account.navs)
# TO DO: simplify the code class Random(ParamSearch): def __init__(self,q,*args,**kwargs): super().__init__(*args,**kwargs) if not 0 < q < 1: raise ValueError('q must be in (0,1)') self.q = q def run(self,*args,**kwargs): params = list(dict_product(self._paramset)) size = len(params) self.n = int(size*self.q) idxs = np.random.randint(0,size,self.n,dtype=int) params = [params[i] for i in idxs] list(map(lambda s: self._run(s,*args,**kwargs),params)) return self if __name__ == '__main__': from strategy_tester.utils import generate_data, dict_product from strategy_tester.account import Account from strategy_tester.strategy import Strategy from strategy_tester.risk_management import ConstantRate data = generate_data(100000) account = Account(balance=1000) paramset = {'RiskManagement':[ConstantRate(0.05),ConstantRate(0.1),ConstantRate(0.2)]} sim = Random(0.7,account,Strategy,paramset).run(data.values) print(sim.output)
'size': self.RiskManagement.order_size(Account), 'strike_price': spot_price[asset_id] } output[asset_id] = args return output def decide_long_close(self, order, spot_price, timestamp, Account, exog): return exog[0] < exog[1] def decide_short_close(self, order, spot_price, timestamp, Account, exog): return exog[0] > exog[1] np.random.seed(123) aapl = AAPL(generate_data(100000)) account = Account(initial_balance=1000) risk_man = ConstantRate(0.01, on='free_margin') strategy = MACross(RiskManagement=risk_man, id=45450, name='ma_cross_trader') strategy = aapl.register(strategy) slow_period = 45 fast_period = 35 sma = np.zeros((aapl.data.shape[0], 2)) sma[(slow_period - 1):, 0] = moving_average(aapl.data[:, 1], slow_period) sma[(fast_period - 1):, 1] = moving_average(aapl.data[:, 1], fast_period) sim = BackTest(Account=account, Strategy=strategy, track=(ROI, sharpe_ratio)).run(aapl, exog=sma) print(sim.tracked_results) print(sim.Account.balances)