def calcStrategy(start_date, end_date, index): full_market_returns = [] full_returns_bh = [] #dh = am.DataHandler(index) dh = MSDataManager() for ticker in dh.ReturnIndexConstituents(index): df1 = dh.ReturnData(ticker, start_date=start_date, end_date=end_date,) df, returnsStrat, returnsBH = MOM1(df1, start_date, end_date, 5) full_market_returns.append(returnsStrat*100) full_returns_bh.append(returnsBH*100) return [np.average(np.array(full_market_returns)), np.average(np.array(full_returns_bh))]
def calcReturns(stockPicker, start_date, end_date, strategyToTest, index): dh = MSDataManager() df1 = dh.ReturnData(stockPicker, start_date=start_date, end_date=end_date) df, returnsStrat, returnsBH = globals()[strategyToTest](df1, start_date, end_date, 5) tickerSymbol = [] buyPrices = [] buyDates = [] buySignals = [] sellPrices = [] sellDates = [] sellSignals = [] returns = [] for i in range(len(df)): sig1 = df['bsSig'].iat[i] val1 = df['Close'].iat[i] date1 = df.index[i] signal = str(int(df['SignalMACD'][i])) + str(int( df['SignalROC'][i])) + str(int(df['SignalSTOC'][i])) + str( int(df['SignalRSI'][i])) if sig1 == 1: tickerSymbol.append(stockPicker) priceBuy = val1 buyPrices.append(val1) buyDates.append(date1) buySignals.append(signal) elif sig1 == -1: priceSell = val1 sellPrices.append(val1) sellDates.append(date1) profit = (priceSell - priceBuy) / priceBuy sellSignals.append(signal) returns.append(round(profit * 100, 2)) data = np.array([ tickerSymbol, buyDates, buyPrices, buySignals, sellDates, sellPrices, sellSignals, returns ]).T.tolist() dff = pd.DataFrame(data=data, columns=[ 'Symbol', 'datebuy', 'pricebuy', 'buysignals', 'datesell', 'pricesell', 'sellsignals', 'perprofit' ]) return dff, returnsStrat, returnsBH
def info_div_callback(ticker, n_intervals): ticker_sym = ticker.split('-')[0].strip() ticker_sec = ticker.split('-')[1].strip() dh = MSDataManager() mh = MarketHours('NYSE') mo_class = 'cgreen' if mh.MarketOpen else 'cred' mo_str = 'open' if mh.MarketOpen else 'closed' latest_trade_date = dh.ReturnLatestStoredDate(ticker_sym) latest_trade_date_str = latest_trade_date.strftime( '%d-%m-%Y - %H:%M:%S') data = dh.ReturnData(ticker_sym, start_date=latest_trade_date - relativedelta(years=1), end_date=latest_trade_date, limit=None) latest = data['Close'].iloc[-1] diff = (data['Close'][-2] - data['Close'][-1]) pct_change = diff / data['Close'][-2] pl_class = 'cgreen' if diff > 0 else 'cred' pl_sign = '+' if diff > 0 else '-' # pct_change = f'' ftwh = data['Close'].values.max() ftwl = data['Close'].values.min() #market_cap = data['market_cap'].iloc[-1] # market_cap = 0 #curr = str(data['currency'].iloc[-1]).replace('EUR', '€') curr = 'USD' children = [ dbc.Row([html.H6(f'{ticker_sec} ({ticker_sym})', className='')]), dbc.Row([ dbc.Col( [ html.P([ html.Span( html.Strong( f'{curr} {latest:.2f} ', className=pl_class + ' large bold')), html.Span(f'{pl_sign}{diff:.2f} ', className=pl_class + ' small'), html.Span(f'({pl_sign}{pct_change:.2f}%)', className=pl_class + ' small'), ], ), html.P( html.Span( f'As of {latest_trade_date_str}. Market {mo_str}.', className=' small')) ], md=12, ), ]), ] # dbc.Row( # html.Div([ # dcc.RangeSlider( # disabled = True, # min=ftwl, # max=ftwh, # value=[ftwl, latest, ftwh], # # value=[1, 20, 40] # marks={ # float(ftwl): {'label': f'{curr} {ftwl:.2f}', 'style': {'color': '#77b0b1'}}, # float(latest): {'label': f'{curr} {latest:.2f}', 'style': {'color': '#77b0b1'}}, # float(ftwh): {'label': f'{curr} {ftwh:.2f}', 'style': {'color': '#77b0b1'}} # } # ) # ], # style={'display': 'block', 'width': '60%', 'padding': ''}, # className='mt-1' # ) # ) # {latest_trade_date} # latest}+({pct_change:.2f})') return children
def get_fig(ticker, type_trace, studies, start_date, end_date, index): # for ticker in ticker_list: #dh = am.DataHandler(index) dh = MSDataManager() df = dh.ReturnData(ticker, start_date=start_date, end_date=end_date) selected_subplots_studies = [] selected_first_row_studies = [] row = 2 # number of subplots if studies != []: for study in studies: if study in subplot_traces: row += 1 # increment number of rows only if the study needs a subplot selected_subplots_studies.append(study) else: selected_first_row_studies.append(study) fig = tools.make_subplots(rows=row, shared_xaxes=True, shared_yaxes=False, cols=1, print_grid=True, vertical_spacing=0.05, row_width=[0.2] * (row - 1) + [1 - (row - 1) * 0.2]) fig.append_trace(globals()[type_trace](df), 1, 1) fig['layout'][f'xaxis{row}'].update(tickangle=-0, tickformat='%Y-%m-%d', autorange=True, showgrid=True, mirror='ticks', color='rgba(255, 255, 255, 1)', tickcolor='rgba(255,255,255,1)') fig['layout']['yaxis1'].update( range=[df['Close'].min() / 1.3, df['Close'].max() * 1.05], showgrid=True, anchor='x1', mirror='ticks', layer='above traces', color='rgba(255, 255, 255, 1)', gridcolor='rgba(255, 255, 255, 1)') fig['layout']['yaxis2'].update( # range= [0, df['Volume'].max()*4], # overlaying = 'y2', # layer = 'below traces', autorange=True, # anchor = 'x1', side='left', showgrid=True, title='D. Trad. Vol.', color='rgba(255, 255, 255, 1)', ) # if model != '' and model is not None: # # bsSig, retStrat, retBH = globals()[strategyTest](df, start_date, end_date, 5) # ml = load(model) # fig = bsMarkers(df, fig) # fig['layout'].update(annotations=[ # dict( # x = df.index[int(round(len(df.index)/2, 0))], # y = df['Close'].max()*1.02, # text = 'Your Strategy: ' + str(round(retStrat*100, 0)) + ' % \nBuy&Hold: ' + str(round(retBH*100, 0)) + '%', # align = 'center', # font = dict( # size = 16, # color = 'rgb(255, 255, 255)'), # showarrow = False, # ) # ] # ) for study in selected_first_row_studies: fig = globals()[study](df, fig) # add trace(s) on fig's first row row = 2 fig = vol_traded(df, fig, row) for study in selected_subplots_studies: row += 1 fig = globals()[study](df, fig, row) # plot trace on new row fig['layout'].update(chart_layout) fig['layout']['xaxis'].update(rangeselector=dict(buttons=list([ dict(count=1, label='1M', step='month', stepmode='backward'), dict(count=6, label='6M', step='month', stepmode='backward'), dict(count=1, label='YTD', step='year', stepmode='todate'), dict(count=1, label='1Y', step='year', stepmode='backward'), dict(count=3, label='3Y', step='year', stepmode='backward'), dict(step='all', label='MAX') ])), rangeslider=dict(visible=False), type="date") return fig
def info_div_callback(ticker, n_intervals, index, timeRange): #dh = am.DataHandler(index) dh = MSDataManager() #print(index) mh = MarketHours('NYSE') data = None #data = dh.ReturnDataRT(ticker) #children = '' #if not data.empty data = dh.ReturnData(ticker, limit=2) #if data is not None: latest = data['Close'].iloc[-1] latest_trade_date = dh.ReturnLatestStoredDate(ticker).strftime( '%Y:%M:%d - %H:%M:%S') diff = data['Close'].diff()[-1] pct_change = data['Close'].pct_change()[-1] ftwh = data['Close'].values.max() ftwl = data['Close'].values.min() #market_cap = data['market_cap'].iloc[-1] market_cap = 0 #curr = str(data['currency'].iloc[-1]).replace('EUR', '€') curr = 'USD' children = [ html.Div([ html.Table( [ # html.Tr([ # html.Td(html.H2(ticker)), # html.Td(), # html.Td(), # html.Td('Market cap:'), # html.Td(f'{curr} {market_cap:.2f}') # ]), # html.Tr([ # html.Td([ # html.Span(f'{curr}{latest:.2f}'), # html.Span(f'{diff:.2f} + ({pct_change:.2f})') # ], className = 'small'), # html.Td(), # html.Td(), # html.Td(html.Span('Market open', style={'color': 'green'}) if mh.MarketOpen() else html.Span('Market closed', style={'color': 'red'})), # html.Td() # ]), # html.Tr([ # html.Td([html.Span(str(latest_trade_date))]), # html.Td(), # html.Td(), # html.Td(), # html.Td() # ]), ], className='small'), ]), # html.Div([ # dcc.RangeSlider( # disabled = True, # min=ftwl, # max=ftwh, # value=[ftwl, latest, ftwh], # marks={ # ftwl: {'label': curr + str(ftwl), 'style': {'color': '#77b0b1'}}, # latest: {'label': curr + str(latest), 'style': {'color': '#77b0b1'}}, # ftwh: {'label': curr + str(ftwh), 'style': {'color': '#77b0b1'}} # } # ) # ], style={'display': 'block', 'width': '60%', 'padding': '8px 40px'}) ] # children = html.H1(ticker) return children
def get_fig(ticker, type_trace, studies, strategyTest, start_date, end_date, index): # for ticker in ticker_list: #dh = am.DataHandler(index) dh = MSDataManager() df = dh.ReturnData(ticker, start_date=start_date, end_date=end_date) subplot_traces = [ # first row traces 'RSI', 'ROC', 'MACD', 'STOC', 'D_RETURNS', 'ATR', 'ADX', 'WR' ] selected_subplots_studies = [] selected_first_row_studies = [] row = 2 # number of subplots if studies != []: for study in studies: if study in subplot_traces: row += 1 # increment number of rows only if the study needs a subplot selected_subplots_studies.append(study) else: selected_first_row_studies.append(study) fig = tools.make_subplots(rows=row, shared_xaxes=True, shared_yaxes=False, cols=1, print_grid=True, vertical_spacing=0.05, row_width=[0.2] * (row - 1) + [1 - (row - 1) * 0.2]) fig.append_trace(globals()[type_trace](df), 1, 1) fig = average_close(df, index, ticker, fig) fig['layout'][f'xaxis{row}'].update(tickangle=-0, tickformat='%Y-%m-%d', autorange=True, showgrid=True, mirror='ticks', color='rgba(255, 255, 255, 1)', tickcolor='rgba(255,255,255,1)') fig['layout']['yaxis1'].update( range=[df['Close'].min() / 1.3, df['Close'].max() * 1.05], showgrid=True, anchor='x1', mirror='ticks', layer='above traces', color='rgba(255, 255, 255, 1)', gridcolor='rgba(255, 255, 255, 1)') fig['layout']['yaxis2'].update( # range= [0, df['Volume'].max()*4], # overlaying = 'y2', # layer = 'below traces', autorange=True, # anchor = 'x1', side='left', showgrid=True, title='D. Trad. Vol.', color='rgba(255, 255, 255, 1)', ) if strategyTest != '' and strategyTest is not None: bsSig, retStrat, retBH = globals()[strategyTest](df, start_date, end_date, 5) fig = bsMarkers(df, fig) fig['layout'].update(annotations=[ dict( x=df.index[int(round(len(df.index) / 2, 0))], y=df['Close'].max() * 1.02, text='Your Strategy: ' + str(round(retStrat * 100, 0)) + ' % \nBuy&Hold: ' + str(round(retBH * 100, 0)) + '%', align='center', font=dict(size=16, color='rgb(255, 255, 255)'), showarrow=False, ) ]) for study in selected_first_row_studies: fig = globals()[study](df, fig) # add trace(s) on fig's first row row = 2 fig = vol_traded(df, fig, row) for study in selected_subplots_studies: row += 1 fig = globals()[study](df, fig, row) # plot trace on new row fig['layout']['margin'] = {'b': 30, 'r': 60, 'l': 40, 't': 10} fig['layout'].update( autosize=True, uirevision='The User is always right', height=600, # paper_bgcolor = '#000000', paper_bgcolor='#222', # paper_bgcolor = 'rgb(64, 68, 72)', # paper_bgcolor = 'rgb(219, 240, 238)', # plot_bgcolor = '#000000', plot_bgcolor='#222', # plot_bgcolor = 'rgb(64, 68, 72)', # plot_bgcolor = 'rgb(219, 240, 238)', hovermode='x', spikedistance=-1, xaxis={ 'gridcolor': 'rgba(255, 255, 255, 0.5)', 'gridwidth': .5, 'showspikes': True, 'spikemode': 'across', 'spikesnap': 'data', 'spikecolor': 'rgb(220, 200, 220)', 'spikethickness': 1, 'spikedash': 'dot' }, yaxis={ 'gridcolor': 'rgba(255, 255, 255, 0.5)', 'gridwidth': .5 }, legend=dict(x=1.05, y=1)) fig['layout']['xaxis'].update(rangeselector=dict(buttons=list([ dict(count=1, label='1M', step='month', stepmode='backward'), dict(count=6, label='6M', step='month', stepmode='backward'), dict(count=1, label='YTD', step='year', stepmode='todate'), dict(count=1, label='1Y', step='year', stepmode='backward'), dict(count=3, label='3Y', step='year', stepmode='backward'), dict(step='all', label='MAX') ])), rangeslider=dict(visible=False), type="date") return fig