[041]量化交易]简单交易策略:当日涨幅超过3%买入,当持有股票亏损超过3%,平仓
·
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
# 导入tushare
import tushare as ts
import talib
# 当日涨幅超过3%买入。
# 当持有股票亏损超过3%,平仓
# 初始化pro接口
pro = ts.pro_api('')
# 通过股票代码获取股票数据,这里没有指定开始及结束日期
df = pro.daily(ts_code='300104.SZ', start_date='20180101', end_date='20180819')
df.sort_index(ascending=False, inplace=True)
# ascending=True为顺序排列,False为倒序,inplace一定要设置为True
print(df)
print(type(df))
print('df有行数:' + str(df.shape[1]))
print('df有列数:' + str(df.shape[0]))
print('++++++++++++++++++++')
print(df.index)
print(df.index.values)
print('++++++++++++++++++++')
# 处理数据
df.index = pd.to_datetime(df.trade_date) # 20180124转换为2018-07-18
print('*******df.index******')
print(df.index)
print('*********************')
# Pct_change是一个统计函数,用于表示当前元素与前面元素的相差百分比。
# 比如说给定三个元素[2,3,6],计算相差百分比后得到[NaN, 0.5, 1.0],从第一个元素到第二个元素增加50%,从第二个元素到第三个元素增加100%。
# 计算浮动比例
df["pchange"] = df.close.pct_change()
# # 计算浮动点数
# df["diff_change"] = df.close.diff()
# df.to_csv('vvv.csv')
# 设定回撤值
withdraw = 0.03
# 设定突破值
breakthrough = 0.03
# 设定账户资金
account = 10000
# 持有仓位手数
position = 0
def buy(bar):
global account, position
print("{}: buy {}".format(bar.trade_date, bar.close))
# 一手价格
one = bar.close * 100
position = account // one # //运算符表示向下取整除,它会返回整除结果的整数部分 print(7//2)==3
account = account - (position * one) # 买完几手剩下资金
def sell(bar):
global account, position
# 一手价格
print("{}: sell {}".format(bar.trade_date, bar.close))
one = bar.close * 100
account += position * one
position = 0
# iloc 按行取参数
print("开始时间投资时间: ", df.iloc[0].trade_date)
# loc函数:通过行索引 "Index" 中的具体值来取行数据(如取"Index"为"A"的行)
# iloc函数:通过行号来取行数据(如取第二行的数据)
for date in df.index:
bar = df.loc[date] # 取一行数据
# 浮动百分比*** and 浮动百分比大于0.03 and 仓位为0 则买入
if bar.pchange and bar.pchange > breakthrough and position == 0:
buy(bar)
elif bar.pchange and bar.pchange < withdraw and position > 0:
sell(bar)
# if 中 0、''、[]、()、{}、None、False在布尔上下文中为假;其它任何东西都为真;
print("最终可有现金: ", account)
print("最终持有市值: ", position * df.iloc[-1].close * 100)

更多推荐




所有评论(0)