本文整理汇总了Python中zipline.api.get_datetime函数的典型用法代码示例。如果您正苦于以下问题:Python get_datetime函数的具体用法?Python get_datetime怎么用?Python get_datetime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_datetime函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: 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)
示例2: before_trading_start
def before_trading_start(context, data):
dt = api.get_datetime()
# rebalance at the beginning or at the beginning of a new year
if context.year == 0 or context.year == dt.year or len(context.portfolio) != 10:
context.trade = True
context.year = dt.year + 1
# get our dow 30 stocks
members = get_dow(context.dow30)
sids = [m.sid for m in members]
# get fundamentals, save, and update universe
# PROBLEM: this does not always sync up with Dow30
# PROBLEM: example, returns "CAT"/1267 and "CAT_WI"/11740
fundamentals_df = api.get_fundamentals(
api
.query(
api.fundamentals.valuation_ratios.pe_ratio,
api.fundamentals.valuation_ratios.dividend_yield,
)
.filter(api.fundamentals.share_class_reference.sid.in_(sids))
.order_by(
api.fundamentals.valuation_ratios.dividend_yield.desc() # sort by highest to lowest dividend yield
)
.limit(10) # take the top 10 highest paying dividend
)
context.fundamentals_df = fundamentals_df # save to context to use during rebalance()
api.update_universe(fundamentals_df.columns.values)
示例3: handle_data
def handle_data(context, data):
# Skip first 300 days to get full windows
date = get_datetime()
context.i += 1
if context.i < 10:
return
prices = history(25, '1d', 'price')
for sym in data:
upper, middle, lower = talib.BBANDS(
np.array(prices[sym]),
timeperiod=20,
nbdevup=2,
nbdevdn=2,
matype=0
)
potential_buy = []
buy = False
sell = False
if data[sym].price > upper[-1] and context.portfolio.positions[sym].amount == 0:
# log.info('buy')
# log.info(get_datetime())
# log.info(data[sym].price)
# log.info(upper[-1])
order_target_percent(sym, 1.0, limit_price=data[sym].price)
elif data[sym].price < middle[-1] and context.portfolio.positions[sym].amount > 0:
# log.info('sell')
# log.info(get_datetime())
# log.info(data[sym].price)
# log.info(middle[-1])
order_target(sym, 0, limit_price=data[sym].price)
示例4: show_positions
def show_positions (context, data):
if context.order_placed == True :
print ('\n{}'.format(get_datetime().date()))
print ('\nPOSITIONS\n\n')
for asset in context.stocks :
if context.portfolio.positions[asset].amount > 0 :
print ( '{0} : QTY = {1}, COST BASIS {2:3.2f}, CASH = {3:7.2f}, POSITIONS VALUE = {4:7.2f}, TOTAL = {5:7.2f}'
.format(asset, context.portfolio.positions[asset].amount,
context.portfolio.positions[asset].cost_basis,
context.portfolio.cash,
context.portfolio.positions[asset].amount * data[asset].price,
context.portfolio.portfolio_value))
# retrieve all the open orders and log the total open amount
# for each order
open_orders = get_open_orders()
# open_orders is a dictionary keyed by sid, with values that are lists of orders.
if open_orders:
# iterate over the dictionary
for security, orders in open_orders.iteritems():
# iterate over the orders
for oo in orders:
message = '\nOutstanding open order for {amount} shares in {stock}'
message = message.format(amount=oo.amount, stock=security)
print(message)
return
else:
# wait until all orders filled before resetting this flag
context.order_placed = False
return
示例5: rebalance
def rebalance(context, data):
# Wait for 756 trading days (3 yrs) of historical prices before trading
if context.day < context.min_data_window - 1:
return
# Get expanding window of past prices and compute returns
context.today = get_datetime().date()
prices = data.history(context.assets, "price", context.day, "1d")
if context.first_rebal_date is None:
context.first_rebal_date = context.today
context.first_rebal_idx = context.day
print('Starting dynamic allocation simulation...')
# Get investment horizon in days ie number of trading days next month
context.tau = rnr.get_num_days_nxt_month(context.today.month, context.today.year)
# Calculate HFP distribution
asset_rets = np.array(prices.pct_change(context.tau).iloc[context.tau:, :])
num_scenarios = len(asset_rets)
# Set Flexible Probabilities Using Exponential Smoothing
half_life_prjn = 252 * 2 # in days
lambda_prjn = np.log(2) / half_life_prjn
probs_prjn = np.exp(-lambda_prjn * (np.arange(0, num_scenarios)[::-1]))
probs_prjn = probs_prjn / sum(probs_prjn)
mu_pc, sigma2_pc = rnr.fp_mean_cov(asset_rets.T, probs_prjn)
# Perform shrinkage to mitigate estimation risk
mu_shrk, sigma2_shrk = rnr.simple_shrinkage(mu_pc, sigma2_pc)
weights, _, _ = rnr.efficient_frontier_qp_rets(context.n_portfolio,
sigma2_shrk, mu_shrk)
print('Optimal weights calculated 1 day before month end on %s (day=%s)' \
% (context.today, context.day))
#print(weights)
min_var_weights = weights[0,:]
# Rebalance portfolio accordingly
for stock, weight in zip(prices.columns, min_var_weights):
order_target_percent(stock, np.asscalar(weight))
context.weights = min_var_weights
示例6: wrapper
def wrapper(context, data):
dt = get_datetime()
if dt.date() != context.current_date:
context.warmup -= 1
context.mins_for_days.append(1)
context.current_date = dt.date()
else:
context.mins_for_days[-1] += 1
hist = context.history(2, "1d", "close_price")
for n in (1, 2, 3):
if n in data:
if data[n].dt == dt:
context.vol_bars[n].append(data[n].volume)
else:
context.vol_bars[n].append(0)
context.price_bars[n].append(data[n].price)
else:
context.price_bars[n].append(np.nan)
context.vol_bars[n].append(0)
context.last_close_prices[n] = hist[n][0]
if context.warmup < 0:
return f(context, data)
示例7: rebalance
def rebalance(context, data):
if not interval_countdown(context, data, rebalance):
return
#generate_strat_data(context, data)
print ('\nREBALANCE {}'.format(get_datetime()))
context.new_weights = pd.Series(0., index=context.stocks)
for strategy in context.strategies :
for portfolio_no, assets in enumerate(context.strategies[strategy]['portfolios']):
# rank portfolio assets according to zscore parameters
ranks = rank_assets (context, strategy, assets, portfolio_no)
#elligible_pre portfolio assets are those with rank <= n_top
elligible_pre = ranks.index[ranks<=context.strategies[strategy]['n_top']]
# apply asset filter
elligible_post = filter_assets(context, strategy, elligible_pre, context.strategies[strategy]['filter'])
# asset allocation
new_weights = allocate_assets(context, strategy, portfolio_no, elligible_pre, elligible_post)
context.new_weights = context.new_weights + new_weights
return
示例8: handle_data
def handle_data(context, data):
today = get_datetime()
factors = data.factors
for length, key in iteritems(vwap_keys):
for asset in assets:
computed = factors.loc[asset, key]
expected = vwaps[length][asset].loc[today]
# Only having two places of precision here is a bit
# unfortunate.
assert_almost_equal(computed, expected, decimal=2)
示例9: handle_orders
def handle_orders(context, data):
if (context.new_weights == context.current_weights).all() :
print ('\n{} ALLOCATION UNCHANGED\n'.format(get_datetime().date()))
return
for asset in context.new_weights.index:
if abs(context.new_weights[asset] - context.current_weights[asset]) > context.threshold :
print ('\n{} ORDER {} of {} @ {}'.format(get_datetime(), context.new_weights[asset],
asset, data[asset].close_price))
order_target_percent(asset, context.new_weights[asset])
context.current_weights = context.new_weights
context.order_placed = True
# print (context.strat_data['price'].ix[-1])
# print ('\n\n', get_open_orders())
return
示例10: handle_data
def handle_data(context, data):
# 获取股票的收盘价
close_data = history(12,'1d','close')
# 取得过去五天的平均价格
ma5 = close_data[-6:-2].mean()
# 取得过去10天的平均价格
ma10 = close_data[-11:-2].mean()
# 取得当前的现金
print get_datetime(),ma5,ma10
cash = context.portfolio.cash
#print ma5[sid(symbol(context.security))],ma10[sid(stock)],cash,symbol(context.security)
#如果当前有余额,并且五日均线大于十日均线
if ma5[sid(symbol(context.security))] > ma10[sid(symbol(context.security))]:
order_value(symbol(context.security), cash)
# 如果五日均线小于十日均线,并且目前有头寸
elif ma5[sid(symbol(context.security))] < ma10[sid(symbol(context.security))]:
# 全部卖出
order_target(symbol(context.security), 0)
示例11: handle_data
def handle_data(context, data):
results = pipeline_output("test")
date = get_datetime().normalize()
for asset in self.assets:
# Assets should appear iff they exist today and yesterday.
exists_today = self.exists(date, asset)
existed_yesterday = self.exists(date - self.trading_day, asset)
if exists_today and existed_yesterday:
latest = results.loc[asset, "close"]
self.assertEqual(latest, self.expected_close(date, asset))
else:
self.assertNotIn(asset, results.index)
示例12: 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
示例13: handle_data
def handle_data(context, data):
factors = data.factors
date = get_datetime().normalize()
for asset in self.assets:
# Assets should appear iff they exist today and yesterday.
exists_today = self.exists(date, asset)
existed_yesterday = self.exists(date - trading_day, asset)
if exists_today and existed_yesterday:
latest = factors.loc[asset, 'close']
self.assertEqual(latest, self.expected_close(date, asset))
else:
self.assertNotIn(asset, factors.index)
示例14: 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))
示例15: wait_for_data
def wait_for_data (context, data):
if context.waiting_for_data :
print ('\n{} WAITING FOR DATA...'.format(get_datetime().date()))
# wait for history to fill
max_lookback = context.max_lookback
highs = history (max_lookback, '1d', 'high')
if not highs.ix[0].sum() > 0 :
return
else:
context.waiting_for_data = False
return