def main(plot):
    
    # instruments and talbename in sql
    instrument = "ibm"
    tableName = "newyorkexchange.ibm_historicalquotes_newyork"
    
    # create instance to connect Mysql
    cnx = cnxStock()
    # create instance to query Mysql data base
    query = historicalPriceQuery(instrument, tableName)    
    df = query.pandasQuerySingle(cnx.connect())
    #close connection
    cnx.close_connection()
    
    # feed data from PyAlgoTrade back testing
    feed = MyLibrary.pandas_feed_mysql.DataFrameBarFeed(df, instrument, barfeed.Frequency.DAY)
    
    smaPeriod = 163
    strat = sma_crossover.SMACrossOver(feed, instrument, smaPeriod)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, True, False, True)
        plt.getInstrumentSubplot(instrument).addDataSeries("sma", strat.getSMA())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()
def main(plot):
    initialCash = 10000
    instrumentsByClass = {
        "US Stocks": ["ibm"],
        "Foreign Stocks": ["ulbi"],
        "US 10 Year Government Bonds": ["alex"],
        "Real Estate": ["cx"],
        "Commodities": ["tpvg"],
    }

    # Download the bars.
    instruments = ["umc"]
    for assetClass in instrumentsByClass:
        instruments.extend(instrumentsByClass[assetClass])
    tableNames = dict()
    for instrument  in instruments :
        tableName = str("newyorkexchange.%s_historicalquotes_newyork" %instrument)
        tableNames[instrument] = tableName
    
    try :
        # create instance to connect Mysql
        cnx = cnxStock()
        # create instance to query Mysql data base
        query = historicalPriceQuery(instruments, tableNames)
        dfs = query.pandasQueryMulitple(cnx.connect())
        #close connection
    finally:
        cnx.close_connection()
    
    feed = DataFrameMulitpleBarFeed(dfs,barfeed.Frequency.DAY)
    feed.addMultipleBars()
    
    strat = MarketTiming(feed, instrumentsByClass, initialCash)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)
    returnsAnalyzer = returns.Returns()
    strat.attachAnalyzer(returnsAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("cash").addCallback("Cash", lambda x: strat.getBroker().getCash())
        # Plot strategy vs. SPY cumulative returns.
        plt.getOrCreateSubplot("returns").addDataSeries("umc", cumret.CumulativeReturn(feed["umc"].getPriceDataSeries()))
        plt.getOrCreateSubplot("returns").addDataSeries("Strategy", returnsAnalyzer.getCumulativeReturns())

    strat.run()
    
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)
    print "Returns: %.2f %%" % (returnsAnalyzer.getCumulativeReturns()[-1] * 100)

    if plot:
        plt.plot()
 def run(self):
     # 1. output csv file name
     currentTime = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
     fileName = ("./Result/Pair-Cointegration-Record-%s.csv" % currentTime)
     
     # 1. connect database
     cnx = Mysql.cnxStock()
     try:
         connection = cnx.connect()
         # 2. import instruments name from database
         #instrumentList = self.getInstrumentList(connection)["Local_Code"].values
         instrumentList = ("A","ibm","aapl")
         
         print ("Instruments Name import finished")
         
         loopNumber = len(instrumentList) * (len(instrumentList)-1)
         count = 0
         for i in range(len(instrumentList)) :
             for k in range(i+1 , len(instrumentList)) :
                 instrumentA = instrumentList[i]
                 instrumentB = instrumentList[k]
                 print "start %s and %s pair, this %s to process (%s in all)" %(instrumentA, instrumentB, str(count) , str(loopNumber))
                 if instrumentA is not instrumentB :
                     instruments = [instrumentA, instrumentB]
                     # 3. import data from database, as Dict{instrument_Name : dataseries}
                     try :
                         quotes = self.getAllHistoricalQuotes(connection, instruments)
                         # 4 Align time
                         alignedSeries = self.alignTime(quotes)
                         # 5 JohansenTest
                         jres = self.JohansenTest(instruments,alignedSeries)
                         #if jres.lr1[0] > 19.9349 and jres.lr1[1] > 6.6349
                         johansen.print_johan_stats(jres)
                         if jres.lr1[0] > 19.1 and jres.lr1[1] > 4.1 :
                             # 6 output result
                             self.Output(instruments, jres, fileName)
                     except :
                         print "%s and %s has problem" %(instrumentA, instrumentB)
                     
                 count += 1
                     
         
     finally:
         cnx.close_connection()
     print "Finish"
def main(plot):
    
    # trail
    initialCash = 10000
    instruments = ["aapl", "ibm"]
    windowSize = 50
    tableNames = dict()
    for instrument  in instruments :
        tableName = str("newyorkexchange.%s_historicalquotes_newyork" %instrument)
        tableNames[instrument] = tableName
        
    try :
        # create instance to connect Mysql
        cnx = cnxStock()
        # create instance to query Mysql data base
        query = historicalPriceQuery(instruments, tableNames)
        dfs = query.pandasQueryMulitple(cnx.connect())
        #close connection
    finally:
        cnx.close_connection()
    
    feed = DataFrameMulitpleBarFeed(dfs,barfeed.Frequency.DAY)
    feed.addMultipleBars()
    strat = StatArb(feed,dfs, windowSize, initialCash)
    
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strat.attachAnalyzer(sharpeRatioAnalyzer)

    if plot:
        plt = plotter.StrategyPlotter(strat, False, False, True)
        plt.getOrCreateSubplot("zScore").addDataSeries("zScore", strat.getZScoreDS())
        plt.getOrCreateSubplot("spread").addDataSeries("Spread", strat.getSpreadDS())

    strat.run()
    print "Sharpe ratio: %.2f" % sharpeRatioAnalyzer.getSharpeRatio(0.05)

    if plot:
        plt.plot()