量化交易入門筆記-多股票持倉策略
摘要:
'''
同時操作多隻股票
價格高於5天平均價*1.008,則買入
價格小於5天平均價*0.996,則賣出
'''
import jqdata
def initialize(context):
""&...

''' 同時操作多隻股票 價格高於5天平均價*1.008,則買入 價格小於5天平均價*0.996,則賣出 ''' import jqdata def initialize(context): """初始化函式""" # 設定要操作的股票池 g.stocks = ['000001.XSHE', '000002.XSHE', '000004.XSHE', '000005.XSHE'] # 設定基準 set_benchmark('000300.XSHG') # 開啟動態復權 set_option('use_real_price', True) def handle_data(context, data): """單位時間呼叫函式""" # 迴圈每隻股票 for security in g.stocks: # 得出股票之前5天的均價 vwap = data[security].vwap(5) # 得到上一時間點股票平均價 price = data[security].close # 得到當前資金餘額 cash = context.portfolio.cash # 如果上一時間點價格小於5天平均價格*0.996,並且持有該股票,賣出 if price < vwap * 0.996 and context.portfolio.positions[security].closeable_amount > 0: # 下單賣出 order(security, -500) # 記錄這次賣出 log.info('賣出股票 %s' % (security)) # 如果上一時間點價格大於5天平均價*1.008,並且有現金餘額,買入 elif price > vwap * 1.008 and cash > 0: # 下買入單 order(security, 500) # 記錄這次買入 log.info('買入股票 %s' % (security))
回測結果:

注:本文章為個人學習筆記,參考了一些書籍與官方教程,不作任何商業用途!