• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python api.symbol函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中zipline.api.symbol函数的典型用法代码示例。如果您正苦于以下问题:Python symbol函数的具体用法?Python symbol怎么用?Python symbol使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了symbol函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: handle_data

    def handle_data(self, context, data):
        # Implement your algorithm logic here.

        # data[sid(X)] holds the trade event data for that security.
        # context.portfolio holds the current portfolio state.

        # Place orders with the order(SID, amount) method.

        # TODO: implement your own logic here.
        context.trade_days += 1
        if context.trade_days <> 5 :
           return
        context.trade_days = 0


        ## checking the market status:
        ## if SPY > price one year ago, Market is in uptrend
        ## otherwise, market is in downtrend
        hist = history(bar_count = 241, frequency='1d', field='price')
        cash = context.portfolio.cash
        current_price_spy = data[symbol(self.ticker_spy)].price


        try:
            if current_price_spy > hist[symbol(self.ticker_spy)][200] :

                lst = self.top_rets(context.equities, 240)
                lst_mean = lst['zero']
                count = len(lst_mean)



                for ticker in sector_tickers:
                    if ticker in lst_mean:
                        order_target_percent(symbol(ticker), 1.0/count)
                    else :
                        order_target_percent(symbol(ticker), 0)

                order_target_percent(symbol(self.ticker_gld),  0)
                order_target_percent(symbol(self.ticker_tlt), 0)
            else :
                for ticker in sector_tickers:
                    order_target_percent(symbol(ticker), 0)

                order_target_percent(symbol(self.ticker_spy),  0)
                order_target_percent(symbol(self.ticker_gld),  0.5)
                order_target_percent(symbol(self.ticker_tlt),  0.5)
        except:
            pass
开发者ID:cocojumbo77,项目名称:Trading_Strategies,代码行数:49,代码来源:AAA.py


示例17: top_rets

    def top_rets(self, tickers, win) :
        hist = history(bar_count = 241, frequency='1d', field='price')

        ret = ((hist/hist.shift(win)) - 1).tail(1)
        mean_ret = float(np.median(ret))
        max_ret = float(ret.max(axis=1))
        spy_ret = float(ret[symbol(self.ticker_spy)])

        lst = {}
        lst['mean'] = []
        lst['spy'] = []
        lst['zero'] = []
        lst['max'] = []

        for ticker in tickers :
            ticker_ret = float(ret[ticker])
            if ticker_ret > mean_ret :
                lst['mean'].append(ticker)
            if ticker_ret > spy_ret:
                lst['spy'].append(ticker)
            if ticker_ret > 0:
                lst['zero'].append(ticker)
            if ticker_ret >= max_ret:
                lst['max'].append(ticker)
        return lst
开发者ID:cocojumbo77,项目名称:Trading_Strategies,代码行数:25,代码来源:AAA.py


示例18: handle_data

    def handle_data(self, data):
        ######################################################
        # 1. Compute regression coefficients between PEP and KO
        params = self.ols_transform.handle_data(data, self.PEP, self.KO)
        if params is None:
            return
        intercept, slope = params

        ######################################################
        # 2. Compute spread and zscore
        zscore = self.compute_zscore(data, slope, intercept)
        self.record(zscores=zscore, PEP=data[symbol("PEP")].price, KO=data[symbol("KO")].price)

        ######################################################
        # 3. Place orders
        self.place_orders(data, zscore)
开发者ID:zluo,项目名称:zipline,代码行数:16,代码来源:pairtrade.py


示例19: initialize

def initialize(context):

    # Let's set a look up date inside our backtest to ensure we grab the correct security
    #set_symbol_lookup_date('2015-01-01')
    

    # Use a very liquid set of stocks for quick order fills
    context.symbol = symbol('SPY')
    #context.stocks = symbols(['TWX','AIG','PSX','EMC','YHOO','MDY','TNA','CHK','FXI',
    #                            'PEP','SBUX','VZ','VWO','TWC','HAL','MDLZ','CAT','TSLA',
    #                            'MU','PM','WYNN','MET',NOV BRK_B SNDK ESRX YELP])
    #set_universe(universe.DollarVolumeUniverse(99.5, 100))
    #set_benchmark(symbol('SPY'))
    
    # set a more realistic commission for IB, remove both this and slippage when live trading in IB
    set_commission(commission.PerShare(cost=0.014, min_trade_cost=1.4))
    
    # Default slippage values, but here to mess with for fun.
    set_slippage(slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))
        
    # Use dicts to store items for plotting or comparison
    context.next_pred_price = {} # Current cycles prediction
    
    #Change us!
    context.history_len              = 500    # How many days in price history for training set
    context.out_of_sameple_bin_size  = 2
    context.score_filter             = -1000.0
    context.action_to_move_percent   = 0.0

    # Register 2 histories that track daily prices,
    # one with a 100 window and one with a 300 day window
    add_history(context.history_len, '1d', 'price')
    context.i = 0
开发者ID:21hub,项目名称:daily-stock-forecast,代码行数:33,代码来源:svr.py


示例20: positions

    def positions(self):
        now = datetime.datetime.now()
        z_positions = protocol.Positions()
        for pos in self._client.positions():
            if isinstance(pos, list):
                pos = TdxPosition(*pos)
            sid = pos.sid
            available = pos.available
            z_position = protocol.Position(symbol(sid))
            z_position.amount = pos.amount
            z_position.cost_basis = pos.cost_basis
            z_position.last_sale_price = pos.last_sale_price
            z_position.last_sale_date = now
            z_positions[symbol(sid)] = z_position

        return z_positions
开发者ID:huangzhengyong,项目名称:zipline,代码行数:16,代码来源:tdx_broker.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python assets.AssetFinder类代码示例发布时间:2022-05-26
下一篇:
Python api.sid函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap