Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
First Pass Please Help

Hey all,

I'm new to quantoian and writing Python. I have written in Guass and MatLab, but for some reason, I'm having a little hard time here. The ideology behind my code is to check premarket data, run some fundamentals p/e and current assets>current liabilities. Then update my universe and input some geometric brownian motion to account for volatility. After which the algo is supposed to execute long only as a percentage no more than 20%. Please help as of now I'm crashing line 40. Thanks in advance.

import pandas as pd  
import numpy as np  
import urllib2  # works fine with Python 2.7.9 (not 3.4.+)  
import json  
import time  
#Function Below takes in Premarket data from Google Finance and Needs to be modified to stop running after 9:30am EST

def fetchPreMarket(symbol, exchange):  
    link = "http://finance.google.com/finance/info?client=ig&q="  
    url = link+"%s:%s" % (exchange, symbol)  
    u = urllib2.urlopen(url)  
    content = u.read()  
    data = json.loads(content[3:])  
    info = data[0]  
    t = str(info["elt"])    # time stamp  
    l = float(info["l"])    # close price (previous trading day)  
    p = float(info["el"])   # stock price in pre-market (after-hours)  
    return (t,l,p)  

p0 = 0  
while True:  
    t, l, p = fetchPreMarket("CHK","MU", "RDS.A", "LXRX", "NASDAQ")  
    if(p!=p0):  
        p0 = p  
        print("%s\t%.2f\t%.2f\t%+.2f\t%+.2f%%" % (t, l, p, p-l,  
                                                 (p/l-1)*100.))  
    time.sleep(60)

def before_trading_start(context):  
    # Query for securities based on PE ratio and their economic sector  
    fundamental_df = get_fundamentals(  
        # Retrieve data based on PE ratio and economic sector  
        query(fundamentals.valuation_ratios.pe_ratio,fundamentals.balance_sheet.current_assets, fundamentals.balance_sheet.current_liabilites)  
        )

        # Filter where the Sector code matches our technology sector code  
        # Filter where PE ratio is less than 15  
.filter(fundamentals.valuation_ratios.pe_ratio < 15)
.filter(balance_sheet.current_assests>balance_sheet.current_liablities)


        # Order by low PE ratio and limit to 20 results  
        .order_by(fundamentals.valuation_ratios.pe_ratio.desc() and fundamentals.balance_sheet.current_assests>balance_sheet.current_liablities).limit(20)  
    )  
    update_universe(context.fundamental_df.columns.values)  
 def initialize(context):  
for i in range(total_minutes):  
    # Every 45 minutes run schedule  
    if i % 45 == 0:  
      # This will start at 9:31AM and will run every 30 minutes  
      schedule_function(  
      myfunc,  
        date_rules.every_day(),  
        time_rules.market_open(minutes=i),  
        True  
      )  
       set_universe(universe.DollarVolumeUniverse(floor_percentile=1.0, ceiling_percentile=6.0))  
    context.other_stocks = symbols('MU', 'RDS.A', 'LXRX' , 'CHK')  # add some specific securities  
    #adding in Geometirc Brownian Motion to account for Volutity  
#geometric brownian motion with drift

T = 2  
mu = 0.1  
sigma = 0.01  
S0 = 20  
dt = 0.01  
N = round(T/dt)  
t = np.linspace(0, T, N)  
W = np.random.standard_normal(size = N)  
W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###  
X = (mu-0.5*sigma**2)*t + sigma*W  
S = S0*np.exp(X)  
# the other methods in your algorithm.


  # Algorithm will raise an exception if it attempts to place an  
  # order which would cause us to hold negative shares of any security.  
  set_long_only()

def handle_data(context, data):  
    for stock in data:  
        log.info(str(stock))



# Will be called on every trade event for the securities you specify.  
if stock pass .filter order_percent((sid), .2)  
elif order_percent((sid),.0)


        log.error  
        log.pnl  
        log.cash  
5 responses

Hi Daniel,
Welcome to Quantopian!

The problem was that your filters were in the wrong spot. They should be within your get_fundamentals function. Also, some of your indentation was off, so I fixed that. For example, you were calling update_universe multiple times, when it only needs to be called once in initialize. I commented out some code at the end too where I wasn't sure what you were trying to do.

