# 完整示例

双均线策略:

def init(context):
    context.stock = "000001.SZ"
    set_benchmark("000300.SH")
    set_commission(open_commission=0.0003, close_commission=0.0003, close_tax=0.001)
    run_daily(trade, time_rule="every_bar")


def trade(context, bar_dict):
    hist = attribute_history(context.stock, 20, "1d", ["close"])
    if len(hist) < 20:
        return

    close = hist["close"]
    ma5 = close.tail(5).mean()
    ma20 = close.tail(20).mean()
    price = bar_dict[context.stock].close

    has_position = context.stock in context.portfolio.positions

    if ma5 > ma20 and not has_position:
        order_value(context.stock, context.portfolio.available_cash)
        log.info("buy %s price=%s", context.stock, price)
    elif ma5 < ma20 and has_position:
        order_target(context.stock, 0)
        log.info("sell %s price=%s", context.stock, price)

    record(price=price, ma5=ma5, ma20=ma20)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27