File size: 1,386 Bytes
dfbd37e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import requests

# This function groups the data by month
# and returns the first, last or middle data of each month
def get_monthly_sip_nav_df(df, start_date, end_date, SIP_date):
    df = df.copy()
    df['date'] = pd.to_datetime(df['date'])
    df = df[(df['date'] >= start_date) & (df['date'] <= end_date)]
    if SIP_date == 'start':
        df = df.groupby([df['date'].dt.year, df['date'].dt.month]).first()
    elif SIP_date == 'end':
        df = df.groupby([df['date'].dt.year, df['date'].dt.month]).last()
    else:
        df = df.groupby([df['date'].dt.year, df['date'].dt.month]).apply(lambda x: x.iloc[len(x)//2])
    return df


# This function returns the complete list of mutual fund schemes in a DataFrame
def get_all_mf_schemes_df():
    url = "https://api.mfapi.in/mf"
    response = requests.get(url)
    schemes = response.json()
    return pd.DataFrame(schemes)

# This function returns the data of a particular mutual fund scheme, and its inception date
def get_mf_scheme_data(scheme_code):
    url = f"https://api.mfapi.in/mf/{scheme_code}"
    response = requests.get(url)
    data = response.json()
    df = pd.DataFrame(data['data'])
    df['date'] = pd.to_datetime(df['date'], format='%d-%m-%Y')
    df['nav'] = df['nav'].astype(float)
    df = df.sort_values('date')
    inception_date = df['date'].min()
    return df, inception_date