SlideShare a Scribd company logo
For any help regarding Python Homework Help
visit : - https://www.pythonhomeworkhelp.com/,
Email :- support@pythonhomeworkhelp.com or
call us at :- +1 678 648 4277
Here are some practice quiz questions (taken mostly from last year’s final).
1)Is each of the following True or False
1. In Python, the method sortof class listhas a side effect.
2.When run on the same inputs, an exponential algorithm will always
take longer than a polynomial algorithm.
3. Newton’s method is based upon successive approximation.
4.Constructing a black box test suite involves looking at the control flow
of the code to be tested.
5. Python classes enforce data hiding.
2) The code below produces three plots. Match each of the plots on
the next page with the appropriate figure (Figure 1, Figure 2, or
Figure 3).
import pylab y1 = []
y2 = []
y3 = []
for i in range(20):
y1.append(300*i)
y2.append(i**3)
Problem
pythonhomeworkhelp.com
y2.append(i**3) y3.append(2**i)
pylab.figure(1) pylab.plot(y1)
pylab.figure(2) pylab.plot(y2)
pylab.figure(3) pylab.plot(y3)
pylab.semilogy()
pythonhomeworkhelp.com
3) Can the following specification be implemented? If not,
explain why.
def f(x, e):
“““ x and e are floats
returns y, a float, such that x-e <= y*y <= x+e”””
4) Write a Python program that satisfies the following
specification.
def f(L1, L2):
“““ L1 and L2 are lists of integers
returns the element-wise product of L1 and L2. If
the lists are of different length, it uses 1 for the
missing coefficients.
E.g., if L1 = [2, 2, 3] and L2 = [7, 5, 6, 7]
it returns [14, 10, 18, 7] side
effects: none ”””
pythonhomeworkhelp.com
The following questions all refer to the code you were asked to study in preparation
for this exam. They also assume that the following code is used to test the program.
(For your convenience, a copy of the posted code is at the end of this quiz. Feel free
to separate it from the rest of the quiz.)
Warning: The code at the end of this is NOT the same as the code you have been
given to study. It may not be worth your time to study this code carefully enough
to answer all of the practice questions, but these questions should give you the
flavor of the kinds of questions we might ask about the code supplied this term.
numDays = 500 bias = 0.11/200.0 numSectors
= 1
sectorSize = 500
numTrials = 5
print 'Testing Model on', numDays, 'days' mean = 0.0
for i in range(numTrials): pylab.figure(1)
mkt = generateMarket(numSectors, sectorSize, bias)
endPrices = simMkt(mkt, numDays) mean += endPrices[-1]
title = 'Closing Prices With ' + str(numSectors) + ' Sectors'
plotValueOverTime(endPrices, title)
pylab.figure(2) plotDistributionAtEnd(mkt, title)
meanClosing = mean/float(numTrials)
print 'Mean closing with', numSectors, 'sectors is', meanClosing
pythonhomeworkhelp.com
1) If, in class Stock, the line
self.price = self.price * (1.0 + baseMove)
were replaced with the line
self.price = self.price * baseMove
which of the following best describes the expected mean value of
the market after 200 days:
a.Close to 111
b.Close to 100
c.Close to 50
d.Close to 0
e.About the same as with the original code
2)Consider running the above test code twice, once with numSectors = 1 and once
with numSectors = 20. Each will produce a Figure 1. Now consider running a linear
regression to fit a line to each of the curves produced in the Figure 1’s for each test.
Would you expect the average mean square error of the fits for numSectors =
20to be:
pythonhomeworkhelp.com
a.Smaller than the average mean square error of the fits for
numSectors = 1.
b.Larger than the average mean square error of the fits for
numSectors = 1.
c.About the same as the average mean square error of the fits
for
numSectors = 1.
d.None of the above.
5.3) Characterize the algorithmic efficiency of generateMarket.
5.4) If in Stock.makeMove, the line
baseMove=bias+random.uniform(-self.volatility, self.volatility)
were replaced by the line
baseMove = bias
which of the following Figure 2’s is most likely to be produced by
the test code? (10 points)
pythonhomeworkhelp.com
A B
C D
pythonhomeworkhelp.com
import pylab import
random
# Global constant
TRADING_DAYS_PER_YEAR = 200
class Stock:
def init (self, ticker, volatility): self.volatility =
volatility self.ticker = ticker
self.price = None self.history
= []
def setPrice(self, price): self.price =
price
self.history.append(price) def
getPrice(self):
return self.price def
getTicker(self):
return self.ticker def
makeMove(self, bias):
if self.price == 0.0: return
baseMove = bias + random.uniform(-self.volatility, self.volatility)
self.price = self.price * (1.0 + baseMove)
if self.price < 0.01: self.price =
0.0
self.history.append(self.price)
pythonhomeworkhelp.com
class Market:
def init (self): self.sectors =
[] self.tickers = set()
def addSector(self, sect):
if sect.getName() in self.sectors:
raise ValueError('Duplicate sector')
for t in sect.getTickers(): if t in
self.tickers:
raise ValueError('A ticker in sect already in
market') else: self.tickers.add(t)
self.sectors.append(sect)
def getSectors(self):
return self.sectors def
getStocks(self):
stocks = []
for s in self.sectors:
stocks = stocks + s.getStocks()
return stocks
def moveAllStocks(self):
vals = []
for s in self.sectors:
vals = vals + s.moveAllStocks()
return vals
pythonhomeworkhelp.com
class Sector:
def init (self, sectorName, bias): self.tickers =
set() self.sectorName = sectorName
self.stocks = []
self.bias = bias self.origBias =
bias
def addStock(self, stk):
if stk.getTicker() in self.tickers: raise
ValueError('Duplicate ticker')
self.tickers.add(stk.getTicker())
self.stocks.append(stk)
def getStocks(self): return
self.stocks
def getTickers(self): return
self.tickers
def setBias(self, newBias): self.bias =
newBias
def getBias(self): return
self.bias
def getOrigBias(self): return
self.origBias
def sameSector(self, other):
return self.sectorName == other.sectorName def
getName(self):
return self.sectorName def
pythonhomeworkhelp.com
moveAllStocks(self):
vals = []
for stock in self.stocks:
stock.makeMove(self.bias)
vals.append(stock.getPrice()
)
return vals
def generateSector(sectorSize,
sectorName, bias): sect =
Sector(sectorName, bias)
for i in range(sectorSize):
ticker = sectorName + 'Ticker ' + str(i)
volatility = random.uniform(0.01,
0.04) stk = Stock(ticker, volatility)
stk.setPrice(100)
try:
sect.addStock(stk)
except ValueError:
# Tickers are all different by construction, so this should
never # happen
print 'Error in generate stocks, should never reach
here.' raise AssertionError
return sect
pythonhomeworkhelp.com
def simMkt(mkt, numDays):
endPrices = []
for i in range(numDays):
if i%(TRADING_DAYS_PER_YEAR/4) == 0:
for s in mkt.getSectors():
newBias = s.getOrigBias() + random.gauss(0, 2*s.getOrigBias())
s.setBias(newBias)
vals = mkt.moveAllStocks() vals =
pylab.array(vals)
mean = vals.sum()/float(len(vals))
endPrices.append(mean)
return endPrices
def plotValueOverTime(endPrices, title):
pylab.plot(endPrices) pylab.title(title)
pylab.xlabel('Days') pylab.ylabel('Price')
def
generateMarket(numSe
ctors, sectorSize, bias):
mkt = Market()
for n in range(numSectors):
sect = generateSector(sectorSize,
'Sector ' + str(n), bias)
mkt.addSector(sect)
return mkt
pythonhomeworkhelp.com
def
plotDistributionAtEnd(m
kt, title): prices = []
for s in
mkt.getStocks():
prices.append(s.ge
tPrice())
pylab.hist(prices, bins =
20) pylab.title(title)
pylab.xlabel('Last Sale')
pylab.ylabel('Number of
Securities')
pythonhomeworkhelp.com
import pylab, random
class Stock(object):
def __init__(self, price, distribution, vol):
self.price = price
self.history = [price]
self.distribution = distribution
self.vol = vol
self.lastChangeInfluence = 0.0
def setPrice(self, price):
self.price = price
self.history.append(price)
def getPrice(self):
return self.price
def makeMove(self, bias, mo):
oldPrice = self.price
baseMove = self.distribution(self.vol) + bias
self.price = self.price * (1.0 + baseMove)
self.price += mo*random.choice([0.0,
1.0])*self.lastChangeInfluence
self.history.append(self.price)
change = self.price - oldPrice
if change >= 0:
self.lastChangeInfluence = min(change, oldPrice*0.01)
else:
self.lastChangeInfluence = max(change, -oldPrice*0.01)
pythonhomeworkhelp.com
Solution
def showHistory(self, fig, test):
pylab.figure(fig)
pylab.plot(self.history)
pylab.title('Closing Prices, Test ' + test)
pylab.xlabel('Day')
pylab.ylabel('Price')
class SimpleMarket(object):
def __init__(self, numStks, volUB):
self.stks = []
self.bias = 0.0
for n in range(numStks):
volatility = random.uniform(0, volUB)
distribution = lambda vol: random.gauss(0.0, vol)
stk = Stock(100.0, distribution, volatility)
self.addStock(stk)
def addStock(self, stk):
self.stks.append(stk)
def setBias(self, bias):
self.bias = bias
def getBias(self):
return self.bias
def getStocks(self):
return self.stks[:]
pythonhomeworkhelp.com
def move(self, mo):
prices = []
for s in self.stks:
s.makeMove(self.bias, mo)
prices.append(s.getPrice())
return prices
class Market(SimpleMarket):
def __init__(self, numStks, volUB,
dailyBiasRange):
SimpleMarket.__init__(self, numStks, volUB)
self.dailyBiasRange = dailyBiasRange
def move(self, mo):
prices = []
dailyBias =
random.gauss(self.dailyBiasRange[0],
self.dailyBiasRange[1])
for s in self.stks:
s.makeMove(self.bias + dailyBias, mo)
prices.append(s.getPrice())
return prices
def simMkt(mkt, numDays, mo):
endPrices = []
for i in range(numDays):
pythonhomeworkhelp.com
vals = mkt.move(mo)
vals = pylab.array(vals)
mean = vals.sum()/float(len(vals))
endPrices.append(mean)
return endPrices
def plotAverageOverTime(endPrices, title):
pylab.plot(endPrices)
pylab.title(title)
pylab.xlabel('Days')
pylab.ylabel('Price')
def plotDistributionAtEnd(mkt, title, color):
prices = []
sumSoFar = 0
for s in mkt.getStocks():
prices.append(s.getPrice())
sumSoFar += s.getPrice()
mean = sumSoFar/float(len(prices))
prices.sort()
pylab.plot(prices, color)
pylab.axhline(mean, color = color)
pylab.title(title)
pylab.xlabel('Stock')
pylab.ylabel('Last Sale')
pylab.semilogy()
pythonhomeworkhelp.com
def runTrial(showHistory, test, p):
colors = ['b','g','r','c','m','y','k']
mkt = Market(p['numStocks'], p['volUB'],
p['dailyBiasRange'])
mkt.setBias(p['bias'])
endPrices = simMkt(mkt, p['numDays'],
p['mo'])
pylab.figure(1)
plotAverageOverTime(endPrices, 'Average
Closing Prices')
pylab.figure(2)
plotDistributionAtEnd(mkt, 'Distribution of Prices', colors[test%len(colors)])
if showHistory:
for s in mkt.getStocks():
s.showHistory(test+2, str(test))
def runTest(numTrials):
#Constants used in testing
numDaysPerYear = 200.0
params = {}
params['numDays'] = 200
params['numStocks'] = 500
params['bias'] = 0.1/numDaysPerYear #General market bias
pythonhomeworkhelp.com
params['volUB'] = 12.0/numDaysPerYear
#Upper bound on volatility for a stock
params['mo'] = 1.1/numDaysPerYear
#Momentum factor
params['dailyBiasRange'] = (0.0, 4.0/200.0)
for t in range(1, numTrials+1):
runTrial(True, t, params)
runTest(3)
pylab.show()
pythonhomeworkhelp.com

More Related Content

What's hot (20)

PPT
Java căn bản - Chapter6
Vince Vo
 
PDF
Multidimensional arrays in C++
Ilio Catallo
 
PPTX
12. Exception Handling
Intro C# Book
 
PDF
Chap 6 c++
Venkateswarlu Vuggam
 
PPT
Chap 6 c++
Venkateswarlu Vuggam
 
PDF
Arrays in C++
Ilio Catallo
 
PPTX
Python
Sameeksha Verma
 
PPTX
06.Loops
Intro C# Book
 
PDF
Python programming : Abstract classes interfaces
Emertxe Information Technologies Pvt Ltd
 
PDF
Introduction to python
Marian Marinov
 
PDF
Dive Into PyTorch
Illarion Khlestov
 
PDF
Chapter 5
EasyStudy3
 
DOC
C tech questions
vijay00791
 
PPTX
07. Arrays
Intro C# Book
 
PPT
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Enthought, Inc.
 
PPTX
Python programing
hamzagame
 
PDF
Chap 5 c++
Venkateswarlu Vuggam
 
PPTX
13 recursion-120712074623-phpapp02
Abdul Samee
 
PPTX
Chapter 2
application developer
 
PPT
Parameters
James Brotsos
 
Java căn bản - Chapter6
Vince Vo
 
Multidimensional arrays in C++
Ilio Catallo
 
12. Exception Handling
Intro C# Book
 
Arrays in C++
Ilio Catallo
 
06.Loops
Intro C# Book
 
Python programming : Abstract classes interfaces
Emertxe Information Technologies Pvt Ltd
 
Introduction to python
Marian Marinov
 
Dive Into PyTorch
Illarion Khlestov
 
Chapter 5
EasyStudy3
 
C tech questions
vijay00791
 
07. Arrays
Intro C# Book
 
Scientific Computing with Python Webinar March 19: 3D Visualization with Mayavi
Enthought, Inc.
 
Python programing
hamzagame
 
13 recursion-120712074623-phpapp02
Abdul Samee
 
Parameters
James Brotsos
 

Similar to Quality Python Homework Help (20)

DOCX
Study material ip class 12th
animesh dwivedi
 
PPTX
Introduction to Python Programming.pptx
Python Homework Help
 
PPTX
CS 151 Graphing lecture
Rudy Martinez
 
PPTX
Perfect Python Homework Help
Python Homework Help
 
DOCX
NPTEL QUIZ.docx
GEETHAR59
 
PPTX
Python Programming Homework Help.pptx
Python Homework Help
 
PDF
Python Homework Sample
Terrill Shanahan
 
PDF
Lecture 8 - Feature Engineering and Optimization, a lecture in subject module...
Maninda Edirisooriya
 
PPTX
2.3 SciPy library explained detialed 1.pptx
RaveshRawal
 
PPTX
CS151 Deep copy
Rudy Martinez
 
PPTX
Signals and Systems Homework Help.pptx
Matlab Assignment Experts
 
PDF
BUilt in Functions and Simple programs in R.pdf
karthikaparthasarath
 
PDF
MATLAB-Cheat-Sheet-for-Data-Science_LondonSchoolofEconomics (1).pdf
Central university of Haryana
 
PPTX
Python Cheat Sheet Presentation Learning
Naseer-ul-Hassan Rehman
 
PDF
E10
lksoo
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Introduction to Python Programming.pptx
Python Homework Help
 
PPTX
Matlab Assignment Help
Matlab Assignment Experts
 
PPTX
Basic Python Programming.pptx
Python Homework Help
 
PPTX
Data Science for Folks Without (or With!) a Ph.D.
Douglas Starnes
 
Study material ip class 12th
animesh dwivedi
 
Introduction to Python Programming.pptx
Python Homework Help
 
CS 151 Graphing lecture
Rudy Martinez
 
Perfect Python Homework Help
Python Homework Help
 
NPTEL QUIZ.docx
GEETHAR59
 
Python Programming Homework Help.pptx
Python Homework Help
 
Python Homework Sample
Terrill Shanahan
 
Lecture 8 - Feature Engineering and Optimization, a lecture in subject module...
Maninda Edirisooriya
 
2.3 SciPy library explained detialed 1.pptx
RaveshRawal
 
CS151 Deep copy
Rudy Martinez
 
Signals and Systems Homework Help.pptx
Matlab Assignment Experts
 
BUilt in Functions and Simple programs in R.pdf
karthikaparthasarath
 
MATLAB-Cheat-Sheet-for-Data-Science_LondonSchoolofEconomics (1).pdf
Central university of Haryana
 
Python Cheat Sheet Presentation Learning
Naseer-ul-Hassan Rehman
 
E10
lksoo
 
Python Homework Help
Python Homework Help
 
Introduction to Python Programming.pptx
Python Homework Help
 
Matlab Assignment Help
Matlab Assignment Experts
 
Basic Python Programming.pptx
Python Homework Help
 
Data Science for Folks Without (or With!) a Ph.D.
Douglas Starnes
 
Ad

More from Python Homework Help (19)

PPTX
Python Homework Help
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Complete my Python Homework
Python Homework Help
 
PPTX
Introduction to Python Dictionary.pptx
Python Homework Help
 
PPTX
Introduction to Python Programming.pptx
Python Homework Help
 
PPTX
Introduction to Python Programming.pptx
Python Homework Help
 
PPTX
Introduction to Python Programming.pptx
Python Homework Help
 
PPTX
Introduction to Python Programming.pptx
Python Homework Help
 
PPTX
Introduction to Python Programming.pptx
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Python Programming Homework Help
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
PPTX
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Complete my Python Homework
Python Homework Help
 
Introduction to Python Dictionary.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Python Programming Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework Help
 
Ad

Recently uploaded (20)

PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
community health nursing question paper 2.pdf
Prince kumar
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 

Quality Python Homework Help

  • 1. For any help regarding Python Homework Help visit : - https://www.pythonhomeworkhelp.com/, Email :- [email protected] or call us at :- +1 678 648 4277
  • 2. Here are some practice quiz questions (taken mostly from last year’s final). 1)Is each of the following True or False 1. In Python, the method sortof class listhas a side effect. 2.When run on the same inputs, an exponential algorithm will always take longer than a polynomial algorithm. 3. Newton’s method is based upon successive approximation. 4.Constructing a black box test suite involves looking at the control flow of the code to be tested. 5. Python classes enforce data hiding. 2) The code below produces three plots. Match each of the plots on the next page with the appropriate figure (Figure 1, Figure 2, or Figure 3). import pylab y1 = [] y2 = [] y3 = [] for i in range(20): y1.append(300*i) y2.append(i**3) Problem pythonhomeworkhelp.com
  • 3. y2.append(i**3) y3.append(2**i) pylab.figure(1) pylab.plot(y1) pylab.figure(2) pylab.plot(y2) pylab.figure(3) pylab.plot(y3) pylab.semilogy() pythonhomeworkhelp.com
  • 4. 3) Can the following specification be implemented? If not, explain why. def f(x, e): “““ x and e are floats returns y, a float, such that x-e <= y*y <= x+e””” 4) Write a Python program that satisfies the following specification. def f(L1, L2): “““ L1 and L2 are lists of integers returns the element-wise product of L1 and L2. If the lists are of different length, it uses 1 for the missing coefficients. E.g., if L1 = [2, 2, 3] and L2 = [7, 5, 6, 7] it returns [14, 10, 18, 7] side effects: none ””” pythonhomeworkhelp.com
  • 5. The following questions all refer to the code you were asked to study in preparation for this exam. They also assume that the following code is used to test the program. (For your convenience, a copy of the posted code is at the end of this quiz. Feel free to separate it from the rest of the quiz.) Warning: The code at the end of this is NOT the same as the code you have been given to study. It may not be worth your time to study this code carefully enough to answer all of the practice questions, but these questions should give you the flavor of the kinds of questions we might ask about the code supplied this term. numDays = 500 bias = 0.11/200.0 numSectors = 1 sectorSize = 500 numTrials = 5 print 'Testing Model on', numDays, 'days' mean = 0.0 for i in range(numTrials): pylab.figure(1) mkt = generateMarket(numSectors, sectorSize, bias) endPrices = simMkt(mkt, numDays) mean += endPrices[-1] title = 'Closing Prices With ' + str(numSectors) + ' Sectors' plotValueOverTime(endPrices, title) pylab.figure(2) plotDistributionAtEnd(mkt, title) meanClosing = mean/float(numTrials) print 'Mean closing with', numSectors, 'sectors is', meanClosing pythonhomeworkhelp.com
  • 6. 1) If, in class Stock, the line self.price = self.price * (1.0 + baseMove) were replaced with the line self.price = self.price * baseMove which of the following best describes the expected mean value of the market after 200 days: a.Close to 111 b.Close to 100 c.Close to 50 d.Close to 0 e.About the same as with the original code 2)Consider running the above test code twice, once with numSectors = 1 and once with numSectors = 20. Each will produce a Figure 1. Now consider running a linear regression to fit a line to each of the curves produced in the Figure 1’s for each test. Would you expect the average mean square error of the fits for numSectors = 20to be: pythonhomeworkhelp.com
  • 7. a.Smaller than the average mean square error of the fits for numSectors = 1. b.Larger than the average mean square error of the fits for numSectors = 1. c.About the same as the average mean square error of the fits for numSectors = 1. d.None of the above. 5.3) Characterize the algorithmic efficiency of generateMarket. 5.4) If in Stock.makeMove, the line baseMove=bias+random.uniform(-self.volatility, self.volatility) were replaced by the line baseMove = bias which of the following Figure 2’s is most likely to be produced by the test code? (10 points) pythonhomeworkhelp.com
  • 9. import pylab import random # Global constant TRADING_DAYS_PER_YEAR = 200 class Stock: def init (self, ticker, volatility): self.volatility = volatility self.ticker = ticker self.price = None self.history = [] def setPrice(self, price): self.price = price self.history.append(price) def getPrice(self): return self.price def getTicker(self): return self.ticker def makeMove(self, bias): if self.price == 0.0: return baseMove = bias + random.uniform(-self.volatility, self.volatility) self.price = self.price * (1.0 + baseMove) if self.price < 0.01: self.price = 0.0 self.history.append(self.price) pythonhomeworkhelp.com
  • 10. class Market: def init (self): self.sectors = [] self.tickers = set() def addSector(self, sect): if sect.getName() in self.sectors: raise ValueError('Duplicate sector') for t in sect.getTickers(): if t in self.tickers: raise ValueError('A ticker in sect already in market') else: self.tickers.add(t) self.sectors.append(sect) def getSectors(self): return self.sectors def getStocks(self): stocks = [] for s in self.sectors: stocks = stocks + s.getStocks() return stocks def moveAllStocks(self): vals = [] for s in self.sectors: vals = vals + s.moveAllStocks() return vals pythonhomeworkhelp.com
  • 11. class Sector: def init (self, sectorName, bias): self.tickers = set() self.sectorName = sectorName self.stocks = [] self.bias = bias self.origBias = bias def addStock(self, stk): if stk.getTicker() in self.tickers: raise ValueError('Duplicate ticker') self.tickers.add(stk.getTicker()) self.stocks.append(stk) def getStocks(self): return self.stocks def getTickers(self): return self.tickers def setBias(self, newBias): self.bias = newBias def getBias(self): return self.bias def getOrigBias(self): return self.origBias def sameSector(self, other): return self.sectorName == other.sectorName def getName(self): return self.sectorName def pythonhomeworkhelp.com
  • 12. moveAllStocks(self): vals = [] for stock in self.stocks: stock.makeMove(self.bias) vals.append(stock.getPrice() ) return vals def generateSector(sectorSize, sectorName, bias): sect = Sector(sectorName, bias) for i in range(sectorSize): ticker = sectorName + 'Ticker ' + str(i) volatility = random.uniform(0.01, 0.04) stk = Stock(ticker, volatility) stk.setPrice(100) try: sect.addStock(stk) except ValueError: # Tickers are all different by construction, so this should never # happen print 'Error in generate stocks, should never reach here.' raise AssertionError return sect pythonhomeworkhelp.com
  • 13. def simMkt(mkt, numDays): endPrices = [] for i in range(numDays): if i%(TRADING_DAYS_PER_YEAR/4) == 0: for s in mkt.getSectors(): newBias = s.getOrigBias() + random.gauss(0, 2*s.getOrigBias()) s.setBias(newBias) vals = mkt.moveAllStocks() vals = pylab.array(vals) mean = vals.sum()/float(len(vals)) endPrices.append(mean) return endPrices def plotValueOverTime(endPrices, title): pylab.plot(endPrices) pylab.title(title) pylab.xlabel('Days') pylab.ylabel('Price') def generateMarket(numSe ctors, sectorSize, bias): mkt = Market() for n in range(numSectors): sect = generateSector(sectorSize, 'Sector ' + str(n), bias) mkt.addSector(sect) return mkt pythonhomeworkhelp.com
  • 14. def plotDistributionAtEnd(m kt, title): prices = [] for s in mkt.getStocks(): prices.append(s.ge tPrice()) pylab.hist(prices, bins = 20) pylab.title(title) pylab.xlabel('Last Sale') pylab.ylabel('Number of Securities') pythonhomeworkhelp.com
  • 15. import pylab, random class Stock(object): def __init__(self, price, distribution, vol): self.price = price self.history = [price] self.distribution = distribution self.vol = vol self.lastChangeInfluence = 0.0 def setPrice(self, price): self.price = price self.history.append(price) def getPrice(self): return self.price def makeMove(self, bias, mo): oldPrice = self.price baseMove = self.distribution(self.vol) + bias self.price = self.price * (1.0 + baseMove) self.price += mo*random.choice([0.0, 1.0])*self.lastChangeInfluence self.history.append(self.price) change = self.price - oldPrice if change >= 0: self.lastChangeInfluence = min(change, oldPrice*0.01) else: self.lastChangeInfluence = max(change, -oldPrice*0.01) pythonhomeworkhelp.com Solution
  • 16. def showHistory(self, fig, test): pylab.figure(fig) pylab.plot(self.history) pylab.title('Closing Prices, Test ' + test) pylab.xlabel('Day') pylab.ylabel('Price') class SimpleMarket(object): def __init__(self, numStks, volUB): self.stks = [] self.bias = 0.0 for n in range(numStks): volatility = random.uniform(0, volUB) distribution = lambda vol: random.gauss(0.0, vol) stk = Stock(100.0, distribution, volatility) self.addStock(stk) def addStock(self, stk): self.stks.append(stk) def setBias(self, bias): self.bias = bias def getBias(self): return self.bias def getStocks(self): return self.stks[:] pythonhomeworkhelp.com
  • 17. def move(self, mo): prices = [] for s in self.stks: s.makeMove(self.bias, mo) prices.append(s.getPrice()) return prices class Market(SimpleMarket): def __init__(self, numStks, volUB, dailyBiasRange): SimpleMarket.__init__(self, numStks, volUB) self.dailyBiasRange = dailyBiasRange def move(self, mo): prices = [] dailyBias = random.gauss(self.dailyBiasRange[0], self.dailyBiasRange[1]) for s in self.stks: s.makeMove(self.bias + dailyBias, mo) prices.append(s.getPrice()) return prices def simMkt(mkt, numDays, mo): endPrices = [] for i in range(numDays): pythonhomeworkhelp.com
  • 18. vals = mkt.move(mo) vals = pylab.array(vals) mean = vals.sum()/float(len(vals)) endPrices.append(mean) return endPrices def plotAverageOverTime(endPrices, title): pylab.plot(endPrices) pylab.title(title) pylab.xlabel('Days') pylab.ylabel('Price') def plotDistributionAtEnd(mkt, title, color): prices = [] sumSoFar = 0 for s in mkt.getStocks(): prices.append(s.getPrice()) sumSoFar += s.getPrice() mean = sumSoFar/float(len(prices)) prices.sort() pylab.plot(prices, color) pylab.axhline(mean, color = color) pylab.title(title) pylab.xlabel('Stock') pylab.ylabel('Last Sale') pylab.semilogy() pythonhomeworkhelp.com
  • 19. def runTrial(showHistory, test, p): colors = ['b','g','r','c','m','y','k'] mkt = Market(p['numStocks'], p['volUB'], p['dailyBiasRange']) mkt.setBias(p['bias']) endPrices = simMkt(mkt, p['numDays'], p['mo']) pylab.figure(1) plotAverageOverTime(endPrices, 'Average Closing Prices') pylab.figure(2) plotDistributionAtEnd(mkt, 'Distribution of Prices', colors[test%len(colors)]) if showHistory: for s in mkt.getStocks(): s.showHistory(test+2, str(test)) def runTest(numTrials): #Constants used in testing numDaysPerYear = 200.0 params = {} params['numDays'] = 200 params['numStocks'] = 500 params['bias'] = 0.1/numDaysPerYear #General market bias pythonhomeworkhelp.com
  • 20. params['volUB'] = 12.0/numDaysPerYear #Upper bound on volatility for a stock params['mo'] = 1.1/numDaysPerYear #Momentum factor params['dailyBiasRange'] = (0.0, 4.0/200.0) for t in range(1, numTrials+1): runTrial(True, t, params) runTest(3) pylab.show() pythonhomeworkhelp.com