def plot_funds(tickerlist, initial, start, end): '''Plot a fund by its ticker symbol, normalized to a given initial value. ''' numdays = (end - start).days daysinyear = 365.0 print '%9s %9s %9s %9s' % ('Ticker', 'daily', 'CC', 'abs') # For testing, use something like # FUSVX = yahoo('FUSVX', datetime.datetime(2012, 10, 1), # datetime.datetime(2013, 4, 1), # asobject=True) for i, ticker in enumerate(tickerlist): # This gives a runtime warning for SCAL, and all the aclose vals # come out zero. Catching a RuntimeWarning isn't as simple as try; # http://stackoverflow.com/questions/10519237/python-how-to-avoid-runtimewarning-in-function-definition # http://stackoverflow.com/questions/9349434/how-do-i-check-for-numeric-overflow-without-getting-a-warning-in-python try: fund_data = yahoo(ticker, start, end, asobject=True) except: print "Couldn't get data for", ticker continue # Guard against failures of quotes_historical_yahoo; # without this check you'll see more uncatchable RuntimeWarnings. if fund_data['aclose'][0] == 0: print ticker, ": First adjusted close is 0!" continue # Calculate effective daily-compounded interest rate fixed_pct = fund_data['aclose'][-1] / fund_data['aclose'][0] - 1. Rcc = daysinyear / numdays * \ numpy.log(fund_data['aclose'][-1] / fund_data['aclose'][0]) # Convert CC return to daily-compounded return: Rdaily = daysinyear * (math.exp(Rcc / daysinyear) - 1.) # Another attempt to compute the daily rate, but it's wrong. # Reff = daysinyear * (math.exp(math.log(fund_data['aclose'][-1] # - fund_data['aclose'][0]) # /numdays) - 1) print "%9s %9.2f %9.2f %9.2f" % (ticker, Rdaily * 100, Rcc * 100, fixed_pct * 100) # Normalize to the initial investment: fund_data['aclose'] *= initial / fund_data['aclose'][0] # and plot ax1.plot_date(x=fund_data['date'], y=fund_data['aclose'], fmt=pick_color(i), label=ticker)
def plot_funds(tickerlist, initial, start, end): '''Plot a fund by its ticker symbol, normalized to a given initial value. ''' numdays = (end - start).days daysinyear = 365.0 print '%9s %9s %9s %9s' % ('Ticker', 'daily', 'CC', 'abs') # For testing, use something like # FUSVX = yahoo('FUSVX', datetime.datetime(2012, 10, 1), # datetime.datetime(2013, 4, 1), # asobject=True) for i, ticker in enumerate(tickerlist): # This gives a runtime warning for SCAL, and all the aclose vals # come out zero. Catching a RuntimeWarning isn't as simple as try; # http://stackoverflow.com/questions/10519237/python-how-to-avoid-runtimewarning-in-function-definition # http://stackoverflow.com/questions/9349434/how-do-i-check-for-numeric-overflow-without-getting-a-warning-in-python try: fund_data = yahoo(ticker, start, end, asobject=True) except: print "Couldn't get data for", ticker continue # Guard against failures of quotes_historical_yahoo; # without this check you'll see more uncatchable RuntimeWarnings. if fund_data['aclose'][0] == 0: print ticker, ": First adjusted close is 0!" continue # Calculate effective daily-compounded interest rate fixed_pct = fund_data['aclose'][-1]/fund_data['aclose'][0] - 1. Rcc = daysinyear / numdays * \ numpy.log(fund_data['aclose'][-1] / fund_data['aclose'][0]) # Convert CC return to daily-compounded return: Rdaily = daysinyear * (math.exp(Rcc / daysinyear) - 1.) # Another attempt to compute the daily rate, but it's wrong. # Reff = daysinyear * (math.exp(math.log(fund_data['aclose'][-1] # - fund_data['aclose'][0]) # /numdays) - 1) print "%9s %9.2f %9.2f %9.2f" % (ticker, Rdaily*100, Rcc*100, fixed_pct*100) # Normalize to the initial investment: fund_data['aclose'] *= initial / fund_data['aclose'][0] # and plot ax1.plot_date(x=fund_data['date'], y=fund_data['aclose'], fmt=pick_color(i), label=ticker)
def Vol_Smile(ticker,expiration,S,K,T,r,call_price): implied=1. minimum_value=1000 for i in range(10000): sigma=0.0001*(1+i) d1=(sp.log(S/K)+(r+sigma*sigma/2.)*T)/(sigma*sp.sqrt(T)) d2=d1-sigma*sp.sqrt(T) call_iv=S*sp.stats.norm.cdf(d1)-K*sp.exp(-r*T)*sp.stats.norm.cdf(d2) if call_iv-call_price < minimum_value: minimum_value=call_iv-call_price implied=sigma i=k return implied begdate=datetime.date(2011,1,1) enddate=datetime.date.today() option_data=Options(ticker,'yahoo').get_call_data(expiry=expiration) price_data=yahoo(ticker,begdate,enddate,asobject=True,adjusted=True)
""" # Lower Partial Standard Deviation import pandas as pd import scipy.stats as stats import numpy as np import datetime as dt from matplotlib.finance import quotes_historical_yahoo as yahoo ticker='IBM' begdate=(2008,12,31) enddate=(2009,11,1) # For the risk free rate, using Fama-French daily dataset. The data already formatted has been downloaded from Yan's website. price=yahoo(ticker,begdate,enddate,asobject=True,adjusted=True) returns=(price.aclose[1:]-price.aclose[:-1])/price.aclose[1:] x=pd.DataFrame(data=returns,index=price.date[:-1],columns=['returns']) ff=pd.load('ffDaily.pickle') final_data=pd.merge(x,ff,left_index=True,right_index=True) premium=final_data.returns-final_data.Rf LPSD=np.std(premium[premium > 0])*np.sqrt(252) print "LPSD is " + str(LPSD)
import nltk from nltk.parse.cpchart import CInsideChartParser from nltk.grammar import parse_cpcfg, Nonterminal from scipy.stats import norm from matplotlib.finance import quotes_historical_yahoo as yahoo if __name__ == "__main__": import datetime import numpy as np date1 = datetime.date(2010, 10, 13) date2 = datetime.date(2010, 11, 26) quotes = yahoo("uup", date1, date2) if (len(quotes) == 0): raise SystemExit test = np.diff([100 * np.log(q[2]) for q in quotes]) test = np.round(test, decimals=3).tolist() print test #test = [-0.5,-0.5, 0,0, 0.5, 0.5] densityEmission = { Nonterminal('e1') : lambda x : norm.logpdf(x, loc=0, scale=1), Nonterminal('e2') : lambda x : norm.logpdf(x, loc=0.5, scale=1), Nonterminal('e3') : lambda x : norm.logpdf(x, loc=-0.5, scale=1), } emission = { Nonterminal('e1') : lambda x : norm.rvs(x, loc=0, scale=1), Nonterminal('e2') : lambda x : norm.rvs(x, loc=0.5, scale=1), Nonterminal('e3') : lambda x : norm.rvs(x, loc=-0.5, scale=1), } grammar = parse_cpcfg(""" S -> UPTRI [0.5] | BOTRI [0.5]
""" # Candlesticks indicator and representation from matplotlib.dates import DateFormatter as df, WeekdayLocator as wl, HourLocator as hl, DayLocator as dl, MONDAY import matplotlib.pyplot as plt from matplotlib.finance import quotes_historical_yahoo as yahoo, candlestick as cs, candlestick2 as cs2, plot_day_summary as pds import numpy as np from matplotlib import rc, rcParams begdate=(2014, 9, 27) enddate=(2014, 10, 27) ticker='AAPL' stock_price=yahoo(ticker,begdate,enddate) if len(stock_price)==0: raise SystemExit rcParams['xtick.major.pad']='15' figure,ax=plt.subplots() ax.xaxis.set_major_locator(wl(MONDAY)) ax.xaxis.set_major_formatter(df("%b %d")) ax.xaxis.set_minor_locator(dl()) ax.xaxis.set_minor_formatter(df("%d")) pds(ax,stock_price,ticksize=1) cs(ax,stock_price,width=0.5) rc('xtick', labelsize=8)