```python
# 导入函数库
from jqdata import \*
'''
阅读API文档中Context对象,了解下其中的结构与内容。
写一个策略,内容为在20180301买入一个股票,在20180321卖出一个股票。股票可以自己定。
试着根据止损的例子实现止盈,即指当盈利达到一定幅度后下单卖出股票。
写一个自定义函数,功能是判断一个年份是否是闰年。闰年定义为:普通年(不能被100整除的年份)能被4整除的为闰年。(如2004年就是闰年,1999年不是闰年);世纪年(能被100整除的年份)能被400整除的是闰年。(如2000年是闰年,1900年不是闰年);【提示:利用取余运算(%)判断是否整除】
'''
def initialize(context):
\# 设定沪深300作为基准
set\_benchmark('000300.XSHG')
\# 开启动态复权模式(真实价格)
set\_option('use\_real\_price', True)
g.security = '000007.XSHE'
run_daily(demo2,time='every_bar')
def isLeapYear(year):
if year % 4 == 0:
return True;
else:
return False;
# 在 2028-03-01 买入 2018-03-21 卖出
def demo1(context):
security = g.security
```
date = context.current_dt.strftime("%Y-%m-%d")
if date == "2018-03-01":
order(security, 1000);
elif date == "2018-03-21":
order_target(security, 0)
```
# 在盈利 10 % 后卖出股票
def demo2(context):
security = g.security
date = context.current_dt.strftime("%Y-%m-%d")
#2018-03-01 买入股票
if date == "2019-03-01":
order(security,1000)
# 没有持仓跳过流程
elif len(context.portfolio.positions.values()) == 0:
return
#成本价
avg_cost = context.portfolio.positions[security].avg_cost
#现价
price = context.portfolio.positions[security].price
#盈利率
rate = 0
if avg_cost > 0:
rate = price / avg_cost - 1
if rate >= 0.10:
print("触发止盈")
print("成本价%s" % avg_cost)
print("现价%s" % price)
print("当前日期%s" % date)
order_target(security, 0)
```
1天前