创业板ETF天弘
由bq0r1l32创建,最终由bq0r1l32 被浏览 54 用户
import pandas_datareader as pdr
获取股票数据
stock_data = pdr.get_data_yahoo('股票代码', start='2010-01-01', end='2020-12-31')
计算30日均线和72日均线
stock_data['MA30'] = stock_data['Close'].rolling(30).mean() stock_data['MA72'] = stock_data['Close'].rolling(72).mean()
计算平均数为基准价
stock_data['Avg'] = (stock_data['MA30'] + stock_data['MA72']) / 2
初始化持仓状态和收益
position = False profit = 0
遍历每个交易日
for i in range(len(stock_data)-1):
# 如果股价下跌超过20%
if (stock_data['Close'][i+1] / stock_data['Avg'][i+1]) < 0.8:
# 如果未持仓,买入股票
if not position:
# 等待股价反弹5%
buy_price = 0
for j in range(i+1, len(stock_data)-1):
if (stock_data['Close'][j+1] / stock_data['Close'][i+1]) > 1.05:
buy_price = stock_data['Close'][j+1]
break
# 如果股价反弹达到5%,买入股票
if buy_price > 0:
position = True
profit -= buy_price
print('买入股票,价格为:', buy_price)
# 如果股价上涨超过15%
elif (stock_data['Close'][i+1] / stock_data['Avg'][i+1]) > 1.15:
# 如果持仓,卖出股票
if position:
# 等待股价回落6%
sell_price = 0
for j in range(i+1, len(stock_data)-1):
if (stock_data['Close'][j+1] / stock_data['Close'][i+1]) < 0.94:
sell_price = stock_data['Close'][j+1]
break
# 如果股价回落达到6%,卖出股票
if sell_price > 0:
position = False
profit += sell_price
print('卖出股票,价格为:', sell_price)
print('最终收益为:', profit)