How to Make a Python Fully Automatic AI Based Trading System

Getting the data

Ever since Yahoo! finance decommissioned their historical data API, many programs that relied on it to stop working.

yfinance aimes to solve this problem by offering a reliable, threaded, and Pythonic way to download historical market data from Yahoo! finance.

$ pip install yfinance --user
import yfinance as yfgoogle = yf.Ticker(“GOOG”)
52WeekChange: 0.3531152
SandP52WeekChange: 0.17859101
address1: 1600 Amphitheatre Parkway
algorithm: None
annualHoldingsTurnover: None
annualReportExpenseRatio: None
ask: 1815
askSize: 1100...twoHundredDayAverage: 1553.0764
volume: 1320946
volume24Hr: None
volumeAllCurrencies: None
website: http://www.abc.xyz
yield: None
ytdReturn: None
zip: 94043
df = google.history(period='1d', interval="1m")
print(df.head())
df = google.history(period='1d', interval="1m")
df = df[['Low']]
df.head()
df['date'] = pd.to_datetime(df.index).time
df.set_index('date', inplace=True)
df.head()

Adding the AI

X = df.index.values
y = df['Low'].values# The split point is the 10% of the dataframe length
offset = int(0.10*len(df))X_train = X[:-offset]
y_train = y[:-offset]
X_test = X[-offset:]
y_test = y[-offset:]
plt.plot(range(0,len(y_train)),y_train, label='Train')
plt.plot(range(len(y_train),len(y)),y_test,label='Test')
plt.legend()
plt.show()
from statsmodels.tsa.arima.model import ARIMAmodel = ARIMA(y_train, order=(5,0,1)).fit()
forecast = model.forecast(steps=1)[0]
print(f'Real data for time 0: {y_train[len(y_train)-1]}')
print(f'Real data for time 1: {y_test[0]}')
print(f'Pred data for time 1: {forecast}')---Real data for time 0: 1776.3199462890625Real data for time 1: 1776.4000244140625
Pred data for time 1: 1776.392609828666

Connecting to the broker

RobinHood

$ pip install robin_stocks
import pyotp
import robin_stocks as robinhoodRH_USER_EMAIL = <<<YOUR EMAIL GOES HERE>>>
RH_PASSWORD = <<<YOUR PASSWORD GOES HERE>>>
RH_MFA_CODE = <<<THE ALPHANUMERIC CODE GOES HERE>>>timed_otp = pyotp.TOTP(RH_MFA_CODE).now()
login = rh.login(RH_USER_EMAIL, RH_PASSWORD, mfa_code=totp)
# Buying 5 shares of Google
rh.order_buy_market('GOOG', 5)# Selling 5 shares of Google
rh.order_sell_market('GOOG', 5)

Alpaca

$ pip install alpaca-trade-api
import alpaca_trade_api as alpacaALPACA_KEY_ID = <<<YOUR KEY ID GOES HERE>>>
ALPACA_SECRET_KEY = <<<YOUR SECRET KEY GOES HERE>>># Change to https://api.alpaca.markets for live
BASE_URL = 'https://paper-api.alpaca.markets'api = alpaca.REST(
ALPACA_KEY_ID, ALPACA_SECRET_KEY, base_url=BASE_URL)
# Buying 5 shares of Google
api.submit_order(
symbol='GOOG',
qty='5',
side='buy',
type='market',
time_in_force='day'
)# Selling 5 shares of Google
api.submit_order(
symbol='GOOG',
qty='5',
side='sell',
type='market',
time_in_force='day'
)

Deploy and monitoring

$ npm install serverless --global
$ serverless create --template aws-python3 --path ai_trading_system
import telegram
import sys
import osCHAT_ID = XXXXXXXX
TOKEN = os.environ['TELEGRAM_TOKEN']
# The global variables should follow the structure:
# VARIABLE = os.environ['VARIABLE']
# for instance:
# RH_USER_EMAIL = os.environ['RH_USER_EMAIL]def do_everything():
# The previous code to get the data, train the model
# and send the order to the broker goes here.
return 'The action performed'def send_message(event, context):
bot = telegram.Bot(token=TOKEN)
action_performed = do_everything() bot.sendMessage(chat_id=CHAT_ID, text=action_performed)
org: your-organization-name
app: your-app-name
service: ai_trading_systemframeworkVersion: “>=1.2.0 <2.0.0”provider:
name: aws
runtime: python3.6
environment:
TELEGRAM_TOKEN: ${env:TELEGRAM_TOKEN}
# If using RobinHood
RH_USER_EMAIL: ${env:RH_USER_EMAIL}
RH_PASSWORD: ${env:RH_PASSWORD}
RH_MFA_CODE: ${env:RH_MFA_CODE}
# If using Alpaca
ALPACA_KEY_ID: ${env:ALPACA_KEY_ID}
ALPACA_SECRET_KEY: ${env:ALPACA_SECRET_KEY}functions:
cron:
handler: handler.send_message
events:
# Invoke Lambda function at 21:00 UTC every day
- schedule: cron(00 21 * * ? *)
$ export AWS_ACCESS_KEY_ID=[your key goes here]
$ export AWS_SECRET_ACCESS_KEY=[your key goes here]
$ export TELEGRAM_TOKEN=[your token goes here]# If using RobinHood
$ export RH_USER_EMAIL=[your mail goes here]
$ export RH_PASSWORD=[your password goes here]
$ export RH_MFA_CODE=[your mfa code goes here]

# If using Alpaca
$ export ALPACA_KEY_ID=[your key goes here]
$ export ALPACA_SECRET_KEY=[your key goes here]
$ pip3 install -r requirements.txt -t . --system
$ serverless deploy

References:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store