# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import numpy as np
import pandas as pd
import pickle
import datetime
import matplotlib.pyplot as plt
import matplotlib as mpl

Market_position_df = pd.read_pickle('database\MarketPortfolioWeights26Oct20.pickle')
Momentum_position_df = pd.read_pickle('database\MomentumPortfolioWeights26Oct20.pickle')
Quality_position_df = pd.read_pickle('database\QualityPortfolioWeights26Oct20.pickle')
Value_position_df = pd.read_pickle('database\ValuePortfolioWeights26Oct20.pickle')
Liquidity_position_df = pd.read_pickle('database\LiquidityPortfolioWeights26Oct20.pickle')
Size_position_df = pd.read_pickle('database\SizePortfolioWeights26Oct20.pickle')
price_df = pd.read_pickle('database\\nifty_200_stocks_price_data_24Oct20.pickle')

price_subset_df = price_df[['adjclose','Symbol']]
price_subset_df.index = price_df['formatted_date' ]

nifty_200 = pd.read_csv('database\ind_nifty200list.csv')
price_matrix = {}
for stock in nifty_200.Symbol:
    price_matrix[stock] = price_subset_df[price_subset_df.Symbol == stock]

for stock in nifty_200.Symbol:
    price_matrix[stock].drop(columns='Symbol', inplace = True)
    price_matrix[stock] = price_matrix[stock].iloc[-18:,:]
final_price_matrix = pd.concat(price_matrix, axis = 1)
final_price_matrix.columns = final_price_matrix.columns.droplevel(1)


def Capstone_backtest(position_weight_df,prices_df,commission):
    cap = 70000000
    No_of_shares = {}
    for i in range(len(position_weight_df)):
        if i == 0:
            No_of_shares[position_weight_df.index[i]] = (cap*position_weight_df.iloc[i,:])/prices_df.iloc[i,:]
        else:
            cap = (No_of_shares[position_weight_df.index[i-1]]*prices_df.iloc[i,:]).sum()
            No_of_shares[position_weight_df.index[i]] = (cap*position_weight_df.iloc[i,:])/prices_df.iloc[i,:]
    position_df = pd.concat(No_of_shares,axis=1).T
    
    riskfree_rate = 0.02
    delta_df = position_df.diff()
    worth_df = position_df*prices_df
    worth_df['Total'] = worth_df.sum(axis=1)
    returns_df = delta_df*prices_df
    k = returns_df
    returns_df["returns"] = k.sum(axis=1)-k.abs().sum(axis=1)*commission
    returns_df["per_returns"] = returns_df["returns"]/worth_df['Total']
    sharpe_ratio = (returns_df["per_returns"].mean()-riskfree_rate)/returns_df["per_returns"].std()
    running_max = np.maximum.accumulate(worth_df['Total'])
    running_max[running_max < 1] = 1
    drawdown = (worth_df['Total'])/running_max - 1
    max_drawdown = drawdown.min()
    target = 0
    returns_df['downside_returns'] = 0
    returns_df.loc[returns_df['returns'] < target, 'downside_returns'] = returns_df['returns']**2
    down_stdev = np.sqrt(returns_df['downside_returns'].mean())
    sortino_ratio = (returns_df['returns'].mean() - riskfree_rate)/down_stdev

    # Print
    print('\n')
    start = "2016-08-31"
    end = "2020-10-10"

    print("Start\t\t\t\t\t", start)
    print("End\t\t\t\t\t", end)
    print("Portfolio Final Value [₹]\t\t", worth_df['Total'][-1])
    print("Portfolio Initial Value [₹]\t\t", worth_df['Total'][0])
    print("Portfolio peak [Rs]\t\t\t", worth_df['Total'].max())
    print("Return [%]\t\t\t\t", round((worth_df['Total'][-1]/worth_df['Total'][0]-1)*100,2))
    print("Max. Drawdown [%]\t\t\t", round(abs(max_drawdown)*100,1))
    print("Avg. Drawdown [%]\t\t\t", round(abs(drawdown.mean())*100,1))
    print("Sharpe Ratio\t\t\t\t", round(sharpe_ratio,3))
    print("Sortino Ratio\t\t\t\t", round(sortino_ratio,3))

     # Plot

    mpl.style.use('seaborn')
    fig, axs = plt.subplots(3, 1)

    axs[0].plot(worth_df['Total'],color='blue')
    axs[0].set_xlabel('Date')
    axs[0].set_ylabel('Portfolio Value [₹]')
    axs[0].grid(True)

    axs[1].plot(returns_df["returns"],dashes=[6, 2])
    axs[1].set_ylabel('Cumm. returns')
    axs[1].set_xlabel('Date')
    axs[1].grid(True)

    axs[2].plot(drawdown.abs()*100,color='red',dashes=[6, 2])
    axs[2].set_xlabel('Date')
    axs[2].set_ylabel('Drawdown %')
    axs[2].grid(True)

    fig.autofmt_xdate()
    plt.show()


# +
print(  "\033[4m"+"\033[1m" + "Market position" + "\033[0m"+"\033[0m")
Capstone_backtest(Market_position_df,final_price_matrix,0.01)

print(  "\033[4m"+"\033[1m" + "Momentum position" + "\033[0m"+"\033[0m")
Capstone_backtest(Momentum_position_df,final_price_matrix,0.01)

print(  "\033[4m"+"\033[1m" + "Quality position" + "\033[0m"+"\033[0m")
Capstone_backtest(Quality_position_df,final_price_matrix,0.01)

print(  "\033[4m"+"\033[1m" + "Value position" + "\033[0m"+"\033[0m")
Capstone_backtest(Value_position_df,final_price_matrix,0.01)

print(  "\033[4m"+"\033[1m" + "Liquidity position" + "\033[0m"+"\033[0m")
Capstone_backtest(Liquidity_position_df,final_price_matrix,0.01)

print(  "\033[4m"+"\033[1m" + "Size position" + "\033[0m"+"\033[0m")
Capstone_backtest(Size_position_df,final_price_matrix,0.01)

# Market_position_df
# Momentum_position_df
# Quality_position_df
# Value_position_df
# Liquidity_position_df
# Size_position_df

StarcoderdataJupyterScriptsDedupFiltered