量化交易是指将计算机程序和系统性交易策略结合起来,使用数学模型和统计分析,The process of automatically determining the timing of trading through algorithms and automatically executing transactions.
量化交易具有高效性、精确性和纪律性的特点,能够在瞬间完成决策并执行交易,Reduce human intervention and improve the accuracy and stability of trading decisions.
量化策略主要依赖于计算机算法进行交易。
投资者将初步的交易逻辑输入计算机,并运用大量的历史数据做统计和回测,在此基础上做出适当的修改、扬弃,以形成可接受的交易策略。策略在形成后,往往各个决策条件就已经确定,实盘中按照既定的程序执行。
#coding:utf-8
import os,sys
import pandas as pd
import numpy as np
import math
#写一个趋势跟踪策略量化交易程序
if len(sys.argv)==2:
code=sys.argv[1]
else:
print('usage:python ma20_ma60.py stockcode')
sys.exit(1)
if len(code)!=6:
print('stock code length:6')
sys.exit(2)
df=pd.read_csv(f'{code}.csv')
#计算移动平均线
df['ma20']=df['close'].rolling(window=20).mean()
df['ma60']=df['close'].rolling(window=60).mean()
df=df[df['date']>'2020-01-01']
cost=100000
cash=cost
stock=0
fee=0.0005
for index,row in df.iterrows():
if row['ma20']>row['ma60']and stock==0:
date=row['date']
price=row['close']
stock=math.floor(cash(1-fee)/price/100)100
cash=cash-stockprice(1+fee)
print(f'{date}:cash={cash:.2f},stock={stock}x{price:.2f}')
#如果短期移动平均线下穿长期移动平均线,则卖出
elif row['ma20']<row['ma60']and stock>0:
date=row['date']
price=row['close']
cash=cash+stockprice(1-fee)
stock=0
print(f'{date}:cash={cash:.2f},stock={stock}x{price:.2f}')
#计算最终收益
price=df.iloc[-1]['close']
profit=cash+stock*price-cost
print(f'profit={profit:.2f},stock={stock}x{price:.2f}')