This project explores the relationship between news sentiment and stock price movements, specifically focusing on Tesla (TSLA). It uses Natural Language Processing (NLP) techniques to analyze news articles and a neural network to predict sentiment, which is then used in a simulated trading strategy.
This project combines financial data analysis with NLP to create a system that simulates trading Tesla stock based on the sentiment expressed in news articles. The workflow involves:
- Data Acquisition: Gathering historical Tesla stock prices using
yfinanceand news articles related to Tesla using the NewsAPI. - Data Preprocessing: Cleaning and preprocessing the text data using techniques like removing HTML tags, stop words, and applying lemmatization.
- Sentiment Analysis: Calculating sentiment scores using VADER (Valence Aware Dictionary and sEntiment Reasoner) and training a neural network on TF-IDF and Word2Vec features.
- Trading Simulation: Implementing a basic trading strategy that buys or sells Tesla stock based on the predicted sentiment and a set of predefined rules.
- Performance Evaluation: Evaluating the trading strategy's performance by calculating metrics such as total gain/loss and percentage return and visualizing the account balance over time.
- News Data Collection: Automated fetching of Tesla-related news articles from the NewsAPI.
- Text Preprocessing: Robust text cleaning and preprocessing pipeline.
- Sentiment Analysis: Sentiment scoring using VADER and a trained neural network.
- Feature Engineering: TF-IDF and Word2Vec feature extraction for text representation.
- Neural Network Classification: Multi-Layer Perceptron (MLP) for sentiment classification.
- Backtesting Framework: Simulation of a trading strategy based on news sentiment.
- Performance Metrics: Calculation of key trading metrics and visualization of account balance.
- Risk Analytics: Exports max drawdown, volatility, Sharpe-like score, win rate, profit factor, and round-trip PnL stats to
risk_metrics.csv. - Improved Backtest Realism: Includes transaction fees, position limits, cooldown logic, stop-loss/take-profit exits, and benchmark alpha vs buy-and-hold.
- Modular Backtest Engine: Trading and risk logic moved into
trading_utils.pyfor easier reuse and testing. - Project Quality: Added
requirements.txt,.gitignore, unit tests, and GitHub Actions CI.
- Python
- yfinance
- NewsAPI
- nltk
- gensim
- scikit-learn
- PyTorch
- pandas
- matplotlib
-
Clone the repository:
git clone [invalid URL removed]
-
Navigate to the project directory:
cd StockSentimentTrading -
Install the required packages:
pip install -r requirements.txt
Create a
requirements.txtfile with the following contents:newsapi-python gensim yfinance scikit-learn torch pandas matplotlib nltk transformers accelerate bitsandbytes -
You will need to download the Google News Word2Vec model and store it in your Google Drive. Then, mount your drive in the Colab notebook.
-
Set your NewsAPI key as an environment variable:
export NEWSAPI_KEY="your_newsapi_key_here"
Run the main script:
python your_script_name.py # Replace your_script_name.py with the actual name of your script.For this repository:
python "Stock-Sentiment-Trading-with-News-Analysis.py"Run tests:
python -m pytest -q- Fetch stock and news data.
- Preprocess the text data and perform sentiment analysis.
- Train the neural network models.
- Simulate the trading strategy.
- Print performance metrics and generate a balance plot.
The script will output performance metrics like total gain/loss, percentage return, and a plot of the account balance over time. It will also generate classification reports for the sentiment analysis models.
This project is for educational purposes only. Trading stocks based on sentiment analysis is highly risky, and past performance is not indicative of future results. Do not use this project for actual financial trading without consulting a qualified financial advisor.
##Future Improvements Explore more sophisticated trading strategies. Implement different sentiment analysis models or fine-tune existing ones. Incorporate other financial indicators or market data. Develop a more robust backtesting framework with transaction costs and slippage. Deploy the system as a web application or API.