def get_or_add_mf_obj(amfi_code):
    try:
        mf_obj = MutualFund.objects.get(code=amfi_code)
        return mf_obj
    except MutualFund.DoesNotExist:
        mf = Mftool()
        mf_schemes = get_scheme_codes(mf, False)

        for code, details in mf_schemes.items():
            if amfi_code == code:
                isin2 = None
                if details['isin2'] and details['isin2'] != '' and details[
                        'isin2'] != '-':
                    isin2 = details['isin2']
                mf_obj = MutualFund.objects.create(
                    code=code,
                    name=details['name'],
                    isin=details['isin1'],
                    isin2=isin2,
                    fund_house=details['fund_house'],
                    collection_start_date=datetime.date.today())
                return mf_obj
    mf_details = get_mf_details_from_gist(amfi_code)
    if mf_details:
        mf_obj = MutualFund.objects.create(
            code=amfi_code,
            name=details['name'],
            isin=details.get('isin1', None),
            isin2=details.get('isin2', None),
            fund_house=details['fund_house'],
            collection_start_date=datetime.date.today())
        return mf_obj
    return None
Example #2
0
def get_mf_vals(amfi_code, start, end):
    mf = Mftool()
    response = dict()
    for _ in range(3):
        try:
            vals = mf.get_scheme_historical_nav_year(amfi_code, start.year)
            if vals:
                data = vals['data']
                #print(f' data in get_mf_vals for code {amfi_code} : {data}')
                for entry in data:
                    if 'date' in entry.keys():
                        entry_date = datetime.datetime.strptime(
                            entry['date'], "%d-%m-%Y").date()
                        if entry_date >= start and entry_date <= end:
                            response[entry_date] = float(entry['nav'])
                    if 'Error' in entry.keys():
                        break
                break
        except Exception as ex:
            print(ex)
            pass
    return response
Example #3
0
def get_historical_year_mf_vals(amfi_code, year):
    mf = Mftool()
    today = datetime.date.today()
    for _ in range(3):
        try:
            vals = mf.get_scheme_historical_nav_year(amfi_code, year)
            if vals:
                data = vals['data']
                print(" data in get_mf_vals ", amfi_code, data)
                for entry in data:
                    entry_date = datetime.datetime.strptime(
                        entry['date'], "%d-%m-%Y").date()
                    if entry_date.day in [
                            27, 28, 29, 30, 31, 1
                    ] or (entry_date.year == today.year and abs(
                        (today - entry_date).days) <= 5):
                        nav = float(entry['nav'])
                        try:
                            code = MutualFund.objects.get(code=amfi_code)
                            new_entry = HistoricalMFPrice(code=code,
                                                          date=entry_date,
                                                          nav=nav)
                            new_entry.save()
                        except IntegrityError:
                            pass
                        except Exception as ex:
                            print(
                                "error getting historical mf vals for mutual fund object with code ",
                                amfi_code, ex)
                            pass
                break
        except Exception as ex:
            print(
                f"exception in getting historial mf vals for {amfi_code} for year {year} {ex}"
            )
            pass
def update_mf_scheme_codes():
    print("inside update_mf_scheme_codes")
    mf = Mftool()
    mf_schemes = get_scheme_codes(mf, False)
    #print(mf_schemes)
    changed = 0
    added = 0
    for code, details in mf_schemes.items():
        isin2 = None
        if details['isin2'] and details['isin2'] != '' and details[
                'isin2'] != '-':
            isin2 = details['isin2']
        mf_obj = None
        try:
            mf_obj = MutualFund.objects.get(code=code)
        except MutualFund.DoesNotExist:
            mf_obj = MutualFund.objects.create(
                code=code,
                name=details['name'],
                isin=details['isin1'],
                isin2=isin2,
                fund_house=details['fund_house'],
                collection_start_date=datetime.date.today())
            print('added mutual fund with code', code)
            added = added + 1
        details_changed = False
        if mf_obj.isin != details['isin1']:
            mf_obj.isin = details['isin1']
            details_changed = True
        if mf_obj.isin2 != isin2:
            mf_obj.isin2 = isin2
            details_changed = True
        if mf_obj.name != details['name']:
            mf_obj.name = details['name']
            details_changed = True
        if details_changed:
            changed = changed + 1
            mf_obj.save()
    if added or changed:
        print('Addition to schemes:', added, '. Changed scheme details:',
              changed)
    else:
        print('No addition or changes detected in mutual fund schemes')
