本文整理汇总了Python中zipline.api.symbol函数的典型用法代码示例。如果您正苦于以下问题:Python symbol函数的具体用法?Python symbol怎么用?Python symbol使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了symbol函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle_data
def handle_data(context, data):
# Skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(100, '1d', 'price').mean()
long_mavg = history(300, '1d', 'price').mean()
# price_history = data.history(assets=symbol('TEST'), fields="price", bar_count=5, frequency="1d")
# Trading logic
if short_mavg[0] > long_mavg[0]:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(symbol('AAPL'), 100)
elif short_mavg[0] < long_mavg[0]:
order_target(symbol('AAPL'), 0)
# Save values for later inspection
record(AAPL=data[symbol('AAPL')].price,
short_mavg=short_mavg[0],
long_mavg=long_mavg[0])
示例2: handle_data
def handle_data(context, data):
curr_price = data[symbol('USCRWTIC INDEX')].price
curr_date = data[symbol('USCRWTIC INDEX')].datetime
curr_positions = context.portfolio.positions[symbol('USCRWTIC INDEX')].amount
cash = context.portfolio.cash
local_historical_data = context.oil_historical_data
local_historical_data = local_historical_data['USCRWTIC INDEX'][['price']]
df_to_forecast = local_historical_data[local_historical_data.index <= curr_date]
result = forecast_ts.run(df = df_to_forecast, ts_list = None, freq = 'B', forecast_horizon = 6, start_date = curr_date.strftime('%Y-%m-%d'), method = context.method, processing_params = context.processing_params, expert_params = context.expert_params)
estimated_return = result.iloc[-1].values[-1]
# estimated_return = np.random.rand()-1
print cash, curr_positions, curr_price, curr_date, estimated_return
if estimated_return < 0 and curr_positions == 0:
order(symbol('USCRWTIC INDEX'), -100)
elif estimated_return > 0 and curr_positions != 0:
order(symbol('USCRWTIC INDEX'), 100)
示例3: handle_data
def handle_data(context, data):
#trading algorithm (executed on every event)
#skip first 300 days to get full windows
context.i += 1
if context.i < 300:
return
#compute short and long moving averages:
short_mavg = history(100, '1d', 'price').mean()
long_mavg = history(300, '1d', 'price').mean()
buy = False
sell = False
#trading logic
if (short_mavg[0] > long_mavg[0]) and not context.invested:
buy = True
context.invested = True
order_target(symbol('AAPL'), 100)
elif (short_mavg[0] < long_mavg[0]) and context.invested:
sell = True
context.invested = False
order_target(symbol('AAPL'), -100)
#save values for plotting
record(AAPL = data[symbol('AAPL')].price,
short_mavg = short_mavg[0],
long_mavg = long_mavg[0],
buy=buy,
sell=sell)
示例4: initialize
def initialize(context):
# Turn off the slippage model
set_slippage(slippage.FixedSlippage(spread=0.0))
# Set the commission model
set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0))
context.day = -1 # using zero-based counter for days
context.set_benchmark(symbol('DIA'))
context.assets = []
print('Setup investable assets...')
for ticker in asset_tickers:
#print(ticker)
context.assets.append(symbol(ticker))
context.n_asset = len(context.assets)
context.n_portfolio = 40 # num mean-variance efficient portfolios to compute
context.today = None
context.tau = None
context.min_data_window = 756 # min of 3 yrs data for calculations
context.first_rebal_date = None
context.first_rebal_idx = None
context.weights = None
# Schedule dynamic allocation calcs to occur 1 day before month end - note that
# actual trading will occur on the close on the last trading day of the month
schedule_function(rebalance,
date_rule=date_rules.month_end(days_offset=1),
time_rule=time_rules.market_close())
# Record some stuff every day
schedule_function(record_vars,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_close())
示例5: func0
def func0(context, data):
order(symbol('AAPL UW EQUITY'), 10)
print 'price: ', data[symbol('AAPL UW EQUITY')].price
# order(symbol('AAPL UW EQUITY'), -10)
print context.portfolio.cash
print context.get_datetime().date()
print "==========================="
示例6: handle_data
def handle_data(context, data):
curr_price = data[symbol('USCRWTIC INDEX')].price
curr_positions = context.portfolio.positions[symbol('USCRWTIC INDEX')].amount
cash = context.portfolio.cash
print cash, curr_positions, curr_price
# context.counter += 1
# if context.counter > 500:
# print "Cancelou"
# cancel_order(context.order_id)
# else:
# print 'ola'
random_order = np.random.rand()
if random_order > 0.5 and curr_positions == 0:
order(symbol('USCRWTIC INDEX'), 100)
elif random_order < 0.5 and curr_positions != 0:
order(symbol('USCRWTIC INDEX'), -100)
示例7: handle_data
def handle_data(context, data):
# context.i+=1
# if context.i<=5:
# return
# 循环每只股票
closeprice= history(5,'1d','close')
for security in context.stocks:
vwap=(closeprice[symbol(security)][-2]+closeprice[symbol(security)][-3]+closeprice[symbol(security)][-4])/3
price = closeprice[symbol(security)][-2]
print get_datetime(),security,vwap,price
# # 如果上一时间点价格小于三天平均价*0.995,并且持有该股票,卖出
if price < vwap * 0.995:
# 下入卖出单
order(symbol(security),-300)
print get_datetime(),("Selling %s" % (security))
# 记录这次卖出
#log.info("Selling %s" % (security))
# 如果上一时间点价格大于三天平均价*1.005,并且有现金余额,买入
elif price > vwap * 1.005:
# 下入买入单
order(symbol(security),300)
# 记录这次买入
print get_datetime(),("Buying %s" % (security))
示例8: handle_data
def handle_data(context, data):
context.i += 1
stock_name = context.panel.axes[0][0]
if context.i == 60:
order(symbol(stock_name), 10)
if context.i == 150:
order(symbol(stock_name), -10)
record(Prices=data[symbol(stock_name)].price)
示例9: handle_data
def handle_data(context, data):
print "================================="
print "New iteration"
print data
order(symbol('AAPL'), 10)
record(AAPL=data[symbol('AAPL')].price)
示例10: _handle_data
def _handle_data(self, context, data):
for movimiento in context.movimientos:
clave_emisora = movimiento.emisora
fecha_movimiento = movimiento.fecha
fecha = data[symbol(clave_emisora)].dt
delta = fecha_movimiento - fecha.replace(tzinfo=None)
num_acciones = movimiento.num_acciones
if(delta.days == 0):
order(symbol(clave_emisora), num_acciones)
示例11: initialize
def initialize(context):
print "Initialize..."
context.security = symbol(settings.BACKTEST_STOCK)
context.benchmark = symbol('SPY')
context.strategy = settings.STRATEGY_OBJECT
context.raw_data = settings.PRE_BACKTEST_DATA
context.normalized_data = Manager.preprocessData(context.raw_data)[:-2]
print "Backtest symbol:", context.security
print "Capital Base:", context.portfolio.cash
示例12: handle_data
def handle_data(context, data):
context.panel # Here we have access to training data also.
# Make solution using the result of learning:
if not int(data[symbol('AAPL')].price) % context.result:
order(symbol('AAPL'), 10)
# Record some values for analysis in 'analyze()'.
sids = context.panel.axes[0].values
prices = [data[symbol(sid)].price for sid in sids]
record(Prices=prices)
record(Prediction=3 * data[symbol('AAPL')].price - 2.2 * context.previous)
# Record current price to use it in future.
context.previous = data[symbol('AAPL')].price
示例13: handle_data
def handle_data(context, data):
# check if the spot is outside CI of MPP
day_option_df = context.options[context.options['date'] == get_datetime()]
call_sums = call_otm(day_option_df, 'FB', get_datetime())
put_sums = put_otm(day_option_df, 'FB', get_datetime())
add_to_window(context, 10, max_pain_strike(call_sums, put_sums), 'FB')
ci = CI(context.window, 1)
price = history(1, '1d', 'price').iloc[0,0]
if price < ci[0]: order_target_percent(symbol('FB'), 1)
elif price > ci[1]: order_target_percent(symbol('FB'), 0)
示例14: handle_data
def handle_data(context, data):
context.cur_time += 1
month = get_datetime().date().month
is_january = (month == 1)
new_prices = np.array([data[symbol(symbol_name)].price for symbol_name in context.symbols], dtype='float32')
record(Prices=new_prices)
new_prices = new_prices.reshape((context.N_STOCKS, 1))
# print context.returns_history.shape
# print new_prices.shape
# print context.previous_prices.shape
context.returns_history = np.concatenate([context.returns_history, new_prices / context.previous_prices], axis=1)
context.previous_prices = new_prices
if context.month != month:
# Trading in the beginning of month
context.month_sizes.append(context.day_of_month)
context.day_of_month = 1
context.count_month += 1
context.month_sizes.append(context.day_of_month)
context.day_of_month = 1
if context.count_month > N_MONTHS:
# Deleting too old returns
if context.count_month > N_MONTHS + 1:
context.returns_history = np.delete(context.returns_history, range(context.month_sizes[-14]), axis=1)
model_input = preprocess_data_for_model(context.returns_history, context.month_sizes[-13:], context.scaler)
is_january_column = np.array([is_january] * context.N_STOCKS).reshape((context.N_STOCKS, 1))
model_input = np.concatenate([is_january_column, model_input], axis=1)
# print 'Input shape', model_input.shape
predicted_proba = context.model.predict_proba(model_input)
# print predicted_proba
'''
half_trade = len(context.symbols) * 1 / 10
args_sorted = np.argsort(predicted_proba[:, 0])
buy_args = args_sorted[:half_trade]
sell_args = args_sorted[-half_trade:]
for arg in buy_args:
order_target(symbol(context.symbols[arg]), 1)
for arg in sell_args:
order_target(symbol(context.symbols[arg]), -1)
'''
for i in range(context.N_STOCKS):
if predicted_proba[i, 0] > 0.5:
order_target(symbol(context.symbols[i]), 1)
else:
order_target(symbol(context.symbols[i]), -1)
else:
context.day_of_month += 1
context.month = month
示例15: handle_data
def handle_data(context, data):
#On-Line Moving Average Reversal (OLMAR)
context.days += 1
if context.days < context.window_length:
return
if context.init:
rebalance_portfolio(context, data, context.b_t)
context.init=False
return
m = context.m #num assets
x_tilde = np.zeros(m) #relative mean deviation
b = np.zeros(m) #weights
#compute moving average price for each asset
mavgs = history(context.window_length, '1d', 'price').mean()
#mavgs = data.history(context.sids, 'price', context.window_length, '1d').mean()
for i, stock in enumerate(context.stocks):
price = data[stock]['price']
x_tilde[i] = mavgs[i] / price
x_bar = x_tilde.mean()
market_rel_dev = x_tilde - x_bar #relative deviation
exp_return = np.dot(context.b_t, x_tilde)
weight = context.eps - exp_return
variability = (np.linalg.norm(market_rel_dev))**2
if variability == 0.0:
step_size = 0
else:
step_size = np.max((0, weight/variability))
b = context.b_t + step_size * market_rel_dev
b_norm = simplex_projection(b)
rebalance_portfolio(context, data, b_norm)
context.b_t = b_norm
#save values for plotting
record(AAPL = data[symbol('AAPL')].price,
MSFT = data[symbol('MSFT')].price,
step_size = step_size,
variability = variability
)