Skip to content

Instantly share code, notes, and snippets.

# Get predictions from LSTM neural network
def Predict(stock):
predictions = [100.24, 155.33, 140.55]
# Here we have to organize communication between our algorithm and LSTM Model \
# to get predictions by ticker for the particular stock.
# But this is the question to the infrastructure.
# I am gonna consider it in the next article "Infrastructure itself".
return predictions
# Screen stocks
def ScreenStocks(trader_api):
assets = trader_api.list_assets(status='active', asset_class='us_equity')
assets = [x for x in assets if x.shortable == True and x.exchange == 'NASDAQ']
stocks = [x.symbol for x in assets][:SCREENER_NASDAQ_COUNT]
screened = []
for st in stocks:
_stock = CheckStock(st)
if _stock != {}:
# Check stock with TA indicators
def CheckStock(stock):
data = {}
try:
df = yf.download(stock, period = SCREENER_PERIOD, interval = SCREENER_INTERVAL)
if (len(df) > 0):
df['RSI'] = ta.rsi(df['Close'], timeperiod=14)
bbands = ta.bbands(df['Close'], length = 20, std=2.3)
df['L'] = bbands['BBL_20_2.3']
df['M'] = bbands['BBM_20_2.3']
# Send message to Telegram channel
def send_message(message):
response = rq.post(
f'{TELEGRAM_URL}/{TELEGRAM_BOT_ID}/sendMessage?chat_id={TELEGRAM_CHAT_ID}&parse_mode=Markdown&text={message}')
return response
# SETTINGS
TRADER_BOT_NAME = 'Medium trading bot'
TRADER_API_KEY = '[API key]'
TRADER_API_SECRET = '[API secret]'
TRADER_API_URL = 'https://paper-api.alpaca.markets'
TELEGRAM_URL = 'https://api.telegram.org'
TELEGRAM_BOT_ID = 'bot0000000000:AAA_gNNN00B0xxxDaaaUD00HHH-Y0wAAmhA' # Medium trading bot
TELEGRAM_CHAT_ID = '-1002003005001' # Medium trading bot channel
import requests as rq
import alpaca_trade_api as api
import yfinance as yf
import pandas_ta as ta
!pip install alpaca_trade_api
!pip install yfinance
!pip install pandas_ta
# Execute model for the whole history range
copy_df = init_df.copy()
y_predicted = model.predict(x_train)
y_predicted_transformed = np.squeeze(scaler.inverse_transform(y_predicted))
first_seq = scaler.inverse_transform(np.expand_dims(y_train[:6], axis=1))
last_seq = scaler.inverse_transform(np.expand_dims(y_train[-3:], axis=1))
y_predicted_transformed = np.append(first_seq, y_predicted_transformed)
y_predicted_transformed = np.append(y_predicted_transformed, last_seq)
copy_df[f'predicted_close'] = y_predicted_transformed
if bool(predictions) == True and len(predictions) > 0:
predictions_list = [str(d)+'$' for d in predictions]
predictions_str = ', '.join(predictions_list)
message = f'{STOCK} prediction for upcoming 3 days ({predictions_str})'
print(message)
# GET PREDICTIONS
predictions = []
for step in LOOKUP_STEPS:
df, last_sequence, x_train, y_train = PrepareData(step)
x_train = x_train[:, :, :len(['close'])].astype(np.float32)
model = GetTrainedModel(x_train, y_train)
last_sequence = last_sequence[-N_STEPS:]