Programming lesson
Building a Stock Investment Strategy with Java and MySQL: A Step-by-Step Database Tutorial
Learn how to build a Java program that connects to a MySQL database of stock prices, adjusts for stock splits, and implements a moving average trading strategy. Perfect for CSCI 330 students.
Introduction: Why Database Skills Matter for Stock Trading
In today's data-driven world, stock market analysis relies heavily on databases. Whether you're building a trading bot for AI-driven apps or analyzing historical data for finance homework, knowing how to query and process data efficiently is crucial. This tutorial guides you through building a Java program that connects to a MySQL database, retrieves stock price data, adjusts for stock splits, and implements a simple moving average trading strategy. By the end, you'll understand how to apply database programming concepts to real-world stock investment strategies.
Setting Up the Database Connection
Before any analysis, you need to connect Java to a MySQL database. In this assignment, you'll use an external file ConnectionParameters.txt to store credentials. This approach enhances security and makes testing easier—you can switch between lab and home environments without recompiling code.
ConnectionParameters.txt Example
dburl=jdbc:mysql://mysql.cs.wwu.edu/johnson330
user=your_user_name
password=your_password_we_providedFor off-campus access, set up SSH tunneling and change the URL to jdbc:mysql://127.0.0.1:4321/johnson330. Always ensure no extra blank lines at the end of the file.
Understanding the Database Schema
The database contains two main tables: company and pricevolume. The company table holds ticker symbols, names, and industry info. The pricevolume table stores daily open, high, low, close prices, volume, and adjusted close. For this stock data analysis, you'll primarily query pricevolume ordered by date descending.
Step-by-Step Processing Logic
1. Connect and Accept User Input
Your program loops, asking for a ticker symbol and optional date range. Exit when user enters an empty string. This interactive loop is common in Java database projects.
2. Retrieve Company Name
Query the company table for the given ticker. If not found, print an error and prompt again. This validates input early.
3. Fetch Price Data
Retrieve all pricevolume rows for the ticker within the date range (or all if no dates). Use ORDER BY TransDate DESC to get data in reverse chronological order—essential for split detection.
4. Detect and Adjust for Stock Splits
Stock splits affect historical prices. For example, a 2:1 split means each share becomes two, halving the price. To compare prices consistently, you must adjust historical data. The algorithm scans data backwards, checking ratios of consecutive closing and opening prices:
- 2:1 split if |Cx / Ox+1 – 2.0| < 0.20
- 3:1 split if |Cx / Ox+1 – 3.0| < 0.30
- 3:2 split if |Cx / Ox+1 – 1.5| < 0.15
Maintain a cumulative divisor (starting at 1). When a split is detected, multiply the divisor by the split ratio (2, 3, or 1.5). Then divide all prices (open, high, low, close) for that day and earlier by the new divisor. This ensures all data is adjusted in one pass.
5. Implement the Moving Average Strategy
After adjustments, scan data forward. Compute a 50-day moving average of closing prices. Starting from day 51, apply these rules:
- Buy signal: If close(d) < 50-day average AND close(d) is at least 3% below open(d), buy shares (borrow money if needed).
- Sell signal: If close(d) > 50-day average AND close(d) is at least 3% above open(d), sell all shares.
Track cash and shares. At the end, compute net gain/loss. If fewer than 51 days, report zero gain.
Practical Example: Analyzing Apple (AAPL)
Imagine you run the program with ticker AAPL and get historical data. The algorithm detects a 2:1 split in 2020 and adjusts earlier prices. Then it computes the 50-day average and generates buy/sell signals. This kind of quantitative trading strategy is used in hedge funds and AI trading bots today.
Connecting to Current Trends
In 2026, AI-driven stock analysis is huge. Apps like Robinhood and Webull use similar algorithms to suggest trades. Understanding how to code a stock investment strategy in Java gives you an edge in finance internships and data science careers. Plus, with gamification of trading (e.g., leaderboards, challenges), these skills are more relevant than ever.
Common Pitfalls and Tips
- SQL Injection: Use
PreparedStatementto avoid security holes. - Date Handling: Parse user input carefully; use
java.sql.Date. - Precision: Use
doublefor prices but beware of rounding errors. - Testing: Test with known split dates (e.g., AAPL 2020 split) to verify adjustments.
Conclusion
This tutorial walked you through building a Java program that connects to a MySQL database, adjusts stock data for splits, and implements a moving average strategy. By mastering these steps, you'll be able to tackle similar database assignments and even build your own trading algorithm. Remember, the key is to break the problem into small, manageable steps—connect, fetch, adjust, analyze. Happy coding!