Best free ai video generator : Synthesia
Best free ai audio generator.(realistic speech in your language) : Elevenlabs
bash
pip install yfinance scikit-learn pandas numpy ta-lib
python
import yfinance as yf
import pandas as pd
# Get historical stock data for Apple (AAPL)
stock_data = yf.download("AAPL", start="2020-01-01", end="2023-01-01")
print(stock_data.head())
python
import talib as ta
# Adding a 50-period moving average to the dataset
stock_data['SMA50'] = ta.SMA(stock_data['Close'], timeperiod=50)
stock_data['SMA200'] = ta.SMA(stock_data['Close'], timeperiod=200)
python
# Calculate the target: 1 if the stock price increased the next day, 0 otherwise
stock_data['Target'] = (stock_data['Close'].shift(-1) > stock_data['Close']).astype(int)
# Drop rows with NaN values
stock_data.dropna(inplace=True)
# Select features and labels
features = ['Close', 'SMA50', 'SMA200']
X = stock_data[features]
y = stock_data['Target']
python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Split data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train a Random Forest model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")
python
# Predict whether the stock will go up or down tomorrow
latest_data = stock_data.iloc[-1][features].values.reshape(1, -1)
predicted = model.predict(latest_data)
if predicted == 1:
print("Buy signal: The stock is likely to go up.")
else:
print("Sell signal: The stock is likely to go down.")
python
# Simulating trading strategy
capital = 10000 # Start with $10,000
shares = 0
for i in range(len(stock_data) - 1):
if model.predict([stock_data[features].iloc[i]]) == 1 and capital >= stock_data['Close'].iloc[i]:
# Buy the stock
shares = capital // stock_data['Close'].iloc[i]
capital -= shares * stock_data['Close'].iloc[i]
print(f"Buying at {stock_data['Close'].iloc[i]} on {stock_data.index[i]}")
elif model.predict([stock_data[features].iloc[i]]) == 0 and shares > 0:
# Sell the stock
capital += shares * stock_data['Close'].iloc[i]
shares = 0
print(f"Selling at {stock_data['Close'].iloc[i]} on {stock_data.index[i]}")
# Final capital after simulation
print(f"Final capital: ${capital + shares * stock_data['Close'].iloc[-1]:.2f}")