y1 = 2008 # Make this zero to turn off the lower bound subDict = dict() for curName in stockNameVec: # Download the data stock = downloadStock(curName, y1,1,1,2010,0,0) # Strip out everything except for the Adjusted Close Price and put it in a dictionary as a Series subDict[curName] = pd.Series(stock['Adj Close'].as_matrix(), index=stock.Date) tickerDF = pd.DataFrame(subDict) # Then make a new data frame with just the adjusted closes. firstDayOfData(tickerDF) filename = "ticker.html" plotTitle = "Stocks to Plot" plotTimeSeriesDF(filename, plotTitle, tickerDF) # Translate the daily prices into yearly rates of return subDict = dict() for curName in tickerDF: yearRecord, rate = getYearlyReturn(tickerDF[curName], 2000, 2016) subDict[curName] = pd.Series(rate, index=yearRecord) yearlyReturnDF = pd.DataFrame(subDict) mu, sigma, covar = getStats(yearlyReturnDF, y1) targetReturn = mu.min() w1, r1, s1 = solveMarkowitzWithShorting(yearlyReturnDF, targetReturn, y1) targetReturn = mu.max() w2, r2, s2 = solveMarkowitzWithShorting(yearlyReturnDF, targetReturn, y1)
for sym in testSym: f = feed.getBars(sym) adjCloseList = [] index = [] for bar in f: adjCloseList.append(bar.getAdjClose()) index.append(bar.getDateTime()) # print "{0} {1}".format(bar.getDateTime(), bar.getAdjClose()) subDict[sym] = pd.Series(adjCloseList, index=index) testDF = pd.DataFrame(subDict) # Then make a new data frame with just the adjusted closes. # (filename, plotTitle, DF) plotTimeSeriesDF("trash.html", "TQQQ_Sim is Fake", testDF) # # Function to write yahoo csv def yahooCsvName(sym, year): return "{0}-{1}-yahoofinance.csv".format(sym,year) keys = ["Date","Open","High","Low","Close","Volume","Adj Close"] # 2007-12-31,51.57,51.68,51.209999,51.220001,70135600,47.283854 yearsToWrite = set([d.year for d in fakeIndex]) for curYear in yearsToWrite: outFile = open(yahooCsvName("TQQQ_Sim", curYear), "w") outFile.write(",".join(keys)+"\n")
p1.line(np.array(stockPrice.index), callPrice.as_matrix(), line_color=curColor, line_width=2, line_dash=[2,2]) # p1.line(np.array(stockPrice.index), stockPrice.as_matrix(), line_color=curColor, legend=str(curName), line_width=2) # p1.line(np.array(stockPrice.index), callPrice.as_matrix(), line_color=curColor, legend=str(curName), line_width=2, line_dash=[2,2]) show(p1) # Convergence of the option mean value? c0 = callHistory.iloc[0][0] print ((callHistory.irow(numTimeSteps) - c0)/c0).mean() convergeDF = pd.DataFrame(np.cumsum(((callHistory.irow(numTimeSteps) - c0)/c0))/range(1,numTrajectories+1)) convergeDF.index = range(1,numTrajectories+1) # Index by trajectory # Make a quick convergence plot filename = "convergence.html" plotTitle = "Convergence" mt.plotTimeSeriesDF(filename, plotTitle, convergeDF.irow(np.array(range(0,numTrajectories+1, numTrajectories/20)[1:])-1 )) # Only show 20 pts # TODO: Make those plots that show how the time value decays and snaps to the straight-line diagrams (callHistory.irow(numTimeSteps)-c0)/c0 percentTimesLoseItAll = 1. - len(np.where(callHistory.irow(numTimeSteps) > 0)[0])*1./numTrajectories print percentTimesLoseItAll debugPutReturns = False if debugPutReturns: s0 = 60
subDict[curName] = pd.Series(stock['Adj Close'].as_matrix(), index=stock.Date) # subDict[curName] = pd.Series(stock['Close'].as_matrix(), index=stock.Date) tickerDF = pd.DataFrame(subDict) # Then make a new data frame with just the adjusted closes. # Check to make sure that oldest data is first in the series # if stock.Date.iloc[0] > stock.Date.iloc[-1]: if tickerDF.index[0] > tickerDF.index[-1]: # If first date is greater than last date, then flip tickerDF = tickerDF.iloc[::-1] # Plot the stocks filename = "ticker.html" plotTitle = "Stocks to Plot" plotTimeSeriesDF(filename, plotTitle, tickerDF) # Get the linear weekly returns weeklyReturnDF = getWeeklyReturn(tickerDF) nu = weeklyReturnDF.mean().as_matrix() sigma = weeklyReturnDF.std().as_matrix() covar = weeklyReturnDF.cov().as_matrix() # === Solve the equations from 15.6 numStocks = len(nu) one = np.ones_like(nu) # Need a ones vector mu = nu + 0.5*sigma**2 # First turn the nu into mu (log mean) # Setting gamma = 0 gives log-optimal solution, can find the w's directly without lambda