当前位置: 首页>>代码示例>>Python>>正文


Python api.symbol函数代码示例

本文整理汇总了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])
开发者ID:Ernestyj,项目名称:PyProj,代码行数:25,代码来源:TradingAlgo.py

示例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)
开发者ID:ricardompassos,项目名称:backtest,代码行数:30,代码来源:oil_example_2.py

示例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)
开发者ID:vsmolyakov,项目名称:fin,代码行数:32,代码来源:momentum.py

示例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())
开发者ID:returnandrisk,项目名称:meucci-python,代码行数:29,代码来源:dynamic_allocation_performance_analysis.py

示例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 "==========================="   
开发者ID:ricardompassos,项目名称:backtest,代码行数:7,代码来源:buy_and_hold_my.py

示例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)
开发者ID:ricardompassos,项目名称:backtest,代码行数:26,代码来源:oil_example_simple.py

示例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))
开发者ID:liyizheng0513,项目名称:zipline-chinese,代码行数:25,代码来源:stock_select.py

示例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)
开发者ID:skye17,项目名称:newfront,代码行数:8,代码来源:order_then_sell.py

示例9: handle_data

def handle_data(context, data):
    print "================================="
    print "New iteration"
    print data

    order(symbol('AAPL'), 10)

    record(AAPL=data[symbol('AAPL')].price)
开发者ID:ricardompassos,项目名称:backtest,代码行数:8,代码来源:buyapple.py

示例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)
开发者ID:ivansabik,项目名称:tradinglab-mexico,代码行数:9,代码来源:modelos.py

示例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
开发者ID:nsbradford,项目名称:quantraider,代码行数:9,代码来源:trader.py

示例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
开发者ID:skye17,项目名称:frontopolar_site,代码行数:12,代码来源:default.py

示例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)
开发者ID:vishalv95,项目名称:MaxPain,代码行数:12,代码来源:backtest.py

示例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
开发者ID:skye17,项目名称:newfront,代码行数:53,代码来源:website_trade2.py

示例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
           )
开发者ID:vsmolyakov,项目名称:fin,代码行数:52,代码来源:olmar.py


注:本文中的zipline.api.symbol函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。