Skip to content

Instantly share code, notes, and snippets.

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)
# 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
!pip install alpaca_trade_api
!pip install yfinance
!pip install pandas_ta
import requests as rq
import alpaca_trade_api as api
import yfinance as yf
import pandas_ta as ta
# 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
# 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
# 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']
# 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 != {}:
# 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
# Trade with STOP_LOSS and TAKE_PROFIT
def Trade(api, stock, operation, shares_to_trade, take_profit, stop_loss):
api.submit_order(symbol = stock, qty = shares_to_trade, side = operation, type = 'market',
order_class = 'bracket', time_in_force = 'day',
take_profit = {'limit_price': take_profit},
stop_loss = {'stop_price': stop_loss})
message = f'\n\t*{stock}*, qty _{shares_to_trade}_ \n\t\twere {operation}'
send_message(f'{TRADER_BOT_NAME}: we entered the market with:' + message)
return True