请帮忙基于tushare的数据用python代码写一个马钉策略
时间: 2024-02-06 10:12:13 浏览: 177
基于python对tushare股票数据进行数据分析
好的,以下是基于tushare的数据用Python代码实现马钉策略的示例:
```python
import tushare as ts
# 设置tushare token
ts.set_token('your_tushare_token')
# 初始化tushare pro接口
pro = ts.pro_api()
# 获取股票代码和名称
def get_code_name():
data = pro.stock_basic()
code_name = dict(zip(data['ts_code'], data['name']))
return code_name
# 实现马钉策略
def mati_strategy(code, start_date, end_date):
# 获取股票数据
df = pro.daily(ts_code=code, start_date=start_date, end_date=end_date)
# 计算MA5和MA30
df['ma5'] = df['close'].rolling(5).mean()
df['ma30'] = df['close'].rolling(30).mean()
# 判断是否出现马钉形态
df['cond1'] = (df['ma5'] > df['ma30']) & (df['ma5'].shift(1) < df['ma30'].shift(1))
df['cond2'] = (df['ma5'] < df['ma30']) & (df['ma5'].shift(1) > df['ma30'].shift(1))
df['mati'] = df['cond1'] | df['cond2']
# 计算持仓和收益
position = 0
profit = 0
for i in range(len(df)):
if df['mati'].iloc[i]:
if position == 0:
# 买入
position = 1
buy_price = df['open'].iloc[i]
elif position == 1:
# 卖出
position = 0
sell_price = df['open'].iloc[i]
profit += sell_price - buy_price
return profit
# 测试策略
if __name__ == '__main__':
# 获取股票代码和名称
code_name = get_code_name()
# 选择一只股票进行测试
code = '600519.SH'
name = code_name[code]
# 设置回测时间区间
start_date = '20180101'
end_date = '20211231'
# 进行马钉策略回测
profit = mati_strategy(code, start_date, end_date)
# 输出结果
print('{}马钉策略收益为:{:.2f}'.format(name, profit))
```
在上述代码中,我们通过`tushare`库获取股票的历史行情数据,并计算出MA5和MA30两条均线。随后,我们判断是否出现马钉形态,当MA5和MA30交叉时,即判断为出现马钉形态。最后,我们根据马钉形态进行买入和卖出操作,并计算出总收益。
需要注意的是,该示例中没有考虑交易成本等因素,实际交易中需要加以考虑。同时,投资有风险,交易需谨慎。
阅读全文