import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.preprocessing import scale
from collections import deque
import random
import sklearn
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import datetime
import math, time
import itertools
from sklearn import preprocessing
import datetime
from operator import itemgetter
from sklearn.metrics import mean_squared_error
from math import sqrt
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.recurrent import LSTM
df1=D.history_data(instruments=['0293.HKEX'], start_date='2017-01-01', end_date='2017-01-07',
fields=['open'])
df2=D.history_data(instruments=['0753.HKEX'], start_date='2017-01-01', end_date='2017-01-07', fields=['open'])
df2.head()
instruments = D.instruments()
#instruments.append('0293.HKEX')
stocks=['0293.HKEX','0753.HKEX','1055.HKEX','0670.HKEX']
df = D.history_data(instruments=['0293.HKEX'], start_date='2017-05-19', end_date='2017-12-19',fields=['open', 'high', 'low', 'close','adjusted close'])
def initialize(context):
# 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
instruments = D.instruments()
# 传入预测数据和真实数据
#cnt=0
def handle_data(context, data):
current_dt = current_dt = data.current_dt.strftime('%Y-%m-%d')
sid1 = context.symbol('0293.HKEX')# CATHAY
#sid2 = context.symbol('1055.HKEX')# 南方航空
sid2 = context.symbol('0753.HKEX')# 中国国航
#sid2 = context.symbol('0670.HKEX')# 东方航空
cur_position = context.portfolio.positions[sid1].amount # 持仓
if cur_position==0:
#context.order_value(sid1, -100000)
context.order_value(sid2, 100000)
#context.order_value(sid2, -10000)
#if cur_position==0:
#if df_test['trade_signal'].values[df_test.index==current_dt]==0:
#context.order_target_percent(sid, 0.7)
#elif df_test['trade_signal'].values[df_test.index==current_dt]==1:
#context.order_target_percent(sid, 1.0)
#context.date=current_dt
#else:
#if df_test['trade_signal'].values[df_test.index==current_dt]==-1:
#context.order_target(sid, 0)
m=M.trade.v3(
instruments=stocks,
start_date='2017-01-01',
end_date='2018-02-28',
initialize=initialize,
handle_data=handle_data,
order_price_field_buy='open', # 表示 开盘 时买入
order_price_field_sell='close', # 表示 收盘 前卖出
capital_base=100000,
benchmark='HSI.HKEX',
m_cached=False
)