我做了个红利的网格交易,但是运行后一笔都没买,请问大神

用户头像赖皮熊
2025-04-21 发布

我做了个红利的网格交易,但是运行后一笔都没买,请问大神问题出在哪里

导入必要的模块

import datetime

模拟的交易环境类

class BacktestEnvironment:
def init(self, initial_cash, prices):
self.cash = initial_cash
self.positions = 0 # 持仓数量
self.prices = prices # 历史价格列表
self.current_step = 0
self.base_price = prices[0] if prices else 0
self.grid_upper = self.base_price * 1.03 # 上轨:基准价 +3%
self.grid_lower = self.base_price * 0.97 # 下轨:基准价 -3%

def get_current_price(self):
if self.current_step < len(self.prices):
return self.prices[self.current_step]
return None

def order(self, quantity):
price = self.get_current_price()
if price is None:
return
cost = price * quantity
if quantity > 0:
# 买入
if self.cash >= cost:
self.cash -= cost
self.positions += quantity
print(f"买入 {quantity} 股,价格:{price:.2f},剩余现金:{self.cash:.2f}")
else:
print(f"现金不足,无法买入 {quantity} 股")
elif quantity < 0:
# 卖出
if self.positions >= abs(quantity):
self.positions += quantity # 数量为负,表示卖出
self.cash += cost
print(f"卖出 {-quantity} 股,价格:{price:.2f},剩余现金:{self.cash:.2f}")
else:
print(f"持仓不足,无法卖出 {-quantity} 股")
# 更新网格上下轨
self.grid_upper = self.base_price * 1.03
self.grid_lower = self.base_price * 0.97

def next(self):
self.current_step += 1
if self.current_step < len(self.prices):
self.grid_upper = self.base_price * 1.03
self.grid_lower = self.base_price * 0.97
current_price = self.get_current_price()
if current_price is None:
return

    # 卖出逻辑
    if current_price >= self.grid_upper and self.positions > 0:
        sell_quantity = self.positions  # 全部卖出
        self.order(-sell_quantity)

    # 买入逻辑
    elif current_price <= self.grid_lower and self.cash > current_price:
        buy_quantity = int(self.cash / current_price)
        buy_quantity = min(buy_quantity, 100)  # 最多买入100股
        if buy_quantity > 0:
            self.order(buy_quantity)

else:
    print("回测结束")

def run(self):
while self.current_step < len(self.prices):
self.next()

模拟数据生成函数

def generate_mock_prices(start_price, days, volatility=0.01):
"""
生成模拟的每日收盘价数据。
:param start_price: 起始价格
:param days: 模拟天数
:param volatility: 波动率
:return: 价格列表
"""
prices = [start_price]
for _ in range(days - 1):
daily_return = (np.random.rand() - 0.5) * 0.02 # -1% 到 +1% 的波动
next_price = prices[-1] * (1 + daily_return)
prices.append(round(next_price, 2))
return prices

由于避免使用第三方库,这里简化模拟数据的生成

def generate_mock_prices_simple(start_price, days):
"""
简单生成每日递增或递减的价格,用于模拟。
:param start_price: 起始价格
:param days: 模拟天数
:return: 价格列表
"""
prices = [start_price]
current_price = start_price
for _ in range(days):

模拟每日价格波动(简单涨1%或跌1%)

change = 0.01 if random.choice([True, False]) else -0.01
current_price *= (1 + change)
current_price = round(current_price, 2)
prices.append(current_price)
return prices

主函数

def main_no_third_party():
import random # 仅在生成模拟数据时使用,不涉及策略逻辑

初始资金

initial_cash = 100000 # 10万元

模拟运行天数

days = 20

初始价格

start_price = 1.0 # 假设初始价格为1元

简单的价格生成(固定涨跌)

prices = []
current_price = start_price
for _ in range(days):
# 模拟每日价格波动(简单涨1%或跌1%)
change = 0.01 if random.choice([True, False]) else -0.01
current_price *= (1 + change)
current_price = round(current_price, 2)
prices.append(current_price)

创建回测环境

env = BacktestEnvironment(initial_cash, prices)

设置基准价格(这里简单地使用初始价格)

env.base_price = start_price
env.grid_upper = env.base_price * 1.03
env.grid_lower = env.base_price * 0.97

运行回测

env.run()

回测结果

final_cash = env.cash
final_positions = env.positions
total_value = final_cash + final_positions * env.prices[-1]
print(f"回测结束,最终现金:{final_cash:.2f},持仓数量:{final_positions},总价值:{total_value:.2f}")
if name == "main":
main_no_third_party()

评论

需要帮助?

试试AI小助手吧