def get_mutual_funds(request):
    print('inside get_mutual_funds')
    filte = request.GET.get('q', '')
    fund_house = request.GET.get('fund_house', '')
    print(f' {filte} {fund_house}')
    mfs = list()
    '''
    try:
        i = 0
        for mfo in MutualFund.objects.filter(name__contains=filte):
            data = dict()
            data['value'] = mfo.code
            data['label'] = mfo.name
            mfs.append(data)
            i = i +1
            if i > 10:
                break
    except Exception as ex:
        print('exception in AvailableMutualFunds', ex)
    '''
    mf = Mftool()
    sc = get_scheme_codes(mf)
    print(f'Total number of schemes: {len(sc)}')
    i = 0
    for code, details in sc.items():
        if details['fund_house'] == fund_house and filte in details[
                'name'].lower():
            data = dict()
            data['value'] = code
            data['label'] = details['name']
            mfs.append(data)
            i += 1
            if i > 10:
                break
    #s = json.dumps(mfs)
    print(f'returning {len(mfs)} matching items')

    return JsonResponse(mfs, safe=False)
def get_fund_houses():
    print("inside get_fund_houses")
    mf = Mftool()
    ret = set()
    '''
    data = mf.get_all_amc_profiles(False)

    if data:
        for e in data:
            ret.add(e['Name of the Mutual Fund'])
        return ret
    '''
    url = mf._get_quote_url
    response = mf._session.get(url)
    data = response.text.split("\n")
    probable_fh = ''
    for scheme_data in data:
        if not ";" in scheme_data and scheme_data.strip() != "":
            probable_fh = scheme_data.strip()
        elif ";" in scheme_data:
            if probable_fh != "":
                ret.add(probable_fh)
            probable_fh = ''
    return ret
Original file is located at
    https://colab.research.google.com/drive/1ZYwSBowCZusB0KMIoMZl_yoDcbkiUwOp

