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