Below is a simplified version of a stock simulation trading system implemented in Python. This system allows users to simulate buying and selling stocks based on historical data. It includes functionalities such as retrieving stock data, simulating trades, and evaluating the performance of the trading strategy. Note that this code is for educational purposes and may require additional features and error handling for production use.
```python
import yfinance as yf
import pandas as pd
class StockSimulationSystem:
def __init__(self, start_date, end_date):
self.start_date = start_date
self.end_date = end_date
self.portfolio = {}
def get_stock_data(self, ticker):
data = yf.download(ticker, start=self.start_date, end=self.end_date)
return data
def buy_stock(self, ticker, quantity):
if ticker not in self.portfolio:
self.portfolio[ticker] = quantity
else:
self.portfolio[ticker] = quantity
def sell_stock(self, ticker, quantity):
if ticker in self.portfolio:
if self.portfolio[ticker] >= quantity:
self.portfolio[ticker] = quantity
else:
print("Error: Not enough shares to sell.")
else:
print("Error: Stock not found in portfolio.")
def evaluate_portfolio(self):
total_value = 0
for ticker, quantity in self.portfolio.items():
data = self.get_stock_data(ticker)
latest_price = data['Adj Close'].iloc[1]
total_value = latest_price * quantity
return total_value
Example usage:
if __name__ == "__main__":
Initialize simulation system
start_date = '20230101'
end_date = '20240101'
system = StockSimulationSystem(start_date, end_date)
Simulate buying and selling stocks
system.buy_stock('AAPL', 10)
system.buy_stock('MSFT', 5)
system.sell_stock('AAPL', 3)
Evaluate portfolio performance
portfolio_value = system.evaluate_portfolio()
print("Portfolio value:", portfolio_value)
```
This code utilizes the `yfinance` library to fetch historical stock data from Yahoo Finance. The `StockSimulationSystem` class provides methods to buy and sell stocks, as well as evaluate the portfolio's current value based on the latest available stock prices.
To use this code:
1. Ensure you have `yfinance` installed (`pip install yfinance`).
2. Replace `'AAPL'` and `'MSFT'` with the desired stock tickers.
3. Set the `start_date` and `end_date` to specify the time range for the simulation.
4. Adjust the quantity of stocks bought and sold as needed.
5. Run the script to simulate the trading and evaluate the portfolio's performance.
Remember, this is a basic implementation. For a more robust system, consider adding features such as transaction costs, risk management, and support for different trading strategies. Additionally, ensure proper error handling and data validation for realworld applications.