Quantitative trading strategy design and backtesting

With akshare's dataset, we can use historical data to design simple strategies and backtest them.

The simplest strategy: buy when it's down and sell when it's up.

Install

!pip3 install akshare --upgrade # 这是akshare的
import pandas as pd
import akshare as ak

Import Data

data = ak.fund_etf_fund_info_em('510210','20230101','20230331')
data

operation result:


Filter the data to use

df = data[['净值日期','单位净值']]
df

 


Calculate the rise and fall from the previous trading day

# 计算每日价格涨跌额
df['diff'] = df['单位净值'].diff()
df.head()


Judging whether to trade daily

# 如果上涨,则交易信号为1,代表卖出;否则交易信号为0,代表买入
import numpy as np
df['Signal'] = np.where(df['diff']>0,1,0)
df

 


Visualize the above data

import matplotlib.pyplot as plt
df['单位净值'].plot()
plt.scatter(df['单位净值'].loc[df.Signal==1].index,df['单位净值'][df.Signal==1],marker='v',c='g')
plt.scatter(df['单位净值'].loc[df['Signal']==0].index,df['单位净值'][df['Signal']==0],marker='^',c='r')

 


Calculate whether to buy or sell each day based on buy and sell signals

# 计算每天买卖多少手
df['order'] = df['Signal'].diff()*100 
df = df.fillna(0.0) # 填补空值
df.head(30)

The minimum trading unit is 1 lot, 1 lot is equal to 100 shares


backtest

# 回测
initial_cash = 100 # 本金
df['stock'] = df['order']*df['单位净值']
df['cash'] = initial_cash- (df['order'].diff()*df['单位净值']).cumsum()
df['total'] = df['stock'] + df['cash']
df.head(30)

Unit net value: refers to the market value of the stock. Generally, stocks are sold at the minimum of 1 lot, and 1 lot is 100. The unit net value is the price of 1/100 lot.

Number of shares in order: one lot is equal to 100 shares.

The market value of each stock transaction: refers to how much it costs to buy 1 lot, which is equal to 100 shares multiplied by the net value of the unit.

Cash balance: For example, if the total warehouse is 100 yuan, the cash balance refers to the principal that has not been spent, which is equal to the total principal minus the market value.

total total assets = stock market value + cash balance.

The calculation results show that this simple strategy can obtain a 2% rate of return in this market.


Visualization of positions and returns

# 绘出回测的总资产变化
plt.plot(df['total'])
plt.plot(df['order'].cumsum()*df['单位净值'],'--')

 

Guess you like

Origin blog.csdn.net/Sukey666666/article/details/129905970