Quantopian, python error: TypeError: объект типа 'NoneType' не имеет len () для получения данных morningstar - PullRequest
0 голосов
/ 12 ноября 2018

Я новичок в Quantopian и пытаюсь получить даты ipo от Morningstar. Я нашел код на Quantopian и встроил его в мою линию. (остальная часть кода скопирована для целей тестирования.

Я получаю сообщение об ошибке TypeError: объект типа 'NoneType' не имеет len () в строке xxx. Я посмотрел на другую справку stockoverflow, где они проанализировали ту же ошибку и, учитывая, что там должны быть данные, я не уверен, что не так.

Ошибка в строке: out [:] = np.apply_along_axis (get_delta_days, 0, ipo_dates)

Код: «»» Образец теста Утренней Звезды.

"""


# Import the libraries we will use here

import pandas as pd

import numpy as np

from quantopian.algorithm import attach_pipeline, pipeline_output

from quantopian.pipeline import Pipeline

from quantopian.pipeline.data.builtin import USEquityPricing

from quantopian.pipeline.factors import AverageDollarVolume, Returns

from quantopian.pipeline.data import Fundamentals

#from quantopian.pipeline.data import morningstar as mstar

from quantopian.pipeline import  CustomFactor

def initialize(context):
"""
The initialize function is the place to create your pipeline (security 
selector),
and set trading conditions such as commission and slippage. It is called 
once
at the start of the simulation and also where context variables can be 
set.
"""

# Define context variables that can be accessed in other methods of
# the algorithm.
context.long_leverage = 0.5
context.short_leverage = -0.5
context.returns_lookback = 5

# Rebalance on the first trading day of each week at 11AM.
schedule_function(rebalance, 
                  date_rules.every_day(),#week_start(days_offset=0),
                  time_rules.market_open(hours = 1, minutes = 30))

# Record tracking variables at the end of each day.
schedule_function(record_vars,
                  date_rules.every_day(),
                  time_rules.market_close(minutes=1))

# Create and attach our pipeline (dynamic security selector), defined 
below.
attach_pipeline(make_pipeline(context), 'mean_reversion_example')


class StockAge(CustomFactor):  

inputs = [Fundamentals.ipo_date]  
window_length = 1  
def compute(self, today, assets, out, ipo_dates):  

    def get_delta_days(ipo_dates):  
        # Convert last known (ie -1) ipo_date to Timestamps  
        # Subtract ipo date from current date  
        # Return delta days  
        ipo = pd.Timestamp(ipo_dates[-1], tz='UTC', offset='C')  
        delta = today - ipo  
        print ('Hello, world!')
        return None if pd.isnull(delta) else float(delta.days) 


    # Apply the above function across each column and output the values  
    out[:] = np.apply_along_axis(get_delta_days, 0, ipo_dates)       

def make_pipeline(context):



# Create a pipeline object. 
    pipe = Pipeline()
    stk_age = StockAge()
    stk_top = stk_age.notnan()
    pipe.add(stk_top,'ipo')

    return pipe

def before_trading_start(context, data):
"""
Called every day before market open. This is where we get the securities
that made it through the pipeline.
"""

    context.myipo = context.output[context.output['ipo']]

# Keep a list reference and a set reference to all of our pipeline securities
# (set has much faster lookup)
    context.security_list = context.myipo.index.tolist()
    context.security_set = set(context.security_list)

def assign_weights(context):
"""
Assign weights to ou long and short target positions.
"""

# Set the allocations to even weights for each long position, and even weights
# for each short position.



def rebalance(context,data):
"""
This rebalancing function is called according to our schedule_function 
settings.  
"""

assign_weights(context)
for security in context.security_list:
    order_target_percent(security, context.short_weight)
for security in context.portfolio.positions:
    if security not in context.security_set and data.can_trade(security):
        order_target_percent(security, 0)
order_target_percent
# Log the long and short orders each week.
log.info("This week's ipos: "+", ".join([ipo_.symbol for ipo_ in context.ipo.index]))



def record_vars(context, data):
"""
This function is called at the end of each day and plots certain variables.
"""

# Check how many long and short positions we have.
    longs = shorts = 0
    for position in context.portfolio.positions.itervalues():
        if position.amount > 0:
            longs += 1
        if position.amount < 0:
            shorts += 1

# Record and plot the leverage of our portfolio over time as well as the 
# number of long and short positions. Even in minute mode, only the end-of-day 
# leverage is plotted.
    record(leverage = context.account.leverage, long_count=longs,     short_count=shorts)
...