File size: 5,454 Bytes
77fd868
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import gradio as gr
import pandas as pd
import yfinance as yf
from datetime import timedelta,datetime
import pytz
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from IPython.display import display



def dateoffset(input_date_str):
    
    input_date_dt = datetime.strptime(input_date_str, "%Y-%m-%d")

    
    new_date_dt = input_date_dt - timedelta(days=1)

    
    new_date_str = new_date_dt.strftime("%Y-%m-%d")

    return new_date_str


def setdates(startdate, enddate):
    while startdate not in nifty50["nifty50"].data.index:
        startdate = dateoffset(startdate)

    while enddate not in nifty50["nifty50"].data.index:
        enddate = dateoffset(enddate)

    return startdate, enddate


def organisedata(startdate, enddate):
    
    startdate, enddate = setdates(startdate, enddate)

    
    symbols = list(nifty_stocks.keys())

    
    common_index = nifty50["nifty50"].data.loc[startdate:enddate].index

    
    data_frame = pd.DataFrame(index=symbols, columns=common_index)

    
    for symbol, stock_object in nifty_stocks.items():
        stock_data = stock_object.data.loc[startdate:enddate, 'Close']
        data_frame.loc[symbol] = stock_data.reindex(common_index).values

    return data_frame

def previoustimeframedata(n, startdate):
    
    startdate_dt = pd.to_datetime(startdate)

    
    ndaysagodate = startdate_dt - timedelta(days=int(n))

    
    ndaysagodate_str = ndaysagodate.strftime("%Y-%m-%d")
    startdate_str = startdate_dt.strftime("%Y-%m-%d")

    
    return organisedata(ndaysagodate_str, startdate_str)

def portfoliooperations(equity,startdate,ndaywindow,portfolio):
    
    startdate_dt = pd.to_datetime(startdate)
    windowenddate = startdate_dt + timedelta(days=int(ndaywindow))
    windowenddate_str = windowenddate.strftime("%Y-%m-%d")

    startdate,windowenddate = setdates(startdate,windowenddate_str) 
    
    window_data = organisedata(startdate,windowenddate) 

    differences = window_data.iloc[:, -1] - window_data.iloc[:, 0]  

    next_portfolio = differences[differences > 0].index.tolist() 

    
    portfolio_sum = window_data.loc[portfolio, window_data.columns[0]].sum()

    
    multiplier = equity / portfolio_sum if portfolio_sum != 0 else 0


    portfolio_value = pd.DataFrame(index=window_data.columns, columns=['value'])

    for date in window_data.columns:
    
      portfolio_sum = window_data.loc[portfolio, date].sum()
    
      portfolio_value.loc[date, 'value'] = portfolio_sum * multiplier


    return next_portfolio,portfolio_value

def mainfunction (equity,startdate,enddate,ndaywindow):
    
    pastwindow = previoustimeframedata(n=ndaywindow,startdate=startdate) # No Errors untill here

    differences = pastwindow.iloc[:, -1] - pastwindow.iloc[:, 0]

    portfolio = differences[differences > 0].index.tolist() # No Errors untill here

    portfolio,portfolio_value = portfoliooperations(equity=equity,startdate=startdate,ndaywindow=ndaywindow,portfolio=portfolio)



    enddate_tz = datetime.strptime(enddate,"%Y-%m-%d").replace(tzinfo=pytz.timezone('Asia/Kolkata'))

    while portfolio_value.index[-1] < pd.to_datetime(enddate_tz) - timedelta(days=int(ndaywindow)):

      portfolio,new_portfolio_value = portfoliooperations(equity=equity,startdate=startdate,ndaywindow=ndaywindow,portfolio=portfolio)

      portfolio_value = pd.concat([portfolio_value, new_portfolio_value])

      startdate = (pd.to_datetime(startdate)+ timedelta(days=int(ndaywindow))).strftime("%Y-%m-%d")
      
      equity = portfolio_value.iloc[-1, 0]

    return portfolio_value

def calculate_cagr(series):
    total_return = (series.iloc[-1] / series.iloc[0]) - 1
    num_years = len(series) / 252  
    cagr = (1 + total_return) ** (1 / num_years) - 1
    return cagr * 100


def calculate_volatility(series):
    return series.pct_change().std() * np.sqrt(252) * 100


def calculate_sharpe_ratio(series, risk_free_rate=0):
    cagr = calculate_cagr(series)
    volatility = calculate_volatility(series)
    sharpe_ratio = (cagr - risk_free_rate) / volatility
    return sharpe_ratio


def final_function(equity,startdate,enddate,ndaywindow):

    equity = int(equity)
    ndaywindow = int(ndaywindow)

    portfolio_value = mainfunction(equity=equity,startdate=startdate,enddate=enddate,ndaywindow=ndaywindow)
    nifty_data = nifty50["nifty50"].data
    subset_data = nifty_data[startdate:enddate]
    initial_nifty = subset_data['Close'][0]
    nifty_dataseries = (equity/initial_nifty)*subset_data['Close']
    plt.figure(figsize=(10, 6))
    plt.plot(portfolio_value['value'], label='Strategy')
    plt.plot(nifty_dataseries, label='Nifty50 as Benchmark')
    plt.title('Benchmark vs Strategy')
    plt.xlabel('Date')
    plt.ylabel('Close Price')
    plt.legend()


    image_path = "output_plot.png"
    plt.savefig(image_path)
    plt.close()


    image = Image.open(image_path)

    strategy_cagr = calculate_cagr(portfolio_value['value'])
    strategy_volatility = calculate_volatility(portfolio_value['value'])
    strategy_sharpe_ratio = calculate_sharpe_ratio(portfolio_value['value'])

    benchmark_cagr = calculate_cagr(nifty_dataseries)
    benchmark_volatility = calculate_volatility(nifty_dataseries)
    benchmark_sharpe_ratio = calculate_sharpe_ratio(nifty_dataseries)


    return image, strategy_cagr, strategy_volatility, strategy_sharpe_ratio, benchmark_cagr, benchmark_volatility, benchmark_sharpe_ratio