Пример #1
0
def fundanalysisMain():

    print '\t\t\t                <<< Fund Analysis >>> \n'
    print '\t [1] Analyze Portfolio Allocation  [2] Event Analyzer    [3] Analyze Portfolio'
    print '\t [7] Main Menu '

    try:
        sel_opt = input('\n<<< Select: ')
    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        fundanalysisMain()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        fundanalysisMain()

    if sel_opt == 1:
        basic.print_logo()
        portfolioAnalyz()
    elif sel_opt == 2:
        basic.print_logo()
        eventmenuMain()
    elif sel_opt == 3:
        basic.print_logo()
        print '<<<(s) Update orders.csv file.. \n'
        marketsimMain()
    elif sel_opt == 7:
        basic.go_back()
    else:
        basic.print_clrscr()
        basic.print_logo()
        fundanalysisMain()
Пример #2
0
def eventmenuMain():
    
    print '\t\t\t             <<< Event Analyzer >>> \n '
    print ' [1] Event based on Market           [2] Event based on Bollinger'
    print ' [7] Main Menu '
 
    try:
        sel_opt = input('\n<<< Select: ')
    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        eventmenuMain()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        eventmenuMain()
 
    if sel_opt == 1:
        eventmodMain()
    elif sel_opt == 2:
        eventBollinger.eventBollingerMain()
    elif sel_opt == 7:
        basic.go_back()
    else:
        basic.print_clrscr()
        basic.print_logo()
        eventmenuMain()
Пример #3
0
def fundanalysisMain():

    print '\t\t\t                <<< Fund Analysis >>> \n'
    print '\t [1] Analyze Portfolio Allocation  [2] Event Analyzer    [3] Analyze Portfolio'  
    print '\t [7] Main Menu '
    
    try:
        sel_opt = input('\n<<< Select: ')
    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        fundanalysisMain()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        fundanalysisMain()
        
    if sel_opt == 1:
        basic.print_logo()
        portfolioAnalyz()
    elif sel_opt == 2:
        basic.print_logo()
        eventmenuMain()
    elif sel_opt  == 3:
        basic.print_logo()
        print '<<<(s) Update orders.csv file.. \n'
        marketsimMain()
    elif sel_opt == 7:
        basic.go_back()
    else:
        basic.print_clrscr()
        basic.print_logo()
        fundanalysisMain()
Пример #4
0
def usrHelpMain():
    print '\t\t\t             <<< Help >>> \n '
    print '\t [1] Load Data             [2] General Calculations    [3] Fund Analysis'
    print '\t [4] Reserach Stock        [5] About                   [7] Main Menu'

    try:
        sel = input('Select: ')

    except SyntaxError:
        basic.print_clrscr()
        basic.go_back()
    except ValueError:
        basic.print_clrscr()
        basic.go_back()
    except NameError:
        basic.print_clrscr()
        basic.go_back()

    if sel == 1:
        help_yahooDataPull()
    elif sel == 2:
        help_generalCalc()
    elif sel == 3:
        help_fundAnalysis()
    elif sel == 4:
        help_researchStock()
    elif sel == 5:
        help_about()
    elif sel == 7:
        basic.go_back()
    else:
        basic.print_clrscr()
        basic.go_back()
Пример #5
0
def eventmenuMain():

    print '\t\t\t             <<< Event Analyzer >>> \n '
    print ' [1] Event based on Market           [2] Event based on Bollinger'
    print ' [7] Main Menu '

    try:
        sel_opt = input('\n<<< Select: ')
    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        eventmenuMain()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        eventmenuMain()

    if sel_opt == 1:
        eventmodMain()
    elif sel_opt == 2:
        eventBollinger.eventBollingerMain()
    elif sel_opt == 7:
        basic.go_back()
    else:
        basic.print_clrscr()
        basic.print_logo()
        eventmenuMain()
Пример #6
0
def usrHelpMain():
    print '\t\t\t             <<< Help >>> \n '
    print '\t [1] Load Data             [2] General Calculations    [3] Fund Analysis'
    print '\t [4] Reserach Stock        [5] About                   [7] Main Menu'

    try:
        sel = input('Select: ')

    except SyntaxError:
        basic.print_clrscr()
        basic.go_back()
    except ValueError:
        basic.print_clrscr()
        basic.go_back()
    except NameError:
        basic.print_clrscr()
        basic.go_back()

    if sel == 1:
        help_yahooDataPull()
    elif sel == 2:
        help_generalCalc()                   
    elif sel == 3:
        help_fundAnalysis()     
    elif sel == 4:
        help_researchStock()
    elif sel == 5:
        help_about()                    
    elif sel == 7:
        basic.go_back()                    
    else:
        basic.print_clrscr()
        basic.go_back()
Пример #7
0
def yahooDatamain():
    path = os.getcwd()
    print path
    symbol_file = os.path.join(path,"MRT_SYMBOLS.txt")
    if os.path.isfile(symbol_file):
        ls_symbols = read_symbols(symbol_file)
        download_path = os.path.join(path,'Data\Yahoo')
        get_data(download_path, ls_symbols)
    else:
        print '<<<(w) File Not Found: MRT_SYMBOLS.txt '
        time.sleep(2)
        basic.go_back()
Пример #8
0
def generalcalc():
    print '\t\t\t                <<< General Calculations >>> \n '
    print ' [1] Plot Adjusted Close      [2] Calculate Daily Return  [3] Calculate Standard Devation'
    print ' [4] Optimized Portfolio      [5] Get Sharpe Ration       [6] Best Portfolio'
    print ' [7] Main Menu '

    try:
        sel_opt = input('\n<<< Select: ')
    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        generalcalc()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        generalcalc()

    if sel_opt == 1:
        objcalc = GeneralCalc()
        objcalc.plotAdjustedClose()
    elif sel_opt == 2:
        objcalc = GeneralCalc()
        objcalc.calDailyReturn()
    elif sel_opt == 3:
        objcalc = GeneralCalc()
        d_ret = objcalc.calDailyReturn()
        objcalc.calStdDev(d_ret)
    elif sel_opt == 4:
        objcalc = GeneralCalc()
        rets = objcalc.calDailyReturn()
        objcalc.getPortfolioOpt(rets)
    elif sel_opt == 5:
        objcalc = GeneralCalc()
        rets = objcalc.calDailyReturn()
        objcalc.getSharpeRatio(rets)
    elif sel_opt == 6:
        bestPortfolio.bestPort()
    elif sel_opt == 7:
        basic.go_back()
    else:
        basic.print_clrscr()
        basic.print_logo()
        generalcalc()
