File size: 3,362 Bytes
929e441 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | import yfinance as yf
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import time
# Function to fetch historical data
def get_historical_data(ticker, interval, period):
stock_data = yf.download(ticker, interval=interval, period=period)
return stock_data
# Function to fetch real-time data
def get_realtime_data(ticker):
stock = yf.Ticker(ticker)
data = stock.history(period='7d', interval='1m')
return data
# Function to preprocess data
def preprocess_data(data):
data['returns'] = data['Close'].pct_change()
data['target'] = np.where(data['returns'] > 0, 1, 0)
data.dropna(inplace=True)
return data
# Function to train a simple model
def train_model(data):
X = data[['Open', 'High', 'Low', 'Close', 'Volume']]
y = data['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
accuracy = accuracy_score(y_test, predictions)
print(f'Model Accuracy: {accuracy}')
return model
# Function to simulate trading
def simulate_trading(model, data, initial_balance=1):
data['predicted'] = model.predict(data[['Open', 'High', 'Low', 'Close', 'Volume']])
balance = initial_balance
positions = 0
for i in range(len(data)-1):
if data['predicted'].iloc[i] == 1:
# Buy
positions += balance / data['Close'].iloc[i]
balance = 0
else:
# Sell
balance += positions * data['Close'].iloc[i]
positions = 0
# Sell remaining positions at the last data point
balance += positions * data['Close'].iloc[-1]
return balance
# Function to plot real and predicted data
def plot_data(data):
plt.figure(figsize=(10, 6))
plt.plot(data['Close'], label='Real Data', color='blue')
plt.scatter(data.index, data['Close'], c=data['predicted'], cmap='coolwarm', marker='o', label='Predicted Data')
plt.title('Real vs Predicted Data')
plt.xlabel('Date')
plt.ylabel('Closing Price')
plt.legend()
plt.show()
# Main function
def main():
ticker = 'AAPL' # You can change this to the desired stock symbol
# Fetch real-time data every 1 minute for the last 1 day
data = get_realtime_data(ticker)
# Preprocess data
data = preprocess_data(data)
model = train_model(data)
while True:
# Fetch real-time data every 1 minute
new_data = get_realtime_data(ticker)
# Update the existing data with new data
data = pd.concat([data, new_data])
# Preprocess data
data = preprocess_data(data)
# Simulate trading
final_balance = simulate_trading(model, data)
# Print current balance
print(f'Current Balance: {final_balance:.2f} Rupees')
# Plot real and predicted data
plot_data(data)
# Wait for 1 minute before fetching new data
time.sleep(60)
if __name__ == "__main__":
main() |