import numpy as np
import pandas as pd
import feather
import quantstats as qs
import matplotlib.pyplot as plt
import time
from decimal import Decimal
# 定义一个日期解析器
date_parser = lambda x: pd.to_datetime(x, format='%Y/%m/%d')
# 读取数据
stock_code = "512890.SH"
data = pd.read_csv("D:/cfsworkfiles/myjupyternotebook/Mercury/512890.SH后复权.csv", parse_dates=['date'])
data = pd.DataFrame(data, columns=['date', 'open', 'high', 'low', 'close', 'volume'])
data.set_index('date', drop=True, inplace=True)
data.sort_index(inplace=True)
# 设置开始日期和结束日期
start_date = '2021-09-01'
end_date = '2022-01-31'
# 筛选出开始日期和结束日期范围内的数据
filtered_data = data.loc[start_date:end_date]
# 获取筛选后数据的第一个交易日的开盘价作为收盘价
first_day_close_price = filtered_data.iloc[0]['close']
print("第一个交易日的收盘价:", first_day_close_price)
# 将benchmark设置为第一个交易日的收盘价格
benchmark = first_day_close_price
price = benchmark
# 初始化总资金
total_fund = 200000
# 计算初始持仓数量
position = int(total_fund /2/ first_day_close_price)
# 计算每份资金的数量
trade_quantity = 10000/price
# 设置网格参数
grid = 0.05
print("网格度:", grid)
# 初始化买入和卖出列表
opt_b = []
opt_s = []
# 初始化资金消耗和最大资金消耗
occupy_money = Decimal(0)
max_occupy_money = Decimal(0)
left_money = total_fund - occupy_money
# 初始化总收益
total_profit = 0
# 初始化成本价
cost_price = benchmark
# 第一日买入全部资金的一半进行建仓
occupy_money = Decimal(benchmark) * Decimal(position)
print("建仓成本", occupy_money)
max_occupy_money = max(max_occupy_money, occupy_money) # 更新最大占用资金
opt_b.append([filtered_data.index[0], benchmark, position]) # 使用第一天的日期作为索引
for index, row in filtered_data.iterrows():
open_price = row['open']
high = row['high']
low = row['low']
# 如果最高价大于等于benchmark * (1+grid),则执行以benchmark * (1+grid)的价格卖出一份资金
if high >= benchmark * (1+grid):
price = benchmark * (1+grid)
if position >= trade_quantity: # 检查是否有足够的仓位进行卖出
temp = (price - benchmark) * trade_quantity
total_profit += temp # 计算总收益
opt_s.append([index, price, -trade_quantity])
benchmark = benchmark * (1+grid)
position -= trade_quantity # 更新仓位
print(index, "卖出", price, "收益", temp)
# 如果最低价小于等于benchmark * (1-grid),则执行以benchmark * (1-grid)的价格买入一份资金
elif low <= benchmark * (1-grid):
price = benchmark * (1-grid)
benchmark = benchmark * (1-grid)
position += trade_quantity # 更新仓位
occupy_money = price * trade_quantity
max_occupy_money = max(max_occupy_money, occupy_money) # 更新最大占用资金
opt_b.append([index, price, trade_quantity])
print(index, "买入", price)
# 循环结束后,检查最后一天的收盘价是否大于成本价
last_day_close_price = filtered_data.iloc[-1]['close']
cost_pice = benchmark
if last_day_close_price > cost_price:
# 计算最后一天卖出的收益
final_sell_profit = (last_day_close_price - cost_price) * position
total_profit += final_sell_profit
# 更新总收益和仓位
print(filtered_data.index[-1], "最后一天卖出", last_day_close_price, "收益", final_sell_profit)
position = 0 # 清空仓位
# 打印总收益和最大占用资金
print("总收益:", total_profit)
print("最大占用资金:", max_occupy_money)
print("仓位", position)
# 计算总收益率
total_return_rate = (Decimal(total_profit) / max_occupy_money) * 100
print("网格总收益率:", total_return_rate, "%")
#计算buy&hold收益
buy_and_hold_return = (filtered_data['close'].iloc[-1] / filtered_data['close'].iloc[0] - 1) * 100
print("持有卖出收益:", buy_and_hold_return, "%")
# 可视化买入和卖出点
df_b = pd.DataFrame(opt_b, columns=['timestamp', 'price', 'opt'])
df_b.set_index('timestamp', drop=True, inplace=True)
df_s = pd.DataFrame(opt_s, columns=['timestamp', 'price', 'opt'])
df_s.set_index('timestamp', drop=True, inplace=True)
plt.figure(figsize=(10, 5))
plt.plot(filtered_data.index, filtered_data['close'], label=stock_code, color='b')
plt.scatter(df_b.index, df_b['price'], color='r', label='Buy')
plt.scatter(df_s.index, df_s['price'], color='g', label='Sell')
plt.xlabel('日期')
plt.ylabel(stock_code)
plt.legend()
plt.title(stock_code)
plt.show()
02-03
11-29
739
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)