def opt_cut_aggr(self, cuts, grades, seed, plot=True): heatmap = np.zeros([len(cuts), len(grades)]) for i, cut in enumerate(cuts): for j, grade in enumerate(grades): # set cut of strateg self.strat.cut = cut self.strat.grade = grade # set initial investment of Backtester Backtester = backtester.Backtester(self.DataHelper, self.model, self.strat, 1) Backtester.initialInvest = seed # append return _, r, _ = Backtester.backtest_OOT(returnAll=False) heatmap[i, j] = r # change it to df heatmap_df = pd.DataFrame(heatmap, index=cuts, columns=grades) if plot: plt.figure(figsize=(10, 8)) ax = sns.heatmap(heatmap_df, cmap="YlGnBu") ax.set_title( "aggressive strategy return with init invest {}".format(seed)) plt.show() return heatmap_df
def opt_cut_conserv(self, cuts, seed, plot=True): profits = [] for cut in cuts: # set cut of strateg self.strat.cut = cut # set initial investment of Backtester Backtester = backtester.Backtester(self.DataHelper, self.model, self.strat, 1) Backtester.initialInvest = seed # run backtest _, r, _ = Backtester.backtest_OOT(returnAll=False) # append return profits.append(r) if plot: plt.figure(figsize=(10, 8)) plt.plot(cuts, profits) plt.show() return profits
def opt_amountfunc_aggr(self, slopes, maxs, cut, grade, seed, plot=False): # set cut of strateg self.strat.cut = cut self.strat.grade = grade heatmap = np.zeros([len(slopes), len(maxs)]) for i, s in enumerate(slopes): for j, m in enumerate(maxs): # set cut of strateg self.strat.amount_slope = s self.strat.amount_max = m # set initial investment of Backtester Backtester = backtester.Backtester(self.DataHelper, self.model, self.strat, 1) Backtester.initialInvest = seed # append return _, r, _ = Backtester.backtest_OOT(returnAll=False) heatmap[i, j] = r # change it to df heatmap_df = pd.DataFrame(heatmap, index=slopes, columns=maxs) if plot: plt.figure(figsize=(10, 8)) ax = sns.heatmap(heatmap_df, cmap="YlGnBu") ax.set_title( "aggressive strategy return with init invest {}".format(seed)) ax.set_ylabel('p1 - slope') ax.set_xlabel('p2 - max') plt.show() return heatmap_df
def statisticalArb(cash, stock1, stock2, start, end, days_moving_avg, hedge_method): df = getStocks(stock1, stock2, start, end, days_moving_avg) # first graph the stocks df[stock1].plot(label=stock1, color='b') df[stock2].plot(label=stock2, color='g') plt.legend(loc='upper left') plt.title('Stock Prices') plt.show() # calculate hedge ratio df = calculateHedgeRatio(df, stock1, stock2, days_moving_avg, hedge_method) # print "Hedge Ratio Used: " + str(hedge_ratio) df = calculateResidual(df, stock1, stock2, days_moving_avg) getStatistics(df, hedge_method) graph(df) Backtester = backtester.Backtester(capital_limit, df, stock1, stock2, days_moving_avg) Backtester.run() # print df['HedgeRatio'].tolist() # print df['2016-09-01':'2016-11-01'] # staticHedge(df[:'2016-09-19 00:00:00'], days_moving_avg) # DEBUGGING # plt.plot(df.index, df['HedgeRatio'], label='Hedge Ratio') # plt.title('Static Hedge Ratio Over Time (DEBUGGING)') plt.show()
import backtester, math from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix import pickle from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM initial = pd.read_csv('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&interval=1min&symbol=msft&apikey=OUMVBY0VK0HS8I9E&datatype=csv&outputsize=full') initial = initial[::-1].reset_index(drop=True) #initial = initial[:500] scaler = MinMaxScaler(feature_range=(0,1)) model = 1 buy_price = 0.0 initialInvestment = 1000 b = backtester.Backtester(initialInvestment) predictions = [] with open('lstm.pkl', 'rb') as file: model = pickle.load(file) scaler.fit(initial.filter(['close'])) for i in range(len(initial)-60): new_df = initial.filter(['close']) last_60_days = new_df[i:60+i].values last_60_days_scaled = scaler.transform(last_60_days) X_test = [] X_test.append(last_60_days_scaled) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) pred_price = model.predict(X_test)
content = json.loads(buy.content) return float(content['candles'][-1]['mid']['c']) #close first, close second except Exception as e: return 1.257 # r = requests.get('https://finance.yahoo.com/quote/GBPUSD=X/') # soup = bs4.BeautifulSoup(r.text, 'lxml') # f = soup.find('div',{'class': 'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text # return float(f) initial = pd.read_csv('https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol=aud&to_symbol=USD&interval=1min&apikey=OUMVBY0VK0HS8I9E&outputsize=full&datatype=csv') initial = initial[::-1] initial.drop(['timestamp', 'open', 'high', 'low'], axis=1, inplace=True) b = backtester.Backtester(1000) model = 1 buy_price = 0.0 predictions = [1.0] with open('forex_lstm.pkl', 'rb') as file: model = pickle.load(file) scaler = MinMaxScaler(feature_range=(0,1)) scaler.fit(initial) for i in range(10000): now = datetime.now() # dd/mm/YY H:M:S new_dict = {} close = get_close() new_dict['close'] = float(close)
create_order('MSFT', 5, 'sell', 'market', 'day') predictions.append(pred) except Exception as e: print(e) socket = 'wss://data.alpaca.markets/stream' API_KEY = 'PKOT8ZWPLGJ94Q705388' SECRET_KEY = 'GgjCthiFXfl8b05cMsdZ4uhZ2aekaMNgX2ZzPB3T' APCA_API_BASE_URL = 'https://paper-api.alpaca.markets' api = tradeapi.REST(API_KEY, SECRET_KEY, APCA_API_BASE_URL, api_version='v2') account = api.get_account() indicators = pd.DataFrame() i = 0 b = backtester.Backtester(12000) X_test = pd.DataFrame() initial = pd.DataFrame() from sklearn.ensemble import RandomForestRegressor rfc = RandomForestRegressor(n_estimators=100) predictions = [209.8] buy_price = 0.0 with open('stock_model.pkl', 'rb') as file: rfc = pickle.load(file) ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message) ws.run_forever()