python
import yfinance as yf
import pandas as pd
import pandas_ta as ta
import numpy as np
class QuantitativeTradingSystem:
def __init__(self, stock_code, start_date='2000-01-01', end_date='2021-12-31', short_window=20, long_window=50):
self.stock_code = stock_code
self.start_date = start_date
self.end_date = end_date
self.short_window = short_window
self.long_window = long_window
self.data = self.fetch_data()
def fetch_data(self):
data = yf.download(self.stock_code, start=self.start_date, end=self.end_date)
return data
def simple_moving_average(self):
self.data['SMA_short'] = ta.sma(self.data['Close'], self.short_window)
self.data['SMA_long'] = ta.sma(self.data['Close'], self.long_window)
self.data['Signal'] = 0
self.data.loc[self.data['SMA_short'] > self.data['SMA_long'], 'Signal'] = 1
self.data.loc[self.data['SMA_short'] < self.data['SMA_long'], 'Signal'] = -1
def backtest(self):
self.data['Daily_Return'] = np.log(self.data['Close'] / self.data['Close'].shift(1))
self.data['Strat_Return'] = self.data['Daily_Return'] * self.data['Signal'].shift(1)
strat_cumulative_return = self.data['Strat_Return'].cumsum()
benchmark_cumulative_return = self.data['Daily_Return'].cumsum()
return {'strat_cumulative_return': strat_cumulative_return,
'benchmark_cumulative_return': benchmark_cumulative_return}
def run(self):
self.simple_moving_average()
results = self.backtest()
return results
if __name__ == '__main__':
trading_system = QuantitativeTradingSystem('AAPL')
results = trading_system.run()
print('策略累计收益率: ', results['strat_cumulative_return'][-1])
print('基准累计收益率: ', results['benchmark_cumulative_return'][-1])