以下是一个简单的量化交易系统框架的Python代码示例:

import pandas as pd
import numpy as np

class QuantitativeTradingSystem:
    def __init__(self):
        self.data = None
        self.signals = None
        self.positions = None
        self.current_position = None
        self.capital = 1000000
    
    def load_data(self, filename):
        self.data = pd.read_csv(filename)
    
    def calculate_signals(self):
        # 信号生成算法,根据数据计算交易信号
        self.signals = pd.DataFrame(index=self.data.index)
        self.signals['signal'] = np.where(self.data['close'] > self.data['ma'], 1, -1)
    
    def generate_positions(self):
        # 根据信号生成仓位
        self.positions = pd.DataFrame(index=self.signals.index).fillna(0.0)
        self.positions['position'] = self.signals['signal'].diff()
    
    def backtest(self):
        # 回测算法,模拟交易并计算收益
        self.current_position = pd.DataFrame(index=self.positions.index).fillna(0.0)
        self.current_position['position'] = self.positions['position']
        self.current_position['close'] = self.data['close']
        self.current_position['holdings'] = self.current_position['position'].cumsum() * self.current_position['close']
        self.current_position['cash'] = self.capital - (self.current_position['position'] * self.current_position['close']).cumsum()
        self.current_position['total'] = self.current_position['cash'] + self.current_position['holdings']
    
    def plot_results(self):
        # 绘制回测结果图表
        import matplotlib.pyplot as plt
        fig = plt.figure()
        ax1 = fig.add_subplot(111, ylabel='Portfolio value in $')
        self.current_position['total'].plot(ax=ax1, lw=2.)
        ax1.plot(self.current_position.loc[self.current_position.position == 1.0].index,
                 self.current_position.total[self.current_position.position == 1.0],
                 '^', markersize=10, color='g')
        ax1.plot(self.current_position.loc[self.current_position.position == -1.0].index,
                 self.current_position.total[self.current_position.position == -1.0],
                 'v', markersize=10, color='r')
        plt.show()
    
    def run(self, filename):
        self.load_data(filename)
        self.calculate_signals()
        self.generate_positions()
        self.backtest()
        self.plot_results()

使用示例:

if __name__ == '__main__':
    trading_system = QuantitativeTradingSystem()
    trading_system.run('data.csv')

在上述代码中,load_data方法用于加载数据,calculate_signals方法用于根据数据计算交易信号,generate_positions方法用于根据信号生成仓位,backtest方法用于模拟交易并计算收益,plot_results方法用于绘制回测结果图表。run方法是整个系统的入口,用于运行整个量化交易系统


原文地址: https://www.cveoy.top/t/topic/hZpX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录