Пример #9
0
def generalcalc():
    print '\t\t\t                <<< General Calculations >>> \n '
    print ' [1] Plot Adjusted Close      [2] Calculate Daily Return  [3] Calculate Standard Devation'
    print ' [4] Optimized Portfolio      [5] Get Sharpe Ration       [6] Best Portfolio'
    print ' [7] Main Menu '

    try:
        sel_opt = input('\n<<< Select: ')
    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        generalcalc()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        generalcalc()

    if sel_opt == 1:
        objcalc = GeneralCalc()
        objcalc.plotAdjustedClose()
    elif sel_opt == 2:
        objcalc = GeneralCalc()
        objcalc.calDailyReturn()
    elif sel_opt == 3:
        objcalc = GeneralCalc()
        d_ret = objcalc.calDailyReturn()
        objcalc.calStdDev(d_ret)
    elif sel_opt == 4:
        objcalc = GeneralCalc()
        rets = objcalc.calDailyReturn()
        objcalc.getPortfolioOpt(rets)
    elif sel_opt == 5:
        objcalc = GeneralCalc()
        rets = objcalc.calDailyReturn()
        objcalc.getSharpeRatio(rets)
    elif sel_opt == 6:
        bestPortfolio.bestPort()
    elif sel_opt == 7:
        basic.go_back()
    else:
        basic.print_clrscr()
        basic.print_logo()
        generalcalc()
Пример #10
0
def marketsimMain():
    try:
        i_start_cash = float(input('<<< Enter Starting Cash($): '))
    except ValueError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()

    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()

        
    symbols, dates = _csv_read_sym_dates('orders.csv')
    close, timestamps = _read_data(symbols, dates)
    share_matrix = _share_holdings('orders.csv', symbols, timestamps, close)
    share_matrix = _share_value_cash(share_matrix, close, i_start_cash)
    ts_fund = _fund_value(share_matrix, close)  
    _write_fund(ts_fund, 'values.csv')
    analyze.analyzeMain()
Пример #11
0
def get_dates():
    print '------------------------------------------------------------- '
    try:
        start_month = int(input('<<< Enter Start Month: '))

        if int(start_month) > 12 or int(start_month) <= 0:
            basic.print_clrscr()
            basic.go_back()

        start_day = int(input('<<< Enter Start Day: '))
        if int(start_day) > 31 or int(start_day) <= 0:
            basic.print_clrscr()
            basic.go_back()

        start_year = int(input('<<< Enter Start Year: '))
        now = datetime.datetime.now()
        if int(start_year) > now.year or int(start_year) < 2010:
            basic.print_clrscr()
            basic.go_back()

        end_month = input('<<< Enter End Month: ')
        if int(end_month) > 12 or int(end_month) <= 0:
            basic.print_clrscr()
            basic.go_back()

        end_day = input('<<< Enter End Day: ')
        if int(end_day) > 31 or int(end_day) <= 0:
            basic.print_clrscr()
            basic.go_back()

        end_year = input('<<< Enter End Year: ')
        if int(end_year) > now.year or int(end_year) < 2010:
            basic.print_clrscr()
            basic.go_back()

        if start_year > end_year:
            print '<<<(w)End Year should be greater than start year'
            basic.print_clrscr()
            basic.go_back()

    except ValueError:
        basic.print_clrscr()
        basic.go_back()

    except SyntaxError:
        basic.print_clrscr()
        basic.go_back()
    except NameError:
        basic.print_clrscr()
        basic.go_back()

    leap_year_start = start_year % 4
    leap_year_end = end_year % 4

    if leap_year_start != 0 or leap_year_end != 0:
        if start_day == 29 or end_day == 29:
            print '<<(w) Not leap year..\n'
            basic.print_clrscr()
            basic.go_back()

    return start_month, start_day, start_year, end_month, end_day, end_year
Пример #12
0
def analyzeMain():
    ts_fund = _csv_read_fund('values.csv')
    try:
        benchmark = raw_input('Enter Benchmark: ')
    except ValueError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()

    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()


    bench_vals = _read_bench(benchmark, list(ts_fund.index))
    # print bench_vals
    multiple = ts_fund[0] / bench_vals[0]
    bench_vals = bench_vals * multiple
    
    print "Details of the Performance of the portfolio"
    print "Total Fund:", ts_fund[0]
    print 'Data Range : ', ts_fund.index[0], ' to ', ts_fund.index[-1]
    print 'Sharpe Ratio of Fund :', tsu.get_sharpe_ratio(tsu.daily(ts_fund))[0]
    print 'Sharpe Ratio of ' + benchmark + ' :', tsu.get_sharpe_ratio(
                                              tsu.daily(bench_vals))[0]
    print 'Total Return of Fund : ', (((ts_fund[-1] / ts_fund[0]) - 1) + 1)
    print 'Total Return of ' + benchmark + ' :', (((bench_vals[-1]
                                                / bench_vals[0]) - 1) + 1)
    print 'Standard Deviation of Fund : ', np.std(tsu.daily(
                                           ts_fund.values))
    print 'Standard Deviation of ' + benchmark + ' :', np.std(
                                           tsu.daily(bench_vals.values))

    print 'Average Daily Return of Fund : ', np.mean(tsu.daily(
                                           ts_fund.values))
    print 'Average Daily Return of ' + benchmark + ' :', np.mean(
                                           tsu.daily(bench_vals.values))
    KS, P = ks_statistic(ts_fund)    
    print "KS P:" , KS,P    
    plt.clf()
    plt.plot(ts_fund.index, ts_fund.values)
    plt.plot(ts_fund.index, bench_vals)
    plt.ylabel('Fund Value', size='xx-small')
    plt.xlabel('Date', size='xx-small')
    plt.legend(['Fund', 'Benchmark'], loc='best')
    plt.xticks(size='xx-small')
    plt.yticks(size='xx-small')
    plt.grid(axis='both')
    plt.show()
    savefig('funds.png', format = 'png')
    
    try:
        report = input("Want to generate report(Press 1): ")
        
    except ValueError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()
         
    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()        
        
    if report == 1:
        name = str(dt.datetime.now())
        file_conv = name.replace(" ", "")
        file_conv1 = file_conv.replace(":","_")
        file_conv2 = file_conv1.replace("-","_")
        filename = file_conv2+".html"
        print 'Generating report..', filename
        html_file  =  open(filename,"w+")
        html_file.write("<HTML>\n")
        html_file.write("<HEAD>\n")
        html_file.write("<TITLE>MSim Generated Report:" + name + "</TITLE>\n")    
        html_file.write("<H1>Details of the Performance of the portfolio</H1>")
        html_file.write("</HEAD>\n\n")
        html_file.write("<BODY>\n\n")
        html_file.write("<IMG SRC = \'./funds.png\' title=Funds vs Benchmark align=right height= 500 width = 600/>\n")
        html_file.write("<p><i> Total Fund:" +str(ts_fund[0])+ "</p\n")        
        html_file.write("<p><i>Data Range : </i>," +str(ts_fund.index[0])+ "to ," +str(ts_fund.index[-1])+"</p\n")
        html_file.write("<p><i>Sharpe Ratio of Fund :</i>"+str(tsu.get_sharpe_ratio(tsu.daily(ts_fund))[0])+"</p\n")
        html_file.write("<p><i>Sharpe Ratio of </i>" + benchmark + ":" +str(tsu.get_sharpe_ratio(tsu.daily(bench_vals))[0])+"</p\n")

        html_file.write("<p><i>Sharpe Ratio of Fund : ,</i>" +str(tsu.get_sharpe_ratio(tsu.daily(ts_fund))[0])+"</p\n")
        html_file.write("<p><i>Sharpe Ratio of </i>" + benchmark + ":" +str(tsu.get_sharpe_ratio(tsu.daily(bench_vals))[0])+"</p\n")
        html_file.write("<p><i>Total Return of Fund :</i>" +str((((ts_fund[-1] / ts_fund[0]) - 1) + 1))+"</p\n")
        html_file.write("<p><i>Total Return of </i>" + benchmark + " : " +str((((bench_vals[-1]/ bench_vals[0]) - 1) + 1))+"</p\n")
        html_file.write("<p><i>Standard Deviation of Fund : </i>" +str(np.std(tsu.daily(ts_fund.values)))+"</p\n")
        html_file.write("<p><i>Standard Deviation of </i>"+ benchmark + ":" +str(np.std(tsu.daily(bench_vals.values)))+"</p\n")
    
        html_file.write("<p><i>Average Daily Return of Fund : </i> " +str(np.mean(tsu.daily(ts_fund.values)))+"</p\n")
        html_file.write("<p><i>Average Daily Return of </i>" + benchmark + " : " + str(np.mean(tsu.daily(bench_vals.values)))+"</p\n")
        html_file.write("<link type=text/csv rel=stylesheet href=D:\Sim\MSimv2.1/orders.csv />")

        html_file.write("</BODY>\n\n")
        html_file.write("</HTML>")    
Пример #13
0
def find_events(ls_symbols, d_data):
    ''' Finding the event dataframe '''
    df_close = d_data['actual_close']
    ts_market = df_close['SPY']

    print "Finding Events"

    # Creating an empty dataframe
    df_events = copy.deepcopy(df_close)
    df_events = df_events * np.NAN
    # Time stamps for the event range
    ldt_timestamps = df_close.index
    writer = csv.writer(open('orders.csv', 'wb'), delimiter=',')
    
    f_symreturn_cutoff = input('<<< Enter the cutoff in decimel for symbol return today: ')
    f_marketreturn_cutoff = input('<<< Enter the cutoiff in decimel for market return today: ')
    print '1 -> SYMBOL_RETURN_TODAY > ', f_symreturn_cutoff,  '& MARKET_RETURN_TODAY  < ', f_marketreturn_cutoff
    print '2 -> SYMBOL_RETURN_TODAY < ', f_symreturn_cutoff,  '& MARKET_RETURN_TODAY  > ', f_marketreturn_cutoff
    print '3 -> SYMBOL_RETURN_TODAY > ', f_symreturn_cutoff,  '& MARKET_RETURN_TODAY  > ', f_marketreturn_cutoff
    print '4 -> SYMBOL_RETURN_TODAY <', f_symreturn_cutoff,  '& MARKET_RETURN_TODAY  < ', f_marketreturn_cutoff
    
    try:
        select = input('Select: ')
    except ValueError:
            basic.print_clrscr()
            basic.print_logo()
            basic.go_back()
    except SyntaxError:
            basic.print_clrscr()
            basic.print_logo()
            basic.go_back()
    except NameError:
            basic.print_clrscr()
            basic.print_logo()
            basic.go_back()


    for s_sym in ls_symbols:
        for i in range(1, len(ldt_timestamps)):
            # Calculating the returns for this timestamp
            f_symprice_today = df_close[s_sym].ix[ldt_timestamps[i]]
            f_symprice_yest = df_close[s_sym].ix[ldt_timestamps[i - 1]]
            f_marketprice_today = ts_market.ix[ldt_timestamps[i]]
            f_marketprice_yest = ts_market.ix[ldt_timestamps[i - 1]]
            f_symreturn_today = (f_symprice_today / f_symprice_yest) - 1

            f_marketreturn_today = (f_marketprice_today / f_marketprice_yest) - 1
            i_shares = 100
            
            if select == 1:
                if f_symreturn_today > float(f_symreturn_cutoff) and f_marketreturn_today < float(f_marketreturn_cutoff):
                    df_events[s_sym].ix[ldt_timestamps[i]] = 1
                    row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                    writer.writerow(row_to_enter)
                    try:
                        time_n = ldt_timestamps[i + 5]
                    except:
                        time_n = ldt_timestamps[-1]
                    row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                    writer.writerow(row_to_enter)   
                        
            elif select == 2:
                if f_symreturn_today < float(f_symreturn_cutoff) and f_marketreturn_today > float(f_marketreturn_cutoff):
                    df_events[s_sym].ix[ldt_timestamps[i]] = 1
                    row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                    writer.writerow(row_to_enter)
                    try:
                        time_n = ldt_timestamps[i + 5]
                    except:
                        time_n = ldt_timestamps[-1]
                    row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                    writer.writerow(row_to_enter)                    
            
            elif select == 3:
                if f_symreturn_today > float(f_symreturn_cutoff) and f_marketreturn_today > float(f_marketreturn_cutoff):
                    df_events[s_sym].ix[ldt_timestamps[i]] = 1
                    row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                    writer.writerow(row_to_enter)
                    try:
                        time_n = ldt_timestamps[i + 5]
                    except:
                        time_n = ldt_timestamps[-1]
                    row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                    writer.writerow(row_to_enter)
                        
            else:
                if f_symreturn_today < float(f_symreturn_cutoff) and f_marketreturn_today < float(f_marketreturn_cutoff):
                    df_events[s_sym].ix[ldt_timestamps[i]] = 1
                    row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                    writer.writerow(row_to_enter)
                    try:
                        time_n = ldt_timestamps[i + 5]
                    except:
                        time_n = ldt_timestamps[-1]
                        row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                        writer.writerow(row_to_enter)                    
                
    return df_events
Пример #14
0
def portfolioAnalyz():
    ''' Main Function
        This method will analyze your performance of portfolio from date specified.
        Create Excel sheet with your portfolio allocation and it will be read by this method to perform analysis
    '''
    # Reading the portfolio
    print '<<<(s) Update your portfolioanalyze.csv file..'
    if os.path.isfile("C:\MRT3.0\portfolioanalyze.csv"):
        na_portfolio = np.loadtxt('portfolioanalyze.csv',
                                  dtype='S5,f4',
                                  delimiter=',',
                                  comments="#",
                                  skiprows=1)
    else:
        print '<<<(w) File Not Found: portfolioanalyze.csv '
        sleep(2)
        basic.go_back()

    # Sorting the portfolio by symbol name
    na_portfolio = sorted(na_portfolio, key=lambda x: x[0])
    print na_portfolio

    # Create two list for symbol names and allocation
    ls_port_syms = []
    lf_port_alloc = []
    for port in na_portfolio:
        ls_port_syms.append(port[0])
        lf_port_alloc.append(port[1])

    # Creating an object of the dataaccess class with Yahoo as the source.
    c_dataobj = da.DataAccess('Yahoo')
    ls_all_syms = c_dataobj.get_all_symbols()
    # Bad symbols are symbols present in portfolio but not in all syms
    ls_bad_syms = list(set(ls_port_syms) - set(ls_all_syms))

    if len(ls_bad_syms) != 0:
        print "<<<(w) Portfolio contains bad symbols : ", ls_bad_syms

    for s_sym in ls_bad_syms:
        i_index = ls_port_syms.index(s_sym)
        ls_port_syms.pop(i_index)
        lf_port_alloc.pop(i_index)

    # Reading the historical data.
    print '<<<(i) Reading Historical data...'

    #dt_end = dt.datetime(2011, 1, 1)
    #dt_start = dt_end - dt.timedelta(days=95)  # Three years
    # We need closing prices so the timestamp should be hours=16.
    dt_timeofday = dt.timedelta(hours=16)
    start_month, start_day, start_year, end_month, end_day, end_year = modDatesReturn.get_dates(
    )
    dt_start = dt.datetime(start_year, start_month, start_day)
    dt_end = dt.datetime(end_year, end_month, end_day)
    # Get a list of trading days between the start and the end.
    ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)

    # Keys to be read from the data, it is good to read everything in one go.
    ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']

    # Reading the data, now d_data is a dictionary with the keys above.
    # Timestamps and symbols are the ones that were specified before.
    ldf_data = c_dataobj.get_data(ldt_timestamps, ls_port_syms, ls_keys)
    d_data = dict(zip(ls_keys, ldf_data))

    # Copying close price into separate dataframe to find rets
    df_rets = d_data['close'].copy()
    # Filling the data.
    df_rets = df_rets.fillna(method='ffill')
    df_rets = df_rets.fillna(method='bfill')

    # Numpy matrix of filled data values
    na_rets = df_rets.values
    # returnize0 works on ndarray and not dataframes.
    tsu.returnize0(na_rets)

    # Estimate portfolio returns
    na_portrets = np.sum(na_rets * lf_port_alloc, axis=1)
    na_port_total = np.cumprod(na_portrets + 1)
    na_component_total = np.cumprod(na_rets + 1, axis=0)

    # Plotting the results
    plt.clf()
    #fig = plt.figure()
    #fig.add_subplot(111)
    plt.plot(ldt_timestamps, na_component_total)
    plt.plot(ldt_timestamps, na_port_total)
    ls_names = ls_port_syms
    ls_names.append('Portfolio')
    plt.legend(ls_names)
    plt.ylabel('Cumulative Returns')
    plt.xlabel('Date')
    #fig.autofmt_xdate(rotation=45)
    plt.show()
Пример #15
0
def get_dates():
        print '------------------------------------------------------------- '
        try:
                start_month = int(input('<<< Enter Start Month: '))
            
                if int(start_month) > 12 or int(start_month) <= 0:
                        basic.print_clrscr()
                        basic.go_back()
                        
                start_day = int(input('<<< Enter Start Day: '))
                if int(start_day) > 31 or int(start_day) <= 0:
                        basic.print_clrscr()
                        basic.go_back()

                start_year = int(input('<<< Enter Start Year: '))
                now = datetime.datetime.now()
                if int(start_year) > now.year or int(start_year) < 2010:
                        basic.print_clrscr()
                        basic.go_back()
    
                end_month = input('<<< Enter End Month: ')
                if int(end_month) > 12 or int(end_month) <= 0:
                        basic.print_clrscr()
                        basic.go_back()
                        
                end_day = input('<<< Enter End Day: ')
                if int(end_day) > 31 or int(end_day ) <= 0:
                        basic.print_clrscr()
                        basic.go_back()
                        
                end_year = input('<<< Enter End Year: ')
                if int(end_year) > now.year or int(end_year) < 2010:
                        basic.print_clrscr()
                        basic.go_back()
                        
                if start_year > end_year:
                    print '<<<(w)End Year should be greater than start year'
                    basic.print_clrscr()
                    basic.go_back()
            
        except ValueError:
                basic.print_clrscr()
                basic.go_back()

        except SyntaxError:
                basic.print_clrscr()
                basic.go_back()
        except NameError:
                basic.print_clrscr()
                basic.go_back()
        
        leap_year_start = start_year%4 
        leap_year_end = end_year%4
        
        if leap_year_start != 0 or leap_year_end != 0:
            if start_day == 29 or end_day == 29:
                print '<<(w) Not leap year..\n' 
                basic.print_clrscr()
                basic.go_back()
                        
        
        return start_month,start_day,start_year,end_month,end_day,end_year
Пример #16
0
def bestPort():
    '''Main Function'''
    # List of symbols
    #ls_symbols = ["AXP", "HPQ", "IBM", "HNZ"]
    ls_symbols = list()

    try:
        len_sym = input('<<< How many symbol(Works only for 4 symbols):  ')
        if len_sym > 4 or len_sym <= 0 or len_sym < 4:
            print '<<<(w) Works only for 4 symbols..\n'
            basic.print_logo()
            basic.print_clrscr()
            basic.go_back()

    except ValueError:
        basic.print_logo()
        basic.print_clrscr()
        basic.go_back()
    except SyntaxError:
        basic.print_logo()
        basic.print_clrscr()
        basic.go_back()
    except NameError:
        basic.print_logo()
        basic.print_clrscr()
        basic.go_back()

    for i in range(len_sym):
        symbols = str(raw_input('<<< Enter the list of symbols: '))
        ls_symbols.append(symbols)

    ## Start and End date of the charts

    start_month, start_day, start_year, end_month, end_day, end_year = modDatesReturn.get_dates(
    )
    dt_start = dt.datetime(start_year, start_month, start_day)
    dt_end = dt.datetime(end_year, end_month, end_day)
    # Start and End date of the charts
    #dt_start = dt.datetime(2010, 1, 1)
    #dt_end = dt.datetime(2010, 12, 31)

    # We need closing prices so the timestamp should be hours=16.
    dt_timeofday = dt.timedelta(hours=16)

    # Get a list of trading days between the start and the end.
    ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)

    # Creating an object of the dataaccess class with Yahoo as the source.
    c_dataobj = da.DataAccess('Yahoo')

    # Keys to be read from the data, it is good to read everything in one go.
    ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']

    # Reading the data, now d_data is a dictionary with the keys above.
    # Timestamps and symbols are the ones that were specified before.
    ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys)
    d_data = dict(zip(ls_keys, ldf_data))

    # Copying close price into separate dataframe to find rets
    df_rets = d_data['close'].copy()
    # Filling the data.
    df_rets = df_rets.fillna(method='ffill')
    df_rets = df_rets.fillna(method='bfill')

    # Numpy matrix of filled data values
    na_rets = df_rets.values
    na_rets = na_rets / na_rets[0, :]

    lf_alloc = [0.0, 0.0, 0.0, 0.0]

    max_sharpe = -1000
    final_stddev = -1000
    final_daily_ret = -1000
    final_cum_ret = -1000
    best_portfolio = lf_alloc

    for i in range(0, 101, 10):
        left_after_i = 101 - i
        for j in range(0, left_after_i, 10):
            left_after_j = 101 - i - j
            for k in range(0, left_after_j, 10):
                left_after_k = 100 - i - j - k
                lf_alloc = [i, j, k, left_after_k]
                lf_alloc = [x * 0.01 for x in lf_alloc]
                stddev, daily_ret, sharpe, cum_ret = simulate(
                    na_rets, lf_alloc)
                if sharpe > max_sharpe:
                    max_sharpe = sharpe
                    final_stddev = stddev
                    final_cum_ret = cum_ret
                    final_daily_ret = daily_ret
                    best_portfolio = lf_alloc

    print "<<< Symbols : ", ls_symbols
    print "<<< Best Portfolio : ", best_portfolio
    print "<<< Statistics : Std. Deviation : ", final_stddev
    print "<<< Statistics : Daily Returns  : ", final_daily_ret
    print "<<< Statistics : Cum. Returns   : ", final_cum_ret
    print "<<< Statistics : Sharpe Ratio   : ", max_sharpe
Пример #17
0
def find_events(ls_symbols, d_data):
    ''' Finding the event dataframe '''
    df_close = d_data['actual_close']
    # ts_market = df_close['SPY']

    print "Finding Events"

    # Creating an empty dataframe
    df_events = copy.deepcopy(df_close)
    df_events = df_events * np.NAN

    # Time stamps for the event range
    ldt_timestamps = df_close.index

    df_close = d_data['close']
    df_mean = pd.rolling_mean(d_data['close'], 20)
    df_std = pd.rolling_std(d_data['close'], 20)

    df_bollinger = (df_close - df_mean) / (df_std)
    writer = csv.writer(open('bollingerorders.csv', 'wb'), delimiter=',')
    
    f_symreturn_cutoff = input('<<< Enter the cutoff in decimel for symbol return today: ')
    f_symyest_cutoff = input('<<< Enter the cutoff in decimel for symbol return yesterday: ')
   
    print '1 -> SYMBOL_RETURN_TODAY > ', f_symreturn_cutoff, 'SYMBOL_RETURN_YESTERDAY < ',f_symyest_cutoff 
    print '2 -> SYMBOL_RETURN_TODAY < ', f_symreturn_cutoff, 'SYMBOL_RETURN_YESTERDAY > ',f_symyest_cutoff 
    print '3 -> SYMBOL_RETURN_TODAY > ', f_symreturn_cutoff, 'SYMBOL_RETURN_YESTERDAY > ',f_symyest_cutoff 
    print '4 -> SYMBOL_RETURN_TODAY <', f_symreturn_cutoff,  'SYMBOL_RETURN_YESTERDAY < ',f_symyest_cutoff
    
    try:
        select = input('Select: ')
    except ValueError:
            basic.print_clrscr()
            basic.print_logo()
            basic.go_back()
    except SyntaxError:
            basic.print_clrscr()
            basic.print_logo()
            basic.go_back()
    except NameError:
            basic.print_clrscr()
            basic.print_logo()
            basic.go_back()
            
    for s_sym in ls_symbols:
        for i in range(1, len(ldt_timestamps)):
            # Calculating the returns for this timestamp
            f_symboll_today = df_bollinger[s_sym].ix[ldt_timestamps[i]]
            f_symboll_yest = df_bollinger[s_sym].ix[ldt_timestamps[i - 1]]
            f_marketbol_today = df_bollinger['SPY'].ix[ldt_timestamps[i]]
            # f_marketprice_yest = ts_market.ix[ldt_timestamps[i - 1]]
            i_shares = 100
            
            if select == 1:
                if f_symboll_today > float(f_symreturn_cutoff) and f_symboll_yest < float(f_symyest_cutoff):
                    if f_marketbol_today > 1.0: 
                        df_events[s_sym].ix[ldt_timestamps[i]] = 1
                        row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                        writer.writerow(row_to_enter)
                        try:
                            time_n = ldt_timestamps[i + 5]
                        except:
                            time_n = ldt_timestamps[-1]
                        row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                        writer.writerow(row_to_enter)   
                        
            elif select == 2:
                if f_symboll_today > float(f_symreturn_cutoff) and f_symboll_yest < float(f_symyest_cutoff):
                    if f_marketbol_today > 1.0:                    
                        df_events[s_sym].ix[ldt_timestamps[i]] = 1
                        row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                        writer.writerow(row_to_enter)
                        try:
                            time_n = ldt_timestamps[i + 5]
                        except:
                            time_n = ldt_timestamps[-1]
                            row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                        writer.writerow(row_to_enter)                    
            
            elif select == 3:
                if f_symboll_today > float(f_symreturn_cutoff) and f_symboll_yest < float(f_symyest_cutoff):
                    if f_marketbol_today > 1.0:
                        df_events[s_sym].ix[ldt_timestamps[i]] = 1
                        row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                        writer.writerow(row_to_enter)
                        try:
                            time_n = ldt_timestamps[i + 5]
                        except:
                            time_n = ldt_timestamps[-1]
                            row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                        writer.writerow(row_to_enter)
                        
            else:
                if f_symboll_today > float(f_symreturn_cutoff) and f_symboll_yest < float(f_symyest_cutoff):
                    if f_marketbol_today > 1.0:
                        df_events[s_sym].ix[ldt_timestamps[i]] = 1
                        row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                        writer.writerow(row_to_enter)
                        try:
                            time_n = ldt_timestamps[i + 5]
                        except:
                            time_n = ldt_timestamps[-1]
                            row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                        writer.writerow(row_to_enter)                    
            
            #if f_symboll_today < -2.0 and f_symboll_yest >= -2.0:
                #if f_marketbol_today > 1.0:
                    #df_events[s_sym].ix[ldt_timestamps[i]] = 1
                    #row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                            #str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                    #writer.writerow(row_to_enter)
                    #try:
                        #time_n = ldt_timestamps[i + 5]
                    #except:
                        #time_n = ldt_timestamps[-1]
                    #row_to_enter = [str(time_n.year), str(time_n.month), \
                            #str(time_n.day), s_sym, 'Sell', i_shares]
                    #writer.writerow(row_to_enter)

    return df_events
Пример #18
0
def analyzeMain():
    ts_fund = _csv_read_fund('values.csv')
    try:
        benchmark = raw_input('Enter Benchmark: ')
    except ValueError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()

    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()

    bench_vals = _read_bench(benchmark, list(ts_fund.index))
    # print bench_vals
    multiple = ts_fund[0] / bench_vals[0]
    bench_vals = bench_vals * multiple

    print "Details of the Performance of the portfolio"
    print "Total Fund:", ts_fund[0]
    print 'Data Range : ', ts_fund.index[0], ' to ', ts_fund.index[-1]
    print 'Sharpe Ratio of Fund :', tsu.get_sharpe_ratio(tsu.daily(ts_fund))[0]
    print 'Sharpe Ratio of ' + benchmark + ' :', tsu.get_sharpe_ratio(
        tsu.daily(bench_vals))[0]
    print 'Total Return of Fund : ', (((ts_fund[-1] / ts_fund[0]) - 1) + 1)
    print 'Total Return of ' + benchmark + ' :', ((
        (bench_vals[-1] / bench_vals[0]) - 1) + 1)
    print 'Standard Deviation of Fund : ', np.std(tsu.daily(ts_fund.values))
    print 'Standard Deviation of ' + benchmark + ' :', np.std(
        tsu.daily(bench_vals.values))

    print 'Average Daily Return of Fund : ', np.mean(tsu.daily(ts_fund.values))
    print 'Average Daily Return of ' + benchmark + ' :', np.mean(
        tsu.daily(bench_vals.values))
    KS, P = ks_statistic(ts_fund)
    print "KS P:", KS, P
    plt.clf()
    plt.plot(ts_fund.index, ts_fund.values)
    plt.plot(ts_fund.index, bench_vals)
    plt.ylabel('Fund Value', size='xx-small')
    plt.xlabel('Date', size='xx-small')
    plt.legend(['Fund', 'Benchmark'], loc='best')
    plt.xticks(size='xx-small')
    plt.yticks(size='xx-small')
    plt.grid(axis='both')
    plt.show()
    savefig('funds.png', format='png')

    try:
        report = input("Want to generate report(Press 1): ")

    except ValueError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()

    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()

    if report == 1:
        name = str(dt.datetime.now())
        file_conv = name.replace(" ", "")
        file_conv1 = file_conv.replace(":", "_")
        file_conv2 = file_conv1.replace("-", "_")
        filename = file_conv2 + ".html"
        print 'Generating report..', filename
        html_file = open(filename, "w+")
        html_file.write("<HTML>\n")
        html_file.write("<HEAD>\n")
        html_file.write("<TITLE>MSim Generated Report:" + name + "</TITLE>\n")
        html_file.write("<H1>Details of the Performance of the portfolio</H1>")
        html_file.write("</HEAD>\n\n")
        html_file.write("<BODY>\n\n")
        html_file.write(
            "<IMG SRC = \'./funds.png\' title=Funds vs Benchmark align=right height= 500 width = 600/>\n"
        )
        html_file.write("<p><i> Total Fund:" + str(ts_fund[0]) + "</p\n")
        html_file.write("<p><i>Data Range : </i>," + str(ts_fund.index[0]) +
                        "to ," + str(ts_fund.index[-1]) + "</p\n")
        html_file.write("<p><i>Sharpe Ratio of Fund :</i>" +
                        str(tsu.get_sharpe_ratio(tsu.daily(ts_fund))[0]) +
                        "</p\n")
        html_file.write("<p><i>Sharpe Ratio of </i>" + benchmark + ":" +
                        str(tsu.get_sharpe_ratio(tsu.daily(bench_vals))[0]) +
                        "</p\n")

        html_file.write("<p><i>Sharpe Ratio of Fund : ,</i>" +
                        str(tsu.get_sharpe_ratio(tsu.daily(ts_fund))[0]) +
                        "</p\n")
        html_file.write("<p><i>Sharpe Ratio of </i>" + benchmark + ":" +
                        str(tsu.get_sharpe_ratio(tsu.daily(bench_vals))[0]) +
                        "</p\n")
        html_file.write("<p><i>Total Return of Fund :</i>" +
                        str((((ts_fund[-1] / ts_fund[0]) - 1) + 1)) + "</p\n")
        html_file.write("<p><i>Total Return of </i>" + benchmark + " : " +
                        str((((bench_vals[-1] / bench_vals[0]) - 1) + 1)) +
                        "</p\n")
        html_file.write("<p><i>Standard Deviation of Fund : </i>" +
                        str(np.std(tsu.daily(ts_fund.values))) + "</p\n")
        html_file.write("<p><i>Standard Deviation of </i>" + benchmark + ":" +
                        str(np.std(tsu.daily(bench_vals.values))) + "</p\n")

        html_file.write("<p><i>Average Daily Return of Fund : </i> " +
                        str(np.mean(tsu.daily(ts_fund.values))) + "</p\n")
        html_file.write("<p><i>Average Daily Return of </i>" + benchmark +
                        " : " + str(np.mean(tsu.daily(bench_vals.values))) +
                        "</p\n")
        html_file.write(
            "<link type=text/csv rel=stylesheet href=D:\Sim\MSimv2.1/orders.csv />"
        )

        html_file.write("</BODY>\n\n")
        html_file.write("</HTML>")
Пример #19
0
def bestPort():
    '''Main Function'''
    # List of symbols
    #ls_symbols = ["AXP", "HPQ", "IBM", "HNZ"]
    ls_symbols = list()
    
    try:
        len_sym = input('<<< How many symbol(Works only for 4 symbols):  ')
        if len_sym > 4 or len_sym <= 0 or len_sym < 4:
            print '<<<(w) Works only for 4 symbols..\n'
            basic.print_logo()
            basic.print_clrscr()
            basic.go_back()        

    except ValueError:
        basic.print_logo()
        basic.print_clrscr()
        basic.go_back()
    except SyntaxError:
        basic.print_logo()
        basic.print_clrscr()
        basic.go_back()
    except NameError:
        basic.print_logo()
        basic.print_clrscr()
        basic.go_back()
    

    
    for i in range(len_sym):
        symbols = str(raw_input('<<< Enter the list of symbols: '))
        ls_symbols.append(symbols)

    ## Start and End date of the charts
 
    start_month,start_day,start_year,end_month,end_day,end_year = modDatesReturn.get_dates()
    dt_start = dt.datetime(start_year, start_month, start_day)
    dt_end = dt.datetime(end_year, end_month, end_day)
    # Start and End date of the charts
    #dt_start = dt.datetime(2010, 1, 1)
    #dt_end = dt.datetime(2010, 12, 31)

    # We need closing prices so the timestamp should be hours=16.
    dt_timeofday = dt.timedelta(hours=16)

    # Get a list of trading days between the start and the end.
    ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)

    # Creating an object of the dataaccess class with Yahoo as the source.
    c_dataobj = da.DataAccess('Yahoo')

    # Keys to be read from the data, it is good to read everything in one go.
    ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']

    # Reading the data, now d_data is a dictionary with the keys above.
    # Timestamps and symbols are the ones that were specified before.
    ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys)
    d_data = dict(zip(ls_keys, ldf_data))

    # Copying close price into separate dataframe to find rets
    df_rets = d_data['close'].copy()
    # Filling the data.
    df_rets = df_rets.fillna(method='ffill')
    df_rets = df_rets.fillna(method='bfill')

    # Numpy matrix of filled data values
    na_rets = df_rets.values
    na_rets = na_rets / na_rets[0, :]
    
    lf_alloc = [0.0, 0.0, 0.0, 0.0]

    max_sharpe = -1000
    final_stddev = -1000
    final_daily_ret = -1000
    final_cum_ret = -1000
    best_portfolio = lf_alloc

    for i in range(0, 101, 10):
        left_after_i = 101 - i
        for j in range(0, left_after_i, 10):
            left_after_j = 101 - i - j
            for k in range(0, left_after_j, 10):
                left_after_k = 100 - i - j - k
                lf_alloc = [i, j, k, left_after_k]
                lf_alloc = [x * 0.01 for x in lf_alloc]
                stddev, daily_ret, sharpe, cum_ret = simulate(na_rets, lf_alloc)
                if sharpe > max_sharpe:
                    max_sharpe = sharpe
                    final_stddev = stddev
                    final_cum_ret = cum_ret
                    final_daily_ret = daily_ret
                    best_portfolio = lf_alloc

    print "<<< Symbols : ", ls_symbols
    print "<<< Best Portfolio : ", best_portfolio
    print "<<< Statistics : Std. Deviation : ", final_stddev
    print "<<< Statistics : Daily Returns  : ", final_daily_ret
    print "<<< Statistics : Cum. Returns   : ", final_cum_ret
    print "<<< Statistics : Sharpe Ratio   : ", max_sharpe
Пример #20
0
def find_events(ls_symbols, d_data):
    ''' Finding the event dataframe '''
    df_close = d_data['actual_close']
    ts_market = df_close['SPY']

    print "Finding Events"

    # Creating an empty dataframe
    df_events = copy.deepcopy(df_close)
    df_events = df_events * np.NAN
    # Time stamps for the event range
    ldt_timestamps = df_close.index
    writer = csv.writer(open('orders.csv', 'wb'), delimiter=',')

    f_symreturn_cutoff = input(
        '<<< Enter the cutoff in decimel for symbol return today: ')
    f_marketreturn_cutoff = input(
        '<<< Enter the cutoiff in decimel for market return today: ')
    print '1 -> SYMBOL_RETURN_TODAY > ', f_symreturn_cutoff, '& MARKET_RETURN_TODAY  < ', f_marketreturn_cutoff
    print '2 -> SYMBOL_RETURN_TODAY < ', f_symreturn_cutoff, '& MARKET_RETURN_TODAY  > ', f_marketreturn_cutoff
    print '3 -> SYMBOL_RETURN_TODAY > ', f_symreturn_cutoff, '& MARKET_RETURN_TODAY  > ', f_marketreturn_cutoff
    print '4 -> SYMBOL_RETURN_TODAY <', f_symreturn_cutoff, '& MARKET_RETURN_TODAY  < ', f_marketreturn_cutoff

    try:
        select = input('Select: ')
    except ValueError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()
    except SyntaxError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()
    except NameError:
        basic.print_clrscr()
        basic.print_logo()
        basic.go_back()

    for s_sym in ls_symbols:
        for i in range(1, len(ldt_timestamps)):
            # Calculating the returns for this timestamp
            f_symprice_today = df_close[s_sym].ix[ldt_timestamps[i]]
            f_symprice_yest = df_close[s_sym].ix[ldt_timestamps[i - 1]]
            f_marketprice_today = ts_market.ix[ldt_timestamps[i]]
            f_marketprice_yest = ts_market.ix[ldt_timestamps[i - 1]]
            f_symreturn_today = (f_symprice_today / f_symprice_yest) - 1

            f_marketreturn_today = (f_marketprice_today /
                                    f_marketprice_yest) - 1
            i_shares = 100

            if select == 1:
                if f_symreturn_today > float(
                        f_symreturn_cutoff) and f_marketreturn_today < float(
                            f_marketreturn_cutoff):
                    df_events[s_sym].ix[ldt_timestamps[i]] = 1
                    row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                    writer.writerow(row_to_enter)
                    try:
                        time_n = ldt_timestamps[i + 5]
                    except:
                        time_n = ldt_timestamps[-1]
                    row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                    writer.writerow(row_to_enter)

            elif select == 2:
                if f_symreturn_today < float(
                        f_symreturn_cutoff) and f_marketreturn_today > float(
                            f_marketreturn_cutoff):
                    df_events[s_sym].ix[ldt_timestamps[i]] = 1
                    row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                    writer.writerow(row_to_enter)
                    try:
                        time_n = ldt_timestamps[i + 5]
                    except:
                        time_n = ldt_timestamps[-1]
                    row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                    writer.writerow(row_to_enter)

            elif select == 3:
                if f_symreturn_today > float(
                        f_symreturn_cutoff) and f_marketreturn_today > float(
                            f_marketreturn_cutoff):
                    df_events[s_sym].ix[ldt_timestamps[i]] = 1
                    row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                    writer.writerow(row_to_enter)
                    try:
                        time_n = ldt_timestamps[i + 5]
                    except:
                        time_n = ldt_timestamps[-1]
                    row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                    writer.writerow(row_to_enter)

            else:
                if f_symreturn_today < float(
                        f_symreturn_cutoff) and f_marketreturn_today < float(
                            f_marketreturn_cutoff):
                    df_events[s_sym].ix[ldt_timestamps[i]] = 1
                    row_to_enter = [str(ldt_timestamps[i].year), str(ldt_timestamps[i].month), \
                                            str(ldt_timestamps[i].day), s_sym, 'Buy', i_shares]
                    writer.writerow(row_to_enter)
                    try:
                        time_n = ldt_timestamps[i + 5]
                    except:
                        time_n = ldt_timestamps[-1]
                        row_to_enter = [str(time_n.year), str(time_n.month), \
                                            str(time_n.day), s_sym, 'Sell', i_shares]
                        writer.writerow(row_to_enter)

    return df_events
Пример #21
0
def portfolioAnalyz():
    ''' Main Function
        This method will analyze your performance of portfolio from date specified.
        Create Excel sheet with your portfolio allocation and it will be read by this method to perform analysis
    '''
    # Reading the portfolio
    print '<<<(s) Update your portfolioanalyze.csv file..'
    if os.path.isfile("C:\MRT3.0\portfolioanalyze.csv"):
        na_portfolio = np.loadtxt('portfolioanalyze.csv', dtype='S5,f4',
                        delimiter=',', comments="#", skiprows=1)
    else:
        print '<<<(w) File Not Found: portfolioanalyze.csv '
        sleep(2)
        basic.go_back()

        
    # Sorting the portfolio by symbol name
    na_portfolio = sorted(na_portfolio, key=lambda x: x[0])
    print na_portfolio

    # Create two list for symbol names and allocation
    ls_port_syms = []
    lf_port_alloc = []
    for port in na_portfolio:
        ls_port_syms.append(port[0])
        lf_port_alloc.append(port[1])

    # Creating an object of the dataaccess class with Yahoo as the source.
    c_dataobj = da.DataAccess('Yahoo')
    ls_all_syms = c_dataobj.get_all_symbols()
    # Bad symbols are symbols present in portfolio but not in all syms
    ls_bad_syms = list(set(ls_port_syms) - set(ls_all_syms))

    if len(ls_bad_syms) != 0:
        print "<<<(w) Portfolio contains bad symbols : ", ls_bad_syms

    for s_sym in ls_bad_syms:
        i_index = ls_port_syms.index(s_sym)
        ls_port_syms.pop(i_index)
        lf_port_alloc.pop(i_index)

    # Reading the historical data.
    print '<<<(i) Reading Historical data...'
    

    #dt_end = dt.datetime(2011, 1, 1)
    #dt_start = dt_end - dt.timedelta(days=95)  # Three years
    # We need closing prices so the timestamp should be hours=16.
    dt_timeofday = dt.timedelta(hours=16)
    start_month,start_day,start_year,end_month,end_day,end_year = modDatesReturn.get_dates()
    dt_start = dt.datetime(start_year, start_month, start_day)
    dt_end = dt.datetime(end_year, end_month, end_day)
    # Get a list of trading days between the start and the end.
    ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)

    # Keys to be read from the data, it is good to read everything in one go.
    ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']

    # Reading the data, now d_data is a dictionary with the keys above.
    # Timestamps and symbols are the ones that were specified before.
    ldf_data = c_dataobj.get_data(ldt_timestamps, ls_port_syms, ls_keys)
    d_data = dict(zip(ls_keys, ldf_data))

    # Copying close price into separate dataframe to find rets
    df_rets = d_data['close'].copy()
    # Filling the data.
    df_rets = df_rets.fillna(method='ffill')
    df_rets = df_rets.fillna(method='bfill')

    # Numpy matrix of filled data values
    na_rets = df_rets.values
    # returnize0 works on ndarray and not dataframes.
    tsu.returnize0(na_rets)

    # Estimate portfolio returns
    na_portrets = np.sum(na_rets * lf_port_alloc, axis=1)
    na_port_total = np.cumprod(na_portrets + 1)
    na_component_total = np.cumprod(na_rets + 1, axis=0)

    # Plotting the results
    plt.clf()
    #fig = plt.figure()
    #fig.add_subplot(111)
    plt.plot(ldt_timestamps, na_component_total)
    plt.plot(ldt_timestamps, na_port_total)
    ls_names = ls_port_syms
    ls_names.append('Portfolio')
    plt.legend(ls_names)
    plt.ylabel('Cumulative Returns')
    plt.xlabel('Date')
    #fig.autofmt_xdate(rotation=45)
    plt.show()