Another thing is that your fetchPreMarket function cannot use urllib2. See the modules we allow, and other help information, here. You can import external data with fetcher.

We don't currently support pre-market data, but you could try importing it via fetcher. Another option is to use data from the first bar of the day, or the last bar of the previous day. See the history function to do that.

Let me know if you need help with anything else!

Gus

import pandas as pd  
import numpy as np  
##import urllib2  # works fine with Python 2.7.9 (not 3.4.+)  
import json  
import time

#Function Below takes in Premarket data from Google Finance and Needs to be modified to stop running after 9:30am EST

def fetchPreMarket(symbol, exchange):  
    link = "http://finance.google.com/finance/info?client=ig&q="  
    url = link+"%s:%s" % (exchange, symbol)  
    u = urllib2.urlopen(url)  
    content = u.read()  
    data = json.loads(content[3:])  
    info = data[0]  
    t = str(info["elt"])    # time stamp  
    l = float(info["l"])    # close price (previous trading day)  
    p = float(info["el"])   # stock price in pre-market (after-hours)  
    return (t,l,p)  

p0 = 0  
while True:  
    t, l, p = fetchPreMarket("CHK","MU", "RDS_A", "LXRX", "NASDAQ")  
    if(p!=p0):  
        p0 = p  
        print("%s\t%.2f\t%.2f\t%+.2f\t%+.2f%%" % (t, l, p, p-l,  
                                                 (p/l-1)*100.))  
    time.sleep(60)

def before_trading_start(context):  
    # Query for securities based on PE ratio and their economic sector  
    fundamental_df = get_fundamentals(  
        # Retrieve data based on PE ratio and economic sector  
        query(  
            fundamentals.valuation_ratios.pe_ratio,  
            fundamentals.balance_sheet.current_assets,  
            fundamentals.balance_sheet.current_liabilites  
            )  
        # Filter where the Sector code matches our technology sector code  
        # Filter where PE ratio is less than 15  
        .filter(fundamentals.valuation_ratios.pe_ratio < 15)  
        .filter(balance_sheet.current_assests>balance_sheet.current_liablities)

        # Order by low PE ratio and limit to 20 results  
        .order_by(fundamentals.valuation_ratios.pe_ratio.desc() and fundamentals.balance_sheet.current_assests>balance_sheet.current_liablities).limit(20)  
    )  
    update_universe(context.fundamental_df.columns.values)  
def initialize(context):  
    set_universe(universe.DollarVolumeUniverse(floor_percentile=1.0, ceiling_percentile=6.0))  
    for i in range(total_minutes):  
        # Every 45 minutes run schedule  
        if i % 45 == 0:  
          # This will start at 9:31AM and will run every 30 minutes  
          schedule_function(myfunc, date_rules.every_day(), time_rules.market_open(minutes=i), True)  
        context.other_stocks = symbols('MU', 'RDS.A', 'LXRX' , 'CHK')  # add some specific securities  
        #adding in Geometirc Brownian Motion to account for Volutity  
    #geometric brownian motion with drift

    T = 2  
    mu = 0.1  
    sigma = 0.01  
    S0 = 20  
    dt = 0.01  
    N = round(T/dt)  
    t = np.linspace(0, T, N)  
    W = np.random.standard_normal(size = N)  
    W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###  
    X = (mu-0.5*sigma**2)*t + sigma*W  
    S = S0*np.exp(X)  
    # the other methods in your algorithm.


    # Algorithm will raise an exception if it attempts to place an  
    # order which would cause us to hold negative shares of any security.  
    set_long_only()

def handle_data(context, data):  
    for stock in data:  
        log.info(str(stock))


# Will be called on every trade event for the securities you specify.  
"""if stock pass .filter order_percent((sid), .2)  
elif order_percent((sid),.0)


        log.error  
        log.pnl  
        log.cash"""  
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thanks gus. Super helpful. I really appreciate it.

@gus, I got it sorted to line 22 and it keeps telling me there is a syntax error. I have looked at the API documentation, and I don't understand why it keeps crashing.

import pandas as pd  
import numpy as np  