Author: Shreyans Jain: https://www.linkedin.com/in/shreyans-jain-693655177/
Article Link on TradeWithPython: https://tradewithpython.com/getting-mutual-funds-net-asset-value-via-python-using-mftools-api
"""
#installing the required Packages 
pip install datetime
pip install mftool 

import pandas as pd
from mftool import Mftool
from datetime import datetime, timedelta # importing datetime and timedelta form datetime

mf = Mftool()

# Getting the scheme codes of mutual funds
scheme_codes = mf.get_scheme_codes()
scheme_codes

# getting only the scheme codes from the dictionary.
scheme_code_list = [x for x in scheme_codes.keys()]
scheme_code_list

def HistoricalNav(scheme_code_list, start_date, end_date):
  # Assert keyword is a debugging tool.
  # Below assert keyword check whehther the scheme_code_list is a list and it is present, if not it raises an assertion failure message.
  assert (isinstance(scheme_code_list, list) is True), "Arguement scheme_code_list should be a list" 
  assert (isinstance(start_date, str) is True), "start_date must be a str in %d-%m-%Y format" # checks whether start date is present and is in correct format.
  assert (isinstance(end_date, str) is True), "end_date must be a str in %d-%m-%Y format" # checks whether end date is present and is in correct format
Example #8
0
 def setUp(self):
     self.mftool = Mftool()
Example #9
0
class TestAPIs(unittest.TestCase):
    def setUp(self):
        self.mftool = Mftool()

    def test_get_scheme_codes(self):
        sc = self.mftool.get_scheme_codes()
        self.assertIsNotNone(sc)
        self.assertIsInstance(sc, dict)
        # test the json format return
        sc_json = self.mftool.get_scheme_codes(as_json=True)
        self.assertIsInstance(sc_json, str)
        # reconstruct the dict from json and compare
        six.assertCountEqual(self, sc, json.loads(sc_json))

    def test_is_valid_code(self):
        code = '119598'
        self.assertTrue(self.mftool.is_valid_code(code))

    def test_negative_is_valid_code(self):
        wrong_code = '1195'
        self.assertFalse(self.mftool.is_valid_code(wrong_code))

    def test_get_scheme_quote(self):
        code = '101305'
        self.assertIsInstance(self.mftool.get_scheme_quote(code), dict)
        # with json respomftool
        self.assertIsInstance(self.mftool.get_scheme_quote(code, as_json=True),
                              str)
        # with wrong code
        code = 'wrong code'
        self.assertIsNone(self.mftool.get_scheme_quote(code))
        # with code in 'int' format
        code = 101305
        self.assertIsInstance(self.mftool.get_scheme_quote(code), dict)

    def test_get_scheme_historical_nav(self):
        code = '101305'
        self.assertIsInstance(self.mftool.get_scheme_historical_nav(code),
                              dict)
        # with json respomftool
        self.assertIsInstance(
            self.mftool.get_scheme_historical_nav(code, as_json=True), str)
        # with wrong code
        code = 'wrong code'
        self.assertIsNone(self.mftool.get_scheme_historical_nav(code))
        # with code in 'int' format
        code = 101305
        self.assertIsInstance(self.mftool.get_scheme_historical_nav(code),
                              dict)

    def test_get_scheme_details(self):
        code = '101305'
        self.assertIsInstance(self.mftool.get_scheme_details(code), dict)
        # with json respomftool
        self.assertIsInstance(
            self.mftool.get_scheme_details(code, as_json=True), str)
        # with wrong code
        code = 'wrong code'
        self.assertIsNone(self.mftool.get_scheme_details(code))
        # with code in 'int' format
        code = 101305
        self.assertIsInstance(self.mftool.get_scheme_details(code), dict)
Example #10
0
"""
Created on Tue Jan 14 13:46:40 2020

@author: admin
"""

import os
os.chdir('E:\\Sri\\')

from glob import glob
from mftool import Mftool
from tqdm import tqdm
import pandas as pd
import numpy as np
lst = glob('Data_filtered\\Nav*')
mf = Mftool()
ite_code = 0
Val = np.zeros([15000, 7])
date_object = ["7d", "30d", "90d", "180d", "12M", "36M", "60M"]
wei = [53, 12, 4, 2, 1, 0.333, 0.2]
#df = pd.DataFrame({'dummy': rank_mat }, index = date_object)
Cod = []
select = []
select_pct = []
New_scheme = []
for i in tqdm(iter(lst)):
    df = pd.read_pickle(i)
    #df = df.drop('dummy',axis=1)
    codes = df.keys()
    for code in iter(codes):
        #Val = Val_d
Example #11
0
class TestAPIs(unittest.TestCase):
    def setUp(self):
        self.mftool = Mftool()

    def test_get_scheme_codes(self):
        sc = self.mftool.get_scheme_codes()
        self.assertIsNotNone(sc)
        self.assertIsInstance(sc, dict)
        # test the json format return
        sc_json = self.mftool.get_scheme_codes(as_json=True)
        self.assertIsInstance(sc_json, str)
        # reconstruct the dict from json and compare
        six.assertCountEqual(self, sc, json.loads(sc_json))

    def test_is_valid_code(self):
        code = '119598'
        self.assertTrue(self.mftool.is_valid_code(code))

    def test_negative_is_valid_code(self):
        wrong_code = '1195'
        self.assertFalse(self.mftool.is_valid_code(wrong_code))

    def test_get_scheme_quote(self):
        code = '101305'
        self.assertIsInstance(self.mftool.get_scheme_quote(code), dict)
        # with json respomftool
        self.assertIsInstance(self.mftool.get_scheme_quote(code, as_json=True),
                              str)
        # with wrong code
        code = 'wrong code'
        self.assertIsNone(self.mftool.get_scheme_quote(code))
        # with code in 'int' format
        code = 101305
        self.assertIsInstance(self.mftool.get_scheme_quote(code), dict)
        # verify data present
        result = self.mftool.get_scheme_quote(code)
        self.assertIsNotNone(result)

    def test_get_scheme_historical_nav(self):
        code = '101305'
        self.assertIsInstance(self.mftool.get_scheme_historical_nav(code),
                              dict)
        # with json respomftool
        self.assertIsInstance(
            self.mftool.get_scheme_historical_nav(code, as_json=True), str)
        # with wrong code
        code = 'wrong code'
        self.assertIsNone(self.mftool.get_scheme_historical_nav(code))
        # with code in 'int' format
        code = 101305
        self.assertIsInstance(self.mftool.get_scheme_historical_nav(code),
                              dict)
        # verify data present
        result = self.mftool.get_scheme_historical_nav(code)
        self.assertIsNotNone(result)

    def test_get_scheme_details(self):
        code = '101305'
        self.assertIsInstance(self.mftool.get_scheme_details(code), dict)
        # with json respomftool
        self.assertIsInstance(
            self.mftool.get_scheme_details(code, as_json=True), str)
        # with wrong code
        code = 'wrong code'
        self.assertIsNone(self.mftool.get_scheme_details(code))
        # with code in 'int' format
        code = 101305
        self.assertIsInstance(self.mftool.get_scheme_details(code), dict)
        # verify data present
        result = self.mftool.get_scheme_details(code)
        self.assertIsNotNone(result)

    def test_calculate_balance_units_value(self):
        code = '101305'
        result = self.mftool.calculate_balance_units_value(code, 221)
        self.assertIsNotNone(result)

    def test_get_scheme_historical_nav_year(self):
        code = '101305'
        self.assertIsInstance(
            self.mftool.get_scheme_historical_nav_year(code, 2018), dict)
        # with json respomftool
        self.assertIsInstance(
            self.mftool.get_scheme_historical_nav_year(code,
                                                       2018,
                                                       as_json=True), str)
        # with wrong code
        code = 'wrong code'
        self.assertIsNone(
            self.mftool.get_scheme_historical_nav_year(code, 2018))
        # with code in 'int' format
        code = 101305
        self.assertIsInstance(
            self.mftool.get_scheme_historical_nav_year(code, 2018), dict)
        # verify data present
        result = self.mftool.get_scheme_historical_nav_year(code, 2018)
        self.assertIsNotNone(result)

    def test_get_day(self):
        if self.mftool.is_holiday():
            self.assertTrue((self.mftool.get_friday()))
        else:
            self.assertTrue((self.mftool.get_today()))

    def test_get_scheme_historical_nav_for_dates(self):
        code = '101305'
        self.assertIsInstance(
            self.mftool.get_scheme_historical_nav_for_dates(
                code, '1-1-2018', '31-12-2018'), dict)
        # with json respomftool
        self.assertIsInstance(
            self.mftool.get_scheme_historical_nav_for_dates(code,
                                                            '1-1-2018',
                                                            '31-12-2018',
                                                            as_json=True), str)
        # with wrong code
        code = 'wrong code'
        self.assertIsNone(
            self.mftool.get_scheme_historical_nav_for_dates(
                code, '1-1-2018', '31-12-2018'))
        # with code in 'int' format
        code = 101305
        self.assertIsInstance(
            self.mftool.get_scheme_historical_nav_for_dates(
                code, '1-1-2018', '31-12-2018'), dict)
        # verify data present
        result = self.mftool.get_scheme_historical_nav_for_dates(
            code, '1-1-2018', '31-12-2018')
        self.assertIsNotNone(result)

    def test_get_open_ended_equity_scheme_performance(self):
        self.assertIsInstance(
            self.mftool.get_open_ended_equity_scheme_performance(False), dict)
        # verify data present
        result = self.mftool.get_open_ended_equity_scheme_performance(False)
        self.assertNotEqual(
            result, {
                'Large Cap': [],
                'Large & Mid Cap': [],
                'Multi Cap': [],
                'Mid Cap': [],
                'Small Cap': [],
                'Value': [],
                'ELSS': [],
                'Contra': [],
                'Dividend Yield': [],
                'Focused': []
            })