![]() 欢迎来到全面的回测教程!本文专为希望加深对回测及其在金融领域应用的理解的交易员、投资者和金融专业人士而设计。回测是一种重要工具,用于通过模拟历史数据的表现来评估交易策略和投资组合的表现。 在本教程中,我们将从回测的基本介绍开始,包括其定义、优点和局限性。然后,我们将更深入地研究回测过程,包括涉及的步骤以及使用的数据和工具类型。此外,我们将介绍常见的回溯测试陷阱以及如何避免它们,以及前瞻性测试和蒙特卡罗模拟等高级主题。 到本教程结束时,您将对回测有深入的了解,并能够有效地使用它来评估和优化您自己的交易策略和投资组合。那么,让我们开始吧! 导入库:
import pandas as pd 加载交易数据:
添加交易信号:现在我们将向数据框添加一列来存储交易信号。信号 1 表示买入,信号 -1 表示卖出。你应该首先有信号列表 # Create an empty list to store the signalssignals = []# Loop over the rows of the dataframe and calculate the signals based on your trading strategydf['RSI']=ta.momentum.rsi(close=df['close'], window=14,fillna= True)df['ADX']=ta.trend.adx(high=df['high'] ,low=df['low'],close=df['close'], window=14, fillna= True)for i in range(1, len(df)): # Your trading strategy goes here # For example, you could use a simple moving average crossover strategy if df.iloc[i]['RSI'] > df.iloc[i]['ADX']: signals.append(-1) else: signals.append(1)# Add the signals list to the dataframe as a new columndf['signal'] = signals
循环交易信号:
for i in range(0, len(df)): signal = df.iloc[i]['signal'] close = df.iloc[i]['close'] if signal == 1 and not is_invested: Entrypoint = close print(signal) print(close) quantity = (current_investment / close) print(current_investment) print(quantity) invested_amount = quantity * close is_invested = True elif signal == -1 and is_invested: print(signal) print(close) profit = quantity * (close - Entrypoint) - 2 print(profit) current_investment += profit invested_amount = 0 total_trades += 1 is_invested = False if profit > largest_gain: largest_gain = profit if profit < largest_loss: largest_loss = profit if profit > best_trade: best_trade = profit if profit < worst_trade: worst_trade = profit else: pass final_profit = current_investment - investmentprint('Final Profit: ', final_profit)print('Best Trade: ', best_trade)print('Worst Trade: ', worst_trade)print('Largest Loss: ', largest_loss)print('Largest Gain: ', largest_gain)print('Total Trades: ', total_trades) 就是这样!我们已经使用 Python 成功地为一个简单的交易策略创建了一个回溯测试框架。 ![]() |
|