def before_trading_start(context):  
    # Query for securities based on PE ratio and their economic sector  
    fundamental_df = get_fundamentals(  
        # Retrieve data based on PE ratio and economic sector  
        query(  
            fundamentals.valuation_ratios.pe_ratio,  
            fundamentals.balance_sheet.current_assets,  
            fundamentals.balance_sheet.current_liabilites  
            )  
        # Filter where the Sector code matches our technology sector code  
        # Filter where PE ratio is less than 15  
        .filter(fundamentals.valuation_ratios.pe_ratio < 15)  
        .filter(fundamentals.balance_sheet.current_assests > fundamentals.balance_sheet.current_liablities)

        # Order by low PE ratio and limit to 20 results  
  .order_by(fundamentals.valuation_ratios.pe_ratio.desc()).limit(20) and order_by(fundamentals.balance_sheet.current_assests > fundamentals.balance_sheet.current_liablities.desc()).limit(20)  
    update_universe(context.fundamental_df.columns.values)  


def initialize(context):  
    #only go long securities  
        set_long_only()


def handle_data(context, data):  
    set_universe(context.fundamental_df = fundamental_df)  
        log.info(str(stock))

    for info in range(390):  
        # Every 45 minutes run schedule  
        if i % 45 == 0:  
          # This will start at 9:31AM and will run every 45 minutes  
          schedule_function(myfunc, date_rules.every_day(), time_rules.market_open(minutes=i), True)  

        #adding in Geometirc Brownian Motion to account for Volutity  
    #geometric brownian motion with drift

    T = 2  
    mu = 0.1  
    sigma = 0.01  
    S0 = 20  
    dt = 0.01  
    N = round(T/dt)  
    t = np.linspace(0, T, N)  
    W = np.random.standard_normal(size = N)  
    W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###  
    X = (mu-0.5*sigma**2)*t + sigma*W  
    S = S0*np.exp(X)  
    # the other methods in your algorithm.



# Will be called on every trade event for the securities you specify.  
order_percent((sid),.1)



log.error  
log.pnl  
log.cash

Looks like you were just missing a close parentheses. I fixed a couple other things too, but it looks like you're still adjusting your main functions.

import pandas as pd  
import numpy as np  

def before_trading_start(context):  
    # Query for securities based on PE ratio and their economic sector  
    fundamental_df = get_fundamentals(  
        # Retrieve data based on PE ratio and economic sector  
        query(  
            fundamentals.valuation_ratios.pe_ratio,  
            fundamentals.balance_sheet.current_assets,  
            fundamentals.balance_sheet.current_liabilites  
            )  
        # Filter where the Sector code matches our technology sector code  
        # Filter where PE ratio is less than 15  
        .filter(fundamentals.valuation_ratios.pe_ratio < 15)  
        .filter(fundamentals.balance_sheet.current_assests > fundamentals.balance_sheet.current_liablities)

        # Order by low PE ratio and limit to 20 results  
        .order_by(fundamentals.valuation_ratios.pe_ratio.desc()).limit(20) and order_by(fundamentals.balance_sheet.current_assests > fundamentals.balance_sheet.current_liablities.desc()).limit(20))  
    update_universe(context.fundamental_df.columns.values)  


def initialize(context):  
    #only go long securities  
        set_long_only()


def handle_data(context, data):  
    #set_universe(context.fundamental_df = fundamental_df)  
    log.info(str(stock))

    for info in range(390):  
        # Every 45 minutes run schedule  
        if i % 45 == 0:  
          # This will start at 9:31AM and will run every 45 minutes  
          schedule_function(myfunc, date_rules.every_day(), time_rules.market_open(minutes=i), True)  

        #adding in Geometirc Brownian Motion to account for Volutity  
    #geometric brownian motion with drift

    T = 2  
    mu = 0.1  
    sigma = 0.01  
    S0 = 20  
    dt = 0.01  
    N = round(T/dt)  
    t = np.linspace(0, T, N)  
    W = np.random.standard_normal(size = N)  
    W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###  
    X = (mu-0.5*sigma**2)*t + sigma*W  
    S = S0*np.exp(X)  
    # the other methods in your algorithm.



# Will be called on every trade event for the securities you specify.  
order_percent((sid),.1)



log.error  
log.pnl  
log.cash  

Thanks. And yes, still working through the main function.