Trading Bot 1.0

 avatar
unknown
plain_text
4 months ago
3.2 kB
8
Indexable
import yfinance as yf
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import schedule
import time
from datetime import datetime

# Function to fetch historical stock data
def fetch_historical_data(ticker, start_date, end_date):
    data = yf.download(ticker, start=start_date, end=end_date)
    data['Return'] = data['Close'].pct_change()  # Daily return as a feature
    data['Moving_Avg'] = data['Close'].rolling(window=20).mean()  # 20-day moving average
    data['Volatility'] = data['Close'].rolling(window=20).std()  # Volatility
    data.dropna(inplace=True)
    return data

# Function to preprocess data for prediction
def preprocess_data(data):
    features = data[['Open', 'High', 'Low', 'Close', 'Volume', 'Moving_Avg', 'Volatility']]
    labels = data['Close'].shift(-1)  # Next day's close price as the target
    features = features[:-1]
    labels = labels[:-1]
    return features, labels

# Function to train a prediction model
def train_model(features, labels):
    X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
    model = RandomForestRegressor(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)
    predictions = model.predict(X_test)
    print(f"Model RMSE: {np.sqrt(mean_squared_error(y_test, predictions))}")
    return model

# Function to fetch real-time stock data and predict
def make_prediction(ticker, model):
    current_data = yf.download(ticker, period='1d', interval='1m')
    latest_data = current_data.iloc[-1]
    features = np.array([
        latest_data['Open'],
        latest_data['High'],
        latest_data['Low'],
        latest_data['Close'],
        latest_data['Volume'],
        latest_data['Close'],  # Placeholder for moving average
        0  # Placeholder for volatility
    ]).reshape(1, -1)
    prediction = model.predict(features)
    print(f"Predicted price for next interval: {prediction[0]}")
    return prediction[0]

# Function to simulate a trading strategy
def trading_strategy(ticker, model, threshold=0.01):
    predicted_price = make_prediction(ticker, model)
    current_price = yf.Ticker(ticker).history(period='1d')['Close'][-1]
    if predicted_price > current_price * (1 + threshold):
        print(f"Buying {ticker} - Predicted price: {predicted_price}, Current price: {current_price}")
    elif predicted_price < current_price * (1 - threshold):
        print(f"Selling {ticker} - Predicted price: {predicted_price}, Current price: {current_price}")
    else:
        print(f"Holding {ticker} - Predicted price: {predicted_price}, Current price: {current_price}")

# Schedule the trading bot to run periodically
def run_bot():
    ticker = "AAPL"
    print(f"Running bot at {datetime.now()}")
    historical_data = fetch_historical_data(ticker, "2023-01-01", "2023-12-31")
    features, labels = preprocess_data(historical_data)
    model = train_model(features, labels)
    trading_strategy(ticker, model)

# Run every hour during trading hours
schedule.every().hour.at(":00").do(run_bot)

while True:
    schedule.run_pending()
    time.sleep(1)
Editor is loading...
Leave a Comment