Artificial Intelligence (AI) models for Trading

Google in talks with Ray-Ban for AI smart glasses

In partnership with

Welcome to learning edition of the Data Pragmatist, your dose of all things data science and AI.

đź“– Estimated Reading Time: 5 minutes. Missed our previous editions?

đź‘“ Google in talks with Ray-Ban for AI smart glasses LINK

  • Google is in discussions with EssilorLuxottica, the parent company of Ray-Ban, to develop AI-powered Gemini smart glasses and integrate their Gemini AI assistant.

  • EssilorLuxottica is also collaborating with Meta on the Ray-Ban Meta Smart Glasses, and Meta may acquire a minority stake in EssilorLuxottica, which could affect Google's plans.

  • Google's Gemini smart glasses are expected to feature a microphone, speaker, and camera without displays, aligning with the prototypes shown at I/O 2024 for Project Astra.

The fastest way to build AI apps

Writer is the full-stack generative AI platform for enterprises. Build and deploy AI apps quickly with Writer AI Studio, a suite of developer tools fully integrated with our LLMs, graph-based RAG, AI guardrails, and more.

Use Writer Framework to build Python AI apps with drag-and-drop UI creation, our API and SDKs to integrate AI into your existing codebase, or intuitive no-code tools for business users.

đźš« Loophole that helps you identify any bot blocked by OpenAI LINK

  • OpenAI developed a technique called “instruction hierarchy” to prevent misuse of AI by ensuring the model follows the developer’s original instructions rather than user-injected prompts.

  • The first model to include this new safety feature is GPT-4o Mini, which aims to block the “ignore all previous instructions” loophole that could be used to exploit the AI.

  • This update is part of OpenAI's efforts to enhance safety and regain trust, as the company faces ongoing concerns and criticisms about its safety practices and transparency.

🧠 Artificial Intelligence (AI) models for Trading

Machine Learning and its Relation to Artificial Intelligence

Machine Learning (ML) is a subset of Artificial Intelligence (AI) that focuses on developing algorithms enabling computers to learn from data and make decisions. Unlike traditional programming, ML algorithms build models based on sample inputs, making predictions or decisions without human intervention. These algorithms use statistical techniques to identify patterns and relationships within the data, improving their performance over time.

Random Forest Model in Trading Technical Analysis

The Random Forest model, a robust method for classification and regression tasks, constructs multiple decision trees during training. It outputs the mode of the classes or the mean prediction of the individual trees, mitigating the risk of overfitting. This makes it particularly useful in trading technical analysis due to its ability to handle large amounts of data and complex patterns.

For instance, traders can use Random Forest to predict stock price movements based on historical price data, volume, and technical indicators like moving averages and relative strength index (RSI). By training the model on historical data, it learns the intricate relationships between these indicators and future price movements. This enables traders to make informed buy or sell decisions based on the model’s predictions, leveraging its pattern recognition capabilities to enhance predictive accuracy and manage risks.

Practical Example and Model Training

To demonstrate, we retrieve Bitcoin’s daily data using EODHD APIs. We then add technical indicators such as SMA50, SMA200, MACD, RSI14, and VROC. After normalizing and scaling the data, we split it into training and testing sets. Using the scikit-learn library, we train the Random Forest model and make predictions.

from eodhd import APIClient
import config as cfg
from sklearn.model_selection import train_test_split  
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

api = APIClient(cfg.API_KEY)

def get_ohlc_data():
    df = api.get_historical_data("BTC-USD.CC", "d", results=2000)
    return df

def calculate_sma(data, window):
    return data.rolling(window=window).mean()

def calculate_macd(data, short_window=12, long_window=26, signal_window=9):
    short_ema = data.ewm(span=short_window, adjust=False).mean()
    long_ema = data.ewm(span=long_window, adjust=False).mean()
    macd = short_ema - long_ema
    signal_line = macd.ewm(span=signal_window, adjust=False).mean()
    return macd, signal_line

def calculate_rsi(data, window=14):
    delta = data.diff(1)
    gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    return rsi

def calculate_vroc(volume, window=14):
    vroc = ((volume.diff(window)) / volume.shift(window)) * 100
    return vroc

df = get_ohlc_data()
df["sma50"] = calculate_sma(df["close"], 50)
df["sma200"] = calculate_sma(df["close"], 200)
df["macd"], df["signal"] = calculate_macd(df["close"])
df["rsi14"] = calculate_rsi(df["close"])
df["vroc14"] = calculate_vroc(df["volume"])
df.dropna(inplace=True)

features = ["open", "high", "low", "volume", "sma50", "sma200", "macd", "signal", "rsi14", "vroc14"]
X = df[features]
y = df["close"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

rf = RandomForestRegressor(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
y_train_pred = rf.predict(X_train)
y_test_pred = rf.predict(X_test)

Evaluation and Improvement

We evaluate the model’s performance using Mean Absolute Error (MAE), Mean Squared Error (MSE), and the R-squared score (R²). Although the model performs well, some degree of overfitting is observed. To improve this, we can employ techniques like regularization, cross-validation, feature engineering, and hyperparameter tuning. These steps help achieve a better balance between training and testing performance, leading to a more robust model.

feature_importances = rf.feature_importances_
importance_df = pd.DataFrame({"Feature": features, "Importance": feature_importances})
importance_df = importance_df.sort_values(by="Importance", ascending=False)

plt.figure(figsize=(12, 8))
sns.barplot(x="Importance", y="Feature", data=importance_df)
plt.title("Feature Importances of Technical Indicators")
plt.show()

Feature Importance

The Random Forest model can also determine the importance of various features in predicting the target. This insight allows traders to refine their strategies by focusing on the most impactful indicators. However, applying technical analysis rules to these features can provide more meaningful insights, such as using moving average crossovers or RSI thresholds to generate buy and sell signals.

feature_importances = rf.feature_importances_
importance_df = pd.DataFrame({"Feature": features, "Importance": feature_importances})
importance_df = importance_df.sort_values(by="Importance", ascending=False)

plt.figure(figsize=(12, 8))
sns.barplot(x="Importance", y="Feature", data=importance_df)
plt.title("Feature Importances of Technical Indicators")
plt.show()

Top AI Tools for Trading

EquBot

  1. AI tool for stock trading analysis using NLP and ML algorithms.

  2. Features:

    • Assesses sentiment from news/social media

    • Identifies technical patterns

    • Custom watchlists

Trade Ideas

  1. AI-driven tool scanning the stock market for trading opportunities.

  2. Features:

    • Spots bullish/bearish patterns

    • Ranks top stocks

    • Real-time trading alerts

TrendSpider

  1. AI tool for stock chart analysis and trade signals.

  2. Features:

    • Analyzes custom indicators

    • Identifies patterns

    • Automated trade alerts

How did you like today's email?

Login or Subscribe to participate in polls.

If you are interested in contributing to the newsletter, respond to this email. We are looking for contributions from you — our readers to keep the community alive and going.