Quantopian, python error: TypeError: object of type 'NoneType' has no len() in getting morningstar data
I am new to Quantopian and I am trying to obtain the ipo's dates from Morningstar. I found some code on Quantopian and embedded it into my pipline. (the rest of the code is copied for test purposes.
The error message I get is TypeError: object of type 'NoneType' has no len() on line xxx. I looked at other stockoverflow help where they analyzed the same error and given there should be data there, I'm not sure what's wrong.
The error is on the line : out[:] = np.apply_along_axis(get_delta_days, 0, ipo_dates)
The code is:
"""
sample test of morningstar.
"""
# 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)
python quantopian morningstar
add a comment |
I am new to Quantopian and I am trying to obtain the ipo's dates from Morningstar. I found some code on Quantopian and embedded it into my pipline. (the rest of the code is copied for test purposes.
The error message I get is TypeError: object of type 'NoneType' has no len() on line xxx. I looked at other stockoverflow help where they analyzed the same error and given there should be data there, I'm not sure what's wrong.
The error is on the line : out[:] = np.apply_along_axis(get_delta_days, 0, ipo_dates)
The code is:
"""
sample test of morningstar.
"""
# 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)
python quantopian morningstar
add a comment |
I am new to Quantopian and I am trying to obtain the ipo's dates from Morningstar. I found some code on Quantopian and embedded it into my pipline. (the rest of the code is copied for test purposes.
The error message I get is TypeError: object of type 'NoneType' has no len() on line xxx. I looked at other stockoverflow help where they analyzed the same error and given there should be data there, I'm not sure what's wrong.
The error is on the line : out[:] = np.apply_along_axis(get_delta_days, 0, ipo_dates)
The code is:
"""
sample test of morningstar.
"""
# 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)
python quantopian morningstar
I am new to Quantopian and I am trying to obtain the ipo's dates from Morningstar. I found some code on Quantopian and embedded it into my pipline. (the rest of the code is copied for test purposes.
The error message I get is TypeError: object of type 'NoneType' has no len() on line xxx. I looked at other stockoverflow help where they analyzed the same error and given there should be data there, I'm not sure what's wrong.
The error is on the line : out[:] = np.apply_along_axis(get_delta_days, 0, ipo_dates)
The code is:
"""
sample test of morningstar.
"""
# 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)
python quantopian morningstar
python quantopian morningstar
asked Nov 12 '18 at 3:14
quinnquinn
63
63
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53255525%2fquantopian-python-error-typeerror-object-of-type-nonetype-has-no-len-in-g%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53255525%2fquantopian-python-error-typeerror-object-of-type-nonetype-has-no-len-in-g%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown