我们继续以下面这个简单的策略示例来学习在策略中操作多个标的。
def initialize(context):
context.security = 'BTC/USDT.binance'
context.myaccount = context.get_account('myaccount')
def handle_data(context):
current_price = context.get_price(context.security)
context.myaccount.buy(context.security, current_price, 0.1)
用list数据类型存储多个标的 比如下面这样就是在操作两个标的
def initialize(context):
context.security1 = 'BTC/USDT.binance'
context.security2 = 'ETH/USDT.binance'
context.myaccount = context.get_account('myaccount')
def handle_data(context):
current_price1 = context.get_price(context.security1)
context.myaccount.buy(context.security1, current_price1, 0.1)
current_price2 = context.get_price(context.security2)
context.myaccount.buy(context.security2, current_price2, 0.1)
显然的问题是当标的比较多的时候就要写很多遍,很麻烦。因此我们要学习其他的写法,首先我们先学习用list数据类型来存储多个标的,如下:
def initialize(context):
context.securities = ['BTC/USDT.binance','ETH/USDT.binance']
context.myaccount = context.get_account('myaccount')
循环语句
for循环可以遍历任何序列的项目,比如一个list,一般用法如下:
for 变量 in 一个序列:
循环体
说起来复杂,其实很简单,来看个例子:
for k in ['kelvin','david','cherry','jason']:
print(k)
执行后日志如下:
kelvin david cherry jason
可见,for语句的运行过程是,取出list中第一个元素'kelvin'并将其赋值给k,然后执行print(k)即在日志中打印k,此时k中是'kelvin',之后,取出list中第二个元素'david'并将其赋值给k,然后执行print(k)即在日志中打印k,此时k中是'david',以此类推,直到'jason'被打印。
写一个简单的多标的策略
用刚才学到的知识把之前的策略例子改为多标的版本,如下:
def initialize(context):
context.securities = ['BTC/USDT.binance','ETH/USDT.binance']
context.myaccount = context.get_account('myaccount')
def handle_data(context):
for symbol in context.securities:
current_price = context.get_price(symbol)
context.myaccount.buy(symbol, current_price, 0.1)
来源:oschina
链接:https://my.oschina.net/u/4335103/blog/4260843