2、
答:
context中主要是一个对象,
portfolio账户信息属性对象
current_dt 时间类型
run_params 对象
universe
3、写一个策略,内容为在20180301买入一个股票,在20180321卖出一个股票。股票可以自己定。
答:
def initialize(context):
# 定义执行内置函数,可以传入函数不用括号,第二个参数是每天,也可以open每天开盘时执行一次,close每天收盘时执行一次
run_daily(period, time='every_bar')
# 所有代码顶格写,不要加前面的空格
def period(context):
# 获取当前的开始时间调用方法转化为年月日
date=context.current_dt.strftime("%Y-%m-%d")
# 如果时间是2018年3月1日 就 调用内置函数order 下某个股票代码 100股 平安银行
if date=='2018-03-01':
order("000001.XSHE", 100)
# 或者 如果时间不是2018年3月1日 是2018年3月21日 就 调用内置函数order 卖掉某个股票代码 100股 平安银行
elif date=='2018-03-21':
order("000001.XSHE", -100)
4、试着根据止损的例子实现止盈,即指当盈利达到一定幅度后下单卖出股票。
答:2018-03-01买入平安银行,2019-03-06就实现了盈利10%卖出
def initialize(context):
# 每天执行一次策略
run_daily(period, time='every_bar')
# 设置要操作的股票
g.security = '000001.XSHE'
def period(context):
# 获取当前日期
date = context.current_dt.strftime("%Y-%m-%d")
# 1. 到了 2018-03-01 买入 100 股
if date == '2018-03-01':
order(g.security, 100)
# 2. 每天检查是否止盈
# 先判断是否持有这只股票
if g.security in context.portfolio.positions:
# 获取持仓信息
stock = context.portfolio.positions[g.security]
# 计算盈利比例:当前价格 / 买入成本价
profit_ratio = stock.price / stock.avg_cost
# 如果盈利 >= 10%,就卖出止盈
if profit_ratio >= 1.1:
# 卖出 100 股(清空)
order(g.security, -100)
print("已止盈卖出,收益率:", (profit_ratio - 1) * 100, "%")
5、
答:
闰年的普通年:能被4整除,不能被100整除的就是闰年。
2004、2008、2012、2016、2020、2024
闰年的世纪年:能被100整除,且能被400整除。
1600、2000、2400
# 定义一个判断闰年的函数,参数是年份 year
def is_leap_year(year):
# 1. 世纪年:能被100整除 → 必须再被400整除才是闰年
if year % 100 == 0:
return year % 400 == 0
# 2. 普通年:不能被100整除 → 能被4整除就是闰年
else:
return year % 4 == 0
2026-04-20