Esempio n. 1
0
def plot_stock_prices_interactive():
    if request.method == 'GET':
        return render_template('plot_prices_beta_1.html')
    else:

        app_plots.vars = {}  # This is a dictionary
        # Define the variables. This is a local variable, but in Flask it will be passed to the plot route I guess
        if 'data' in request.form:
            app_plots.vars['data_src'] = request.form['data']
            # This get the data source
        else:

            return render_template(
                'plot_prices_beta_1.html',
                error_data=
                '<font size="3" color="red" > Choose at least one data source </font>'
            )

        app_plots.vars['sym'] = request.form['sym'].upper().strip(';').split(
            ';')  # 'sym' should be defined in html file as name

        if (app_plots.vars['sym'][0] == ''):  # sym is a list delimited by ;
            return render_template(
                'plot_prices_beta_1.html',
                error_sym=
                '<font size="3" color="red" > Provide at least one ticker symbol </font>'
            )

        #print request.form

        if len(
                request.form['start_date']
        ) != 0:  # Here start and end date are keys are coming even if they are empty
            try:
                app_plots.vars['start_date'] = dt.datetime.strptime(
                    request.form['start_date'], '%m/%d/%Y')
            except ValueError:
                return render_template(
                    'plot_prices_beta_1.html',
                    error_start_date=
                    '<font size="3" color="red" > Wrong date format </font>')
        else:
            # Take 1 year ago of the current date
            app_plots.vars['start_date'] = dt.datetime.today() - dt.timedelta(
                days=365)  # This does not give the accurate 5 years

        if len(request.form['end_date']) != 0:
            try:
                app_plots.vars['end_date'] = dt.datetime.strptime(
                    request.form['end_date'], '%m/%d/%Y')
            except ValueError:
                return render_template(
                    'plot_prices_beta_1.html',
                    error_end_date=
                    '<font size="3" color="red" > Wrong date format </font>')
        else:
            # Take today as the default date
            app_plots.vars['end_date'] = dt.datetime.today()

        if 'bench_sym' in request.form:
            app_plots.vars['bench_sym'] = request.form['bench_sym']
        else:
            app_plots.vars['bench_sym'] = 'SPY'

        symbols = app_plots.vars['sym']  # Here symbol will be a list

        # print request.form

        # Add the benchmark symbol to the symbols
        symbols.insert(0, app_plots.vars['bench_sym'])
        # Insert the default symbol in the symbols list

        #print symbols,usr_price_features, app_plots.vars['start_date'],app_plots.vars['end_date']

        if app_plots.vars['data_src'] == 'get_data_quandl':
            # Here get all the required features

            features = ['Open', 'Close', 'High', 'Low', 'Volume', 'Adj. Close']

            full_data = [(sym,
                          apicall_data.get_data_from_quandl(
                              symbol=sym,
                              features=features,
                              start_dt=app_plots.vars['start_date'],
                              end_dt=app_plots.vars['end_date']))
                         for sym in symbols]

            script_ele, div_ele = plot_symbols_interactive(full_data, 'Quandl')

            #computed_df=compute_params(full_data)

            #script_param,div_param=plot_params(full_data)

            return render_template('plot_prices_beta_1.html',
                                   script_symbols=script_ele,
                                   plot_div_symbols=div_ele)

        elif app_plots.vars['data_src'] == 'get_data_yahoo':
            # TODO: This needs a lot of change (pass not yet implemented)
            # data_dict=apicall_data.get_data_from_yahoo(symbol=symbols, features=features)
            return render_template(
                'plot_prices_beta_1.html',
                error_yahoo=
                '<font size="3" color="red"> Data source not yet enabled </font>'
            )
Esempio n. 2
0
def getMLmodels():
    if request.method == 'GET':
        return render_template('ml_models.html')
    else:
        # check if the post request has the file part
        app_mlModels.vars = {}
        app_mlModels.vars['ml_algo'] = request.form['ml_algo']

        bench_sym = 'SPY'
        # This is not available for the user

        if (request.form['sym'] == ''):  # sym is a list delimited by ;
            return render_template(
                'ml_models.html',
                error_sym=
                '<font size="3" color="red" > Provide at least one ticker symbol </font>'
            )
        else:
            app_mlModels.vars['sym'] = request.form['sym'].upper().strip(
                ';').split(';')

            app_mlModels.vars['sym'].insert(0, 'SPY')
            # SPY is the bench mark symbol which is not accessible to the user

        if len(
                request.form['start_date']
        ) != 0:  # Here start and end date are keys are coming even if they are empty
            try:
                app_mlModels.vars['start_date'] = dt.datetime.strptime(
                    request.form['start_date'], '%m/%d/%Y')
            except ValueError:
                return render_template(
                    'ml_models.html',
                    error_start_date=
                    '<font size="3" color="red" > Wrong date format </font>')
        else:
            # Take 5 years ago of the current date
            app_mlModels.vars['start_date'] = dt.datetime.today(
            ) - dt.timedelta(
                days=5 * 365)  # This does not give the accurate 5 years

        if len(request.form['end_date']) != 0:
            try:
                app_mlModels.vars['end_date'] = dt.datetime.strptime(
                    request.form['end_date'], '%m/%d/%Y')
            except ValueError:
                return render_template(
                    'ml_models.html',
                    error_end_date=
                    '<font size="3" color="red" > Wrong date format </font>')
        else:
            # Take today as the default date
            app_mlModels.vars['end_date'] = dt.datetime.today()

        #app_mlModels.vars['window']=int(request.form['window']) # Default window size is set to 20
        app_mlModels.vars['ml_algo'] = request.form['ml_algo']
        app_mlModels.vars['bench_ml_algo'] = request.form['bench_ml_algo']

        if app_mlModels.vars['ml_algo'] == app_mlModels.vars['bench_ml_algo']:
            return render_template(
                'ml_models.html',
                error_same_mdl=
                '<font size="3" color="red" > ML-algorithm and the Benchmark should be different </font>'
            )

        app_mlModels.vars['future_days'] = int(request.form['future_days'])
        #print request.form

        full_data = [(sym,
                      apicall_data.get_data_from_quandl(
                          symbol=sym,
                          features=['Adj. Close'],
                          start_dt=app_mlModels.vars['start_date'],
                          end_dt=app_mlModels.vars['end_date']))
                     for sym in app_mlModels.vars['sym']]

        # Convert this to required format
        prices_df = util.get_data(full_data)

        # Drop the bench mark price
        prices_df = prices_df.drop(bench_sym, axis=1)
        split_number = 100
        # This can be changed as needed, primarly use for spliting the data into train (train+cv) and test set

        metrics_df, future_df, bench_future_df, pct_tab = computeFeatures(
            prices_df, app_mlModels.vars['future_days'], split_number
        )  # Prices should technically have one symbol, but also possible that they might have multiple symbols

        # print metrics_df
        # Plot the time-series graph with past and future values

        tab1 = plotPredicted(prices_df, future_df,
                             dict_algo_names_map[app_mlModels.vars['ml_algo']],
                             split_number)

        tab2 = plotPredicted(
            prices_df, bench_future_df,
            dict_algo_names_map[app_mlModels.vars['bench_ml_algo']],
            split_number)

        tabs = Tabs(tabs=[tab1, tab2, pct_tab])

        script_el_data, div_el_data = components(tabs)
        # Put the metrics table in the html using bokeh
        metrics_data = dict(metrics_df[[i
                                        for i in metrics_df.columns]].round(4))
        #print metrics_data
        metrics_data[
            'Metric'] = metrics_df.index  # This will add the index (Note: Instead of Metric, if I use index, then the width of output index column cannot be adjustested )
        source = ColumnDataSource(metrics_data)
        columns = [TableColumn(field=i, title=i) for i in metrics_df.columns]
        # Insert the index column to the list of columns
        columns.insert(0, TableColumn(field="Metric", title="Metric"))
        metrics_table = DataTable(source=source,
                                  columns=columns,
                                  height=250,
                                  width=400)
        script_metrics, div_metrics = components(WidgetBox(metrics_table))

        # Similarly for the price describe data
        price_describe = prices_df.describe().round(4)
        price_describe_data = dict(price_describe[[i for i in price_describe]])
        price_describe_data[
            'Metric'] = price_describe.index  # This will add the index (Note: Instead of Metric, if I use index, then the width of output index column cannot be adjustested )
        source = ColumnDataSource(price_describe_data)
        columns = [
            TableColumn(field=i, title=i) for i in price_describe.columns
        ]
        # Insert the index column to the list of columns
        columns.insert(0, TableColumn(field="Metric", title="Metric"))
        price_describe_table = DataTable(source=source,
                                         columns=columns,
                                         height=250,
                                         width=400)
        script_price_describe, div_price_describe = components(
            WidgetBox(price_describe_table))

        return render_template('ml_models.html',
                               script_el_data=script_el_data,
                               div_el_data=div_el_data,
                               script_metrics=script_metrics,
                               div_metrics=div_metrics,
                               script_price_describe=script_price_describe,
                               div_price_describe=div_price_describe)
Esempio n. 3
0
def plot_stock_prices():
    if request.method=='GET':
        return render_template('plot_prices.html')
    else:
        
        app_quantfy.vars={} # This is a dictionary
        # Define the variables. This is a local variable, but in Flask it will be passed to the plot route I guess
        
        app_quantfy.vars['sym'] = request.form['sym'].upper().strip(';').split(';') # 'sym' should be defined in html file as name
                
        if 'data' in request.form:
            app_quantfy.vars['data_src']=request.form['data']; # This get the data source
        else:
           
            return render_template('plot_prices.html',error_data='<font size="3" color="red" > Choose at least one data source </font>') 

        #print request.form
        
        if len(request.form['start_date'])!=0: # Here start and end date are keys are coming even if they are empty
            try:
                app_quantfy.vars['start_date']=dt.datetime.strptime(request.form['start_date'],'%m/%d/%Y')
            except ValueError:
                return render_template('plot_prices.html',error_start_date='<font size="3" color="red" > Wrong date format </font>')
        else:
            # Take 5 years ago of the current date
            app_quantfy.vars['start_date']=dt.datetime.today()-dt.timedelta(days=5*365) # This does not give the accurate 5 years
        
        
        if  len(request.form['end_date'])!=0:
            try:
                app_quantfy.vars['end_date']=dt.datetime.strptime(request.form['end_date'],'%m/%d/%Y')
            except ValueError:
                return render_template('plot_prices.html',error_end_date='<font size="3" color="red" > Wrong date format </font>')
        else:
            # Take today as the default date
            app_quantfy.vars['end_date']=dt.datetime.today()
        
        
        app_quantfy.vars['price_features']=defaultdict(); # This is an empty dictionary
        
        app_quantfy.vars['compute_features']=defaultdict(); # This is a dictionary for computing the requested features
               
        
        
        if 'bench_sym' in request.form: 
            app_quantfy.vars['bench_sym']=request.form['bench_sym']
        else:
            app_quantfy.vars['bench_sym']='SPY'
        
        
        if (app_quantfy.vars['sym'][0]=='') :  # sym is a list delimited by ;
            return render_template('plot_prices.html',error_sym='<font size="3" color="red" > Provide at least one ticker symbol </font>') 
               
        
        symbols=app_quantfy.vars['sym'] # Here symbol will be a list
    
        # Add the benchmark symbol to the symbols
        symbols.insert(0,app_quantfy.vars['bench_sym']); # Insert the default symbol in the symbols list
        
        usr_price_features=list(app_quantfy.vars['price_features'].keys()) 
        
        #print symbols,usr_price_features, app_quantfy.vars['start_date'],app_quantfy.vars['end_date']
        
        if app_quantfy.vars['data_src']=='get_data_quandl':   
            # This is list of tuples, with first element in the tuple being symbol and second element being dict
            # Here get the data for all the price features, filter it in the plot_symbols function, so all the price features are present here
            features=['Open','Close','High','Low','Volume','Adj. Close']
            
            full_data=[(sym, apicall_data.get_data_from_quandl(symbol=sym, features=features,start_dt=app_quantfy.vars['start_date'],end_dt=app_quantfy.vars['end_date'])
                        ) for sym in symbols]
            
            # Pass user selected price features to the plot function
            #script_ele,div_ele=plot_symbols(full_data,usr_price_features, 'Quandl')
            
            script_ele,div_ele=plot_symbols_interactive(full_data, 'Quandl')
            
            computed_df,describe_df=compute_params(full_data)
            
            # print describe_df
            computed_df=computed_df.round(5)
            
            script_computed_params,div_computed_params=convert_pd_bokeh_html(computed_df.round(4))
            script_describe,div_describe=convert_pd_bokeh_html(describe_df.round(4))
            
            script_param,div_param=plot_params(full_data)
            
            return render_template('plot_prices.html',script_symbols=script_ele,plot_div_symbols=div_ele,
                                   script_computed_params=script_computed_params,div_computed_params=div_computed_params,
                                   script_params=script_param,plot_div_features=div_param,
                                   script_describe=script_describe,div_describe=div_describe)
        
        elif app_quantfy.vars['data_src']=='get_data_yahoo': 
            # TODO: This needs a lot of change (pass not yet implemented)
            # data_dict=apicall_data.get_data_from_yahoo(symbol=symbols, features=features)
            return render_template('plot_prices.html',error_yahoo='<font size="3" color="red"> Data source not yet enabled </font>')
Esempio n. 4
0
def portfolio_page():
    if request.method=='GET':
        return render_template('portfolio.html')
    else:
        app_quantfy.vars={} # This is a dictionary
        # Define the variables. This is a local variable, but in Flask it will be passed to the plot route I guess
        
        app_quantfy.vars['sym'] = request.form['sym'].upper().strip(';').split(';') # 'sym' should be defined in html file as name
        
        if (app_quantfy.vars['sym'][0]=='') :  # sym is a list delimited by ;
            return render_template('portfolio.html',error_sym='<font size="3" color="red" > Provide at least one ticker symbol </font>') 
        
        
        if len(request.form['start_date'])!=0: # Here start and end date are keys are coming even if they are empty
            try:
                app_quantfy.vars['start_date']=dt.datetime.strptime(request.form['start_date'],'%m/%d/%Y')
            except ValueError:
                return render_template('portfolio.html',error_start_date='<font size="3" color="red" > Wrong date format </font>')
        else:
            # Take 1 years ago of the current date
            app_quantfy.vars['start_date']=dt.datetime.today()-dt.timedelta(days=365) # This does not give the accurate 5 years
        
        
        if  len(request.form['end_date'])!=0:
            try:
                app_quantfy.vars['end_date']=dt.datetime.strptime(request.form['end_date'],'%m/%d/%Y')
            except ValueError:
                return render_template('portfolio.html',error_end_date='<font size="3" color="red" > Wrong date format </font>')
        else:
            # Take today as the default date
            app_quantfy.vars['end_date']=dt.datetime.today()
        
        #print app_quantfy.vars
        if 'bench_sym' in request.form: 
            app_quantfy.vars['bench_sym']=request.form['bench_sym']
        else:
            app_quantfy.vars['bench_sym']='SPY'
        
        symbols=list(app_quantfy.vars['sym']); # Create a new list as we are doing insert operation next
        symbols.insert(0,app_quantfy.vars['bench_sym']); # Insert the default symbol in the symbols list
        
        # Here just get the data for the 'Adj. Close'
        full_data=[(sym, apicall_data.get_data_from_quandl(symbol=sym, features=['Adj. Close'], start_dt=app_quantfy.vars['start_date'],end_dt=app_quantfy.vars['end_date'])
                        ) for sym in symbols]
        
        # Convert this to required format
        
        df_all_sym=util.get_data(full_data)
        
        app_quantfy.vars['guess_alloc']=request.form['guess_alloc'].strip(';').split(';')
        
        
        
        app_quantfy.vars['start_value']=float(request.form['start_value']); # It has a default value
        
        if len(app_quantfy.vars['guess_alloc']) !=0 and (app_quantfy.vars['guess_alloc'][0]!='') : # app_quantfy.vars['guess_alloc'] is a list because of the strip function
            # print app_quantfy.vars['guess_alloc']
            # print len(app_quantfy.vars['guess_alloc'])
            app_quantfy.vars['guess_alloc']=[float(i) for i in app_quantfy.vars['guess_alloc']]
            try:
                assert len(app_quantfy.vars['guess_alloc'])==len(app_quantfy.vars['sym'])
            except AssertionError:
                return render_template('portfolio.html',error_alloc='<font size="3" color="red" > Number of allocations should be same as symbols   </font>')
            # Sum should be equal to one
            print app_quantfy.vars['guess_alloc']
            
            try:
                assert abs(sum(app_quantfy.vars['guess_alloc'])-1.0)<=1e-5 # Sometimes the rounding does not work correctly
            except AssertionError:
                return render_template('portfolio.html',error_alloc='<font size="3" color="red" > Sum should be 1   </font>')

            
        else:
            # Generate random numbers
            allocs=np.random.random(len(app_quantfy.vars['sym']))
            allocs /=allocs.sum()
            app_quantfy.vars['guess_alloc']=allocs
            #print allocs
        
        cr,adr,sddr,sr,ev,normalized_plot_df=optimization.access_portfolio(df_all_sym, app_quantfy.vars['bench_sym'], 
                                                                           app_quantfy.vars['guess_alloc'],
                                                                           sv=app_quantfy.vars['start_value'])
        
        #print cr,adr,sddr,sr,ev
        
        param_not_opt=pd.DataFrame([cr,adr,sddr,sr,ev],index=['Cumulative Return','Average Daily Return','Stand. Deviation Daily return',
                                                          'Sharpe Ratio','End value'], columns=['Unoptimized'])
        
        script_not_opt_table,div_not_opt_table=convert_pd_bokeh_html(param_not_opt)
        
        # print normalized_plot_df.head()
        hover=HoverTool(
            tooltips=[
                ("Portfolio",'$y')
                
                
            ]
        )
        TOOLS='pan,wheel_zoom,box_zoom,reset,save,box_select,crosshair'
        not_opt_p = figure(width=900, height=500, x_axis_type="datetime",tools=[TOOLS,hover])
        
        colors=['blue','red','green','#cc3300']
        
        for (i,ftr) in enumerate(normalized_plot_df):
            not_opt_p.line(normalized_plot_df.index,normalized_plot_df[ftr],legend=ftr,color=colors[i],line_width=2)
        
        #not_opt_p.line(normalized_plot_df)
        
        not_opt_p.title.text = "Un-optimized portfolio"
        not_opt_p.legend.location = "top_left"
        not_opt_p.xaxis.axis_label = 'Date'
        not_opt_p.yaxis.axis_label = 'Relative portfolio value'
        
        tab_not_opt=Panel(child=not_opt_p,title='Un-optimized portfolio')
        
        # script_not_opt, div_not_opt=components(not_opt_p)
        
        # print script_not_opt,div_not_opt
        # Now run optimized
        
        cr,adr,sddr,sr,ev,normalized_plot_df,optimal_alloc=optimization.optimize_portfolio(df_all_sym,app_quantfy.vars['bench_sym'],
                                                                             app_quantfy.vars['start_value'])
        
        
        # print cr,adr,sddr,sr,ev,optimal_alloc
        
        # print normalized_plot_df.head()
        hover=HoverTool(
            tooltips=[
                ("Portfolio",'$y')
                
                
            ]
        )
        
        opt_p = figure(width=900, height=500, x_axis_type="datetime",tools=[TOOLS,hover])
              
        for (i,ftr) in enumerate(normalized_plot_df):
            opt_p.line(normalized_plot_df.index,normalized_plot_df[ftr],legend=ftr,color=colors[i],line_width=2)
        
        
        # print normalized_plot_df
        opt_p.title.text = "Optimized portfolio value"
        opt_p.legend.location = "top_left"
        opt_p.xaxis.axis_label = 'Date'
        opt_p.yaxis.axis_label = 'Relative portfolio value'
        
        tab_opt=Panel(child=opt_p,title='Optimized portfolio')
        
        tabs=Tabs(tabs=[tab_not_opt,tab_opt])
        
        script_opt, div_opt=components(tabs)
        
        
        param_opt=pd.DataFrame([cr,adr,sddr,sr,ev],index=['Cummulative Return','Additive Daily Return','Stand. Deviation Daily return',
                                                          'Sharpe Ratio','End value'], columns=['Optimized'])
        
        all_params=param_not_opt.join(param_opt)
        
        script_opt_table,div_opt_table=convert_pd_bokeh_html(all_params)
        
        
              
        alloc_df=pd.DataFrame([app_quantfy.vars['guess_alloc'],list(optimal_alloc)],index=['Random/Guess allocations','Optimized allocations'],columns=app_quantfy.vars['sym'])
        
        #str_opt_alloc='Optimal allocations: '+', '.join([str(i) for i in optimal_alloc])
        script_alloc_df,div_alloc_df=convert_pd_bokeh_html(alloc_df)
        
        # script_not_opt_table=script_not_opt_table,div_not_opt_table=div_not_opt_table,
        return render_template('portfolio.html',script_opt_table=script_opt_table, div_opt_table=div_opt_table,
                               script_alloc_df=script_alloc_df,div_alloc_df=div_alloc_df,
                                script_opt=script_opt,plot_opt=div_opt
                               )
Esempio n. 5
0
def compute_portvals(
    orders_file,
    start_val=1000000,
    leverage_threshold=2.0,
    bench_sym='SPY'
):  # Default file is orders.csv, but the test function calls other file

    #print os.path.join(UPLOAD_FOLDER,orders_file)
    orders_df = get_orders(
        os.path.join(UPLOAD_FOLDER,
                     orders_file))  # Pass the filename that was just uploaded
    #print orders_df

    list_symbols = list(orders_df.Symbol.unique(
    ))  # This gives the list of unique symbols in the order dataframe

    list_symbols.insert(0, bench_sym)
    # Insert the default symbol in the symbols list

    # Start date should the first date in the orders file   (and orders file is sorted based on dates)
    start_date = orders_df.index[0]
    # End date should be the last date entry in the orders file
    end_date = orders_df.index[-1]
    # get the price data for all the symbols in the order data frame for the date range in the order file
    # Here just get the data for the 'Adj. Close'

    full_data = [(sym,
                  apicall_data.get_data_from_quandl(symbol=sym,
                                                    features=['Adj. Close'],
                                                    start_dt=start_date,
                                                    end_dt=end_date))
                 for sym in list_symbols]

    # Drop the bench mark price

    # Convert this to required format
    prices_df = util.get_data(full_data)

    all_prices_df = pd.DataFrame(prices_df)

    #all_prices_df.to_csv('cache/all_prices.csv')

    prices_df = prices_df.drop(bench_sym, axis=1)

    # Add the 'Cash' key to the price dataframe with value =1.0
    prices_df['Cash'] = 1.0
    # This add 1.0 to all rows in the prices_df

    # create a trades dataframe and initialize
    trades_df = pd.DataFrame(np.zeros(
        (len(prices_df.index), len(list_symbols))),
                             index=prices_df.index,
                             columns=list_symbols)
    trades_df['Cash'] = 0

    # create holding dataframe and initialize
    holding_df = pd.DataFrame(np.zeros(
        (len(prices_df.index), len(list_symbols))),
                              index=prices_df.index,
                              columns=list_symbols)

    # Initialize  the cash in holding to the start value
    holding_df['Cash'] = start_val
    # Holding cash is same as the 'Cash' in trades_df, except we have start value initialized

    # negative value of stocks in holding_df could indicate that it has

    # create values dataframe and initialize
    values_df = pd.DataFrame(np.zeros(
        (len(prices_df.index), len(list_symbols))),
                             index=prices_df.index,
                             columns=list_symbols)

    values_df['value'] = 0

    # create empty dataframe for leverage

    for (d, rows) in orders_df.iterrows(
    ):  # Here d is the date index # Order file assumes that if the date is same, then they are listed as twice
        if rows['Order'] == 'BUY':
            trades_df.loc[d, rows['Symbol']] = rows['Shares']
            trades_df.loc[d, 'Cash'] += -trades_df.loc[
                d, rows['Symbol']] * prices_df.loc[d, rows['Symbol']]
            # -ve indicates we have purchased the stock
            # holding_df 'Cash' is the same as the trading except we have initialized to start_val
            holding_df.loc[d:, 'Cash'] += -trades_df.loc[
                d, rows['Symbol']] * prices_df.loc[d, rows['Symbol']]

        elif rows[
                'Order'] == 'SELL':  # Negative value indicates you are selling
            trades_df.loc[d, rows['Symbol']] = -rows['Shares']
            trades_df.loc[d, 'Cash'] += -trades_df.loc[
                d, rows['Symbol']] * prices_df.loc[d, rows['Symbol']]
            # This will be +ve since we are selling the stock and it adds to the cash value

            holding_df.loc[d:, 'Cash'] += -trades_df.loc[
                d, rows['Symbol']] * prices_df.loc[d, rows['Symbol']]

        holding_df.loc[d:, rows['Symbol']] += trades_df.loc[d, rows['Symbol']]
        # After we update the number of holdings for each symbol and assuming only new orders are affecting the leverage, compute the leverage for this order and check against the threshold
        #print holding_df.loc[d,list_symbols],prices_df.loc[d,list_symbols]
        leverage = sum(holding_df.loc[d, list_symbols].abs() *
                       prices_df.loc[d, list_symbols]) / (
                           sum(holding_df.loc[d, list_symbols] *
                               prices_df.loc[d, list_symbols]) +
                           holding_df.loc[d, 'Cash'])
        # Check if the threshold has crossed
        if leverage > leverage_threshold:
            # Then the order would not be processed
            # print d, leverage
            # update the holdings and trades_df based on BUY or SELL order
            holding_df.loc[d:, rows['Symbol']] -= trades_df.loc[
                d, rows['Symbol']]  #This is same for both sell and buy

            if rows['Order'] == 'BUY':
                # First update the cash values back to the originals before the order
                trades_df.loc[d, 'Cash'] += trades_df.loc[
                    d, rows['Symbol']] * prices_df.loc[d, rows['Symbol']]
                holding_df.loc[d:, 'Cash'] += trades_df.loc[
                    d, rows['Symbol']] * prices_df.loc[d, rows['Symbol']]
                # Then update the trade count (Warning: doing this first will not change the trades and holding back to its inital values)
                trades_df.loc[d, rows['Symbol']] += -rows['Shares']
                # print trades_df.loc[d,rows['Symbol']]
                rejected_order = 'BUY'

            elif rows[
                    'Order'] == 'SELL':  # Negative value indicates you are selling
                # First update cash values
                trades_df.loc[d, 'Cash'] += trades_df.loc[
                    d, rows['Symbol']] * prices_df.loc[d, rows['Symbol']]
                # This will be +ve since we are selling the stock and it adds to the cash value
                holding_df.loc[d:, 'Cash'] += trades_df.loc[
                    d, rows['Symbol']] * prices_df.loc[d, rows['Symbol']]
                # Second update the trade count
                trades_df.loc[d, rows['Symbol']] += rows['Shares']
                # print trades_df.loc[d,rows['Symbol']]
                rejected_order = 'SELL'

            print(
                'This {0} order on {1} for {2} stocks has been rejected due to leverage of {3}'
                .format(rejected_order, rows['Symbol'], rows['Shares'],
                        leverage))

    values_df = prices_df * holding_df
    # * in pandas gives cell-by-cell multiplication of dataframes
    # print '************'
    # print values_df
    stocks_df = values_df[list_symbols]

    #leverage_df=stocks_df.abs().sum(axis=1)/(stocks_df.sum(axis=1)+values_df['Cash']) # But you don't need this (since we calculate leverage per order basis)
    # Change it to dataframe with renaming
    #leverage_df=pd.DataFrame(leverage_df.ix[:],index=stocks_df.index,columns=['Leverage'])

    portval = pd.DataFrame(values_df.sum(axis=1),
                           index=values_df.index,
                           columns=['Portval'])

    param_df = pd.DataFrame(index=[
        'Portval', 'Benchmark (' + app_marketsim.vars['bench_sym'] + ')'
    ],
                            columns=[
                                'Sharpe ratio', 'Cumulative Return',
                                'Standard Deviation', 'Average Daily Return'
                            ])

    # Compute all the fund parameters:
    sharpe_ratio, cum_ret, std_daily_ret, avg_daily_ret = compute_indicators(
        portval['Portval']
    )  # for this function to work, pass only the portval column
    param_df.ix['Portval'] = [
        sharpe_ratio, cum_ret, std_daily_ret, avg_daily_ret
    ]

    # Compute benchmark parameters

    sharpe_ratio_bench, cum_ret_bench, std_daily_ret_bench, avg_daily_ret_bench = compute_indicators(
        all_prices_df[app_marketsim.vars['bench_sym']])
    param_df.ix['Benchmark (' + app_marketsim.vars['bench_sym'] + ')'] = [
        sharpe_ratio_bench, cum_ret_bench, std_daily_ret_bench,
        avg_daily_ret_bench
    ]

    #print param_df

    return portval, all_prices_df, param_df, orders_df
Esempio n. 6
0
    daily_returns = compute_daily_returns(df)

    volatility = get_rolling_std(daily_returns, window)

    # Put the initial values to zeros,
    volatility.ix[:window, :] = 0

    return volatility


def requested_params():
    return


if __name__ == '__main__':
    symbols = ['SPY', 'GOOG']
    full_data = [
        (sym,
         apicall_data.get_data_from_quandl(
             sym,
             start_dt=dt.datetime.today() - dt.timedelta(days=5 * 365),
             end_dt=dt.datetime.today())) for sym in symbols
    ]
    print full_data
    df = get_data(full_data)
    rm = get_rolling_mean(df, window=20)
    rstd = get_rolling_std(df, window=20)
    u_band, l_band = get_bollinger_bands(rm, rstd)
    #print u_band.columns
    #print l_band.columns