def createByer(nBuy):
    Byer = []
    for i in xrange(int(nBuy * 0.9)):
        Byer.append(
            Investor(random.randint(2700, 3000), 1, random.uniform(0, 3), 0))
    for i in xrange(int(nBuy * 0.1)):
        Byer.append(
            Investor(random.randint(3000, 3300), 1, random.uniform(0, 1), 0))
    return Byer
 def __init__(self, params, contract_name, token_contract_name, log_path):
     Crowdsale.__init__(self, params, contract_name, log_path)
     self.state = self.states["PendingConfiguration"]
     self.investors.append(Investor(self.accounts[1], True, 0))
     self.investors.append(Investor(self.accounts[2], True, 1))
     self.investors.append(Investor(self.accounts[3], False, 0))
     self.investors.append(Investor(self.accounts[4], False, 1))
     self.token_balances = {x: 0 for x in self.accounts}
     self.multisig_wei = self.web3.eth.getBalance(self.params['MW_address'])
     self.token_contract_name = token_contract_name
Example #3
0
def main():
    s = Stock()
    prices = []

    smi = 300  # number of smart money investors
    iis = 500  # number of institutional investors
    hho = 8000  # number of house hold investors

    smif = 40000  # smart money investor's funds
    iisf = 80000  # institutional investor investor's funds
    hhof = 2000  # house hold investor's funds

    my_investors = []

    for i in range(1, smi):
        investor = Investor(i, "smart money", smif, s)
        my_investors.append(investor)

    for i in range(smi, iis + smi):
        investor = Investor(i, "institutional", iisf, s)
        my_investors.append(investor)

    for i in range(iis + smi, iis + smi + hho):
        investor = Investor(i, "householding", hhof, s)
        my_investors.append(investor)

    for day in range(0, 150):
        for inv in my_investors:
            inv.decide()
        s.tick()
        prices.append([day, s.get_price()])

    for p in prices:
        print(p[0], p[1])

    #csvP = CsvProcess()
    #csvP.csvWrite(prices,'price.csv')

    numPrices = np.asarray(prices)
    plt.figure(1)
    plt.plot(numPrices[:, 1])
    plt.xlabel('Time')
    plt.ylabel('Price')

    #plt.figure(2)
    #plt.plot(numPrices[0:60,1])
    #plt.xlabel('Time')
    #plt.ylabel('Price')
    plt.show()
Example #4
0
def generate_investor_list():
    """Use a investor permalink list to generate a file with investor info."""
    investor_permalinks = read_names_from_file(VC_NAMES_FILE)

    investors = []
    for permalink in investor_permalinks:
        investor_dict = lookup_financial_org_by_permalink(permalink)
        investor = Investor(investor_dict)
        investors.append(investor)

    write_investor_csv(investors)
Example #5
0
    def __init__(self,
                 sdate,
                 edate,
                 buy_solver,
                 db,
                 cash=1000,
                 buy_size=25.0,
                 liquidity_limit=1.0):
        self.investor = Investor(cash)
        self.month = pd.Period(sdate, freq='M')
        self.end_month = pd.Period(edate, freq='M')
        self.buy_solver = buy_solver
        self.db = db
        self.buy_size = buy_size
        self.liquidity_limit = liquidity_limit

        self.buy_solver_name = self.buy_solver_lookup(self.buy_solver)

        self.stats = defaultdict(dict)
        self.loans = pd.DataFrame()
        self.current_loans = dict()
Example #6
0
    def __init__(self, sdate, edate, buy_solver, db, cash=1000, buy_size=25.0, liquidity_limit=1.0):
        self.investor = Investor(cash)
        self.month = pd.Period(sdate, freq='M')
        self.end_month = pd.Period(edate, freq='M')
        self.buy_solver = buy_solver
        self.db = db
        self.buy_size = buy_size
        self.liquidity_limit = liquidity_limit

        self.buy_solver_name = self.buy_solver_lookup(self.buy_solver)
        
        self.stats = defaultdict(dict)
        self.loans = pd.DataFrame()
        self.current_loans = dict()
Example #7
0
def test_exchange():
    asset_names = [{
        'name': "Asset 1",
        'id': 1
    }, {
        'name': "Asset 2",
        'id': 2
    }, {
        'name': "Asset 3",
        'id': 3
    }, {
        'name': "Asset 4",
        'id': 4
    }, {
        'name': "Asset 5",
        'id': 5
    }, {
        'name': "Asset 6",
        'id': 6
    }, {
        'name': "Asset 7",
        'id': 7
    }, {
        'name': "Asset 8",
        'id': 8
    }]

    exchange = Exchange("TestExchange", asset_names=asset_names)

    broker = Broker(id=1000, exchange=exchange)

    investor1 = Investor(id=2000, cap=100000, broker=broker)

    for i in range(1):
        investor1.buy(assetid=1, price=5.0, amount=1000)

    investor2 = Investor(id=2001, cap=100000, broker=broker)

    for i in range(5):
        investor2.sell(assetid=1, price=5.0, amount=100)
Example #8
0
            s.Status = 0
            Byer[i].Status = 0
            return True, s.Exp, Byer[i].Exp
        i -= 1
    return False, 0, 0


# simulate
finalPrice = []
pstPrice = 50
pstValue = 0
pstAmnt = 0
Byer = []
Sler = []
for i in xrange(150):
    Byer.append(Investor(0, 1, random.randint(0, 9), 0))
for i in xrange(150):
    Sler.append(Investor(100, -1, random.randint(0, 9), 0))

__displayAll()

for i in xrange(240):
    pstValue = 0
    pstAmnt = 0

    for b in Byer:
        b.histExp.append(b.Exp)
        b.Exp += expChangeFunc(b, pstPrice, 0)
        if b.Status == 1:
            tResult, bexp, sexp = tryBuy(Sler, b)
            if tResult:
Example #9
0
# Submit valid request
print('Submit valid request')
loan1.submitLoanRequest(borrower1, amount=5000, installment_period=6)

# List borrower1 loan Requests
print('List borrower1 loan Requests')
borrower1.checkMyLoans()

# Get loan1 details
print('Get loan1 details')
loan1.showLoanReqDetails()

# create Investors
print('create Investors')
investor1 = Investor(balance=20000)
investor2 = Investor(balance=30000)
investor3 = Investor(balance=100)
print('investor1 investor2 investor3 are created')

# Investors Submitting offers
print('investor1 submit valid offer')
loan1.submitLoanOffer(investor=investor1, interest=10)
print('investor2 submit valid offer')
loan1.submitLoanOffer(investor=investor2, interest=15)

# test submitting offer validation
print('investor3 submit invalid offer investor has no enough balance ')
loan1.submitLoanOffer(investor=investor3, interest=5)

# list loan1 offers
Example #10
0
def main():
	# Parse arguments to determine if we're in test mode or production mode
	parser = argparse.ArgumentParser(description='Autonomous LendingClub account management.')
	parser.add_argument('-p', '--productionMode', action='store_true', help='Enter production mode. Required to invest or transfer funds.')
	parser.add_argument('-t', '--testFilters', action='store_true', help='Test loan filters by applying them to all loans currently listed. Exit once complete.')
	args = parser.parse_args()
	if args.productionMode:
		logger.warning('Entering production mode. Auto-investor may invest in loans or transfer money into your LendingClub account according to your configuration.')
	if args.testFilters:
		logger.info('Entering filter test mode.')

	# Retrieve configuration so we can set up exception handler
	config = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config', 'config.json')
	conf = json.load(open(config))

	global notification_email
	notification_email = conf['email']
	sys.excepthook = global_exc_handler

	# Now that exceptions will be emailed, parse loan filters
	rules = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config', 'rules.json')
	filters = json.load(open(rules))
	db = 'loans.db'

	# Create investor object
	i = Investor.Investor(conf['iid'], conf['auth'], productionMode=args.productionMode)

	# Get loan portfolio
	portfolioName = datetime.now().__format__('%m.%y')
	portfolio = get_portfolio(i, portfolioName)
	if not portfolio:
		portfolio = i.create_portfolio(portfolioName)
	portfolioId = portfolio['portfolioId']

	# Initialize filters
	init_filters(i, filters)

	# Conditionally verify filters
	if args.testFilters:
		i.test_filters()
		logger.info('Filter test complete.')
		return

	# Retrieve available cash and any pending transfers
	available_cash = i.get_cash()
	xfers = i.get_pending_transfers()
	pending_xfer_amt = sum(map(lambda x : x['amount'], xfers))

	# Transfer additional funds if we are below the minimum cash balance
	total_funds = available_cash + pending_xfer_amt
	if total_funds < conf['min_balance']:
		xfer_amt = ((conf['min_balance'] - total_funds) + (conf['orderamnt'] - .01)) // conf['orderamnt'] * conf['orderamnt']
		logger.info('Transfering $%d to meet minimum balance requirement of $%d' % (xfer_amt, conf['min_balance']))
		i.add_funds(xfer_amt)
		pending_xfer_amt += xfer_amt

	# Retrieve new loans that pass filters
	logger.info('Retrieving newly posted loans')
	new_loans = i.get_new_loans()
	if not len(new_loans):
		logger.info('No new loans to invest in. Exiting.')
		return

	# Save loans away for characterization later
	logger.info('%s loans pass filters' % (len(new_loans)))
	add_to_db(db, new_loans)

	# Bail out if we don't have enough cash to invest
	if available_cash < conf['orderamnt']:
		logger.warning('Exiting. Not enough cash to invest')
		return

	# Hell yeah, let's order
	#if 'yes' in input('Are you sure you wish to invest in these loans? (yes/no): '):
	num_loans = int(min( int(available_cash) / conf['orderamnt'], len(new_loans)))
	logger.info('Placing order with %s loans.' % (num_loans))
	if i.submit_order(new_loans[0 : num_loans], portfolioId):
		email_body = 'Purchased %s loan(s) at %s\n\n' % (num_loans, datetime.now())
		for loan in new_loans[0 : num_loans]:
			email_body += '%s\n' % (str(loan))
		email_purchase_notification(conf['email'], num_loans, email_body=email_body)

	return
Example #11
0
from borrower import Borrower
from investor import Investor
from loan import Loan
from paymentFacade import PaymentFacade
from lenmoSingleton import Lenmo

borrower = Borrower(balance=100000)
investor = Investor(balance=2000000)
loan = Loan()
loan.submitLoanRequest(borrower=borrower, amount=500000, installment_period=6)
loan.showLoanReqDetails()
loan.submitLoanOffer(investor, 15)
loan.showLoanOffers()
offerId = loan.offers[0].id
loan.acceptLoanOffer(id=offerId)
borrower.checkMyLoanRequests()
investor.showMyOffers()
investor.showMyAcceptedOffers()
transaction = PaymentFacade(loan)
transaction.fundLoan()
print('lenmo balance increased by 3 $ paid by Investor')
print('lenmo balance: ', Lenmo().balance)
print('borrower balance =', borrower.balance)
print('borrower outstanding balance is =', borrower.outstanding)
print('investor balance =', investor.balance)
print('investor outstanding balance is =', investor.outstanding)
print('\n PAYMENT SCHEDULE' + '-' * 30)
transaction.showPaymentSchedule()

print('\n First Transaction' + '-' * 30)
transaction.doMonthlyPayment()
Example #12
0
class Backtest():
    def __init__(self,
                 sdate,
                 edate,
                 buy_solver,
                 db,
                 cash=1000,
                 buy_size=25.0,
                 liquidity_limit=1.0):
        self.investor = Investor(cash)
        self.month = pd.Period(sdate, freq='M')
        self.end_month = pd.Period(edate, freq='M')
        self.buy_solver = buy_solver
        self.db = db
        self.buy_size = buy_size
        self.liquidity_limit = liquidity_limit

        self.buy_solver_name = self.buy_solver_lookup(self.buy_solver)

        self.stats = defaultdict(dict)
        self.loans = pd.DataFrame()
        self.current_loans = dict()

    def buy_solver_lookup(self, function):
        return {
            simple_filter_buy_solver: 'Simple Filter',
            generic_buy_solver: 'Generic n-Loan',
            single_buy_solver: 'Single Buy',
            zero_buy_solver: 'Zero Buy'
        }[function]

    def solve_month(self):
        self.investor.get_payments()
        new_loans, matching_new_loans, available_new_loans = self.buy()

        self.loans = pd.concat([self.loans, new_loans], axis=0)
        self.current_loans[self.month] = [loan for loan in self.investor.loans]
        self.stats['loans added'][self.month] = new_loans.shape[0]
        self.stats['strategy available loans'][self.month] = matching_new_loans
        self.stats['available loans'][self.month] = available_new_loans
        self.stats['loans held'][self.month] = len(self.investor.loans)
        self.stats['cumulative loans held'][self.month] = self.loans.shape[0]
        self.stats['cumulative defaults'][
            self.month] = self.investor.cum_defaults
        self.stats['cash held'][self.month] = self.investor.balance
        self.stats['net worth'][self.month] = self.investor.get_net_worth()
        self.stats['imbalance'][self.month] = self.investor.cum_imbalance
        self.stats['abs imbalance'][
            self.month] = self.investor.abs_cum_imbalance
        self.stats['imbalance %'][self.month] = self.stats['imbalance'][
            self.month] / self.stats['net worth'][self.month]
        self.stats['abs imbalance %'][self.month] = self.stats[
            'abs imbalance'][self.month] / self.stats['net worth'][self.month]

        self.month += 1

    def buy(self):
        month_db = self.db[self.db['issue_d'] == self.month]
        purchase_count = np.floor(self.investor.balance / self.buy_size)
        # if purchase_count > 0: ### We can just pass 0 to the solver and get back an empty dataframe for now
        buy_dict = self.buy_solver(self.month, self.investor, month_db,
                                   purchase_count, self.liquidity_limit)

        buy_df = buy_dict['loans']
        buy_matching = buy_dict['matching quantity']
        buy_available = buy_dict['available quantity']

        if buy_df.empty:
            buy_df = pd.DataFrame()

        new_loans = buy_df.apply(self.map_loan_row, axis=1)

        self.investor.buy_loans(new_loans)
        return new_loans, buy_matching, buy_available

    def map_loan_row(self, row):
        return Loan(loan_id=row['id'],
                    grade=row['grade'],
                    int_rate=row['int_rate'],
                    term=row['term'],
                    amount=row['funded_amnt'],
                    issue_date=row['issue_d'],
                    last_date=row['last_pymnt_d'],
                    investment=self.buy_size,
                    defaults=row['defaulted'],
                    total_payment=row['total_pymnt'],
                    total_principle=row['total_rec_prncp'],
                    recoveries=row['recoveries'])

    def run(self):
        while self.month <= self.end_month:
            print self.month, self.end_month
            self.solve_month()

        self.stats = pd.DataFrame(self.stats)
        self.stats['defaults'] = self.stats['cumulative defaults'].diff()
        self.stats['monthly return'] = self.stats['net worth'].diff().shift(
            -1) / self.stats['net worth']
        self.stats['annualized return'] = self.stats[
            'monthly return'].resample('A', how='mean').resample(
                'M', fill_method='ffill')
        self.stats['total liquidity'] = self.stats['loans added'] / self.stats[
            'available loans']
        self.stats['strategy liquidity'] = self.stats[
            'loans added'] / self.stats['strategy available loans'].replace(
                0, np.nan)
        self.stats['strategy vs total liquidity'] = self.stats[
            'strategy available loans'] / self.stats[
                'available loans'].replace(0, np.nan)
        self.stats['default rate'] = self.stats['defaults'] / self.stats[
            'loans held'].replace(0, np.nan)
        self.stats['growth of $1'] = self.stats['net worth'] / self.stats[
            'net worth'].iloc[0]

        self.stats_dict = dict()

        try:
            self.stats_dict['sharpe'] = self.stats['net worth'].diff().mean(
            ) / self.stats['net worth'].diff().std() * np.sqrt(12)
        except ZeroDivisionError as e:
            warnings.warn('Division by zero: Sharpe Ratio')
            self.stats_dict['sharpe'] = np.nan

        self.stats_dict = pd.Series(self.stats_dict)

        self.loan_stats = dict()
        self.current_loans = {
            month: pd.DataFrame(
                [loan.to_dict() for loan in self.current_loans[month]])
            for month in self.current_loans
        }
        self.loan_stats['grade'] = pd.DataFrame({
            month: self.current_loans[month]['grade'].value_counts()
            for month in self.current_loans
            if not self.current_loans[month].empty
        }).T.reindex(self.stats.index)
        self.loan_stats['grade_int_rate'] = pd.DataFrame({
            month:
            self.current_loans[month].groupby('grade')['int_rate'].mean()
            for month in self.current_loans
            if not self.current_loans[month].empty
        }).T.reindex(self.stats.index)
        self.loan_stats['duration'] = pd.DataFrame({
            month: (self.current_loans[month]['end_date'] - month)
            for month in self.current_loans
            if not self.current_loans[month].empty
        }).T.reindex(self.stats.index) / 12
        self.loan_stats['int_rate'] = pd.DataFrame({
            month: self.current_loans[month]['int_rate']
            for month in self.current_loans
            if not self.current_loans[month].empty
        }).T.reindex(self.stats.index)
        self.loan_stats['defaulted'] = pd.DataFrame({
            month: self.current_loans[month]['defaulted']
            for month in self.current_loans
            if not self.current_loans[month].empty
        }).T.reindex(self.stats.index)
        self.loan_stats['remaining_amount'] = pd.DataFrame({
            month: self.current_loans[month]['remaining_amount']
            for month in self.current_loans
            if not self.current_loans[month].empty
        }).T.reindex(self.stats.index)
        self.loan_stats['imbalance_percentage'] = pd.DataFrame({
            month: self.current_loans[month]['imbalance_percentage']
            for month in self.current_loans
            if not self.current_loans[month].empty
        }).T.reindex(self.stats.index)

        self.loan_stats_total = dict()
        for category in ['duration', 'int_rate',
                         'imbalance_percentage']:  # self.loan_stats:
            self.loan_stats_total[category] = pd.Series(
                self.loan_stats[category].values.flatten()).dropna()

        self.loan_stats_total['imbalance_percentage'] = pd.Series(
            self.loan_stats_total['imbalance_percentage'].value_counts().index
        )  # small hack to remove duplicates between months

        self.loan_stats_total['grade'] = self.loan_stats['grade'].sum()

        return self.stats

    def generate_report(self):
        pass
 def __init__(self):
     self.accountant = Accountant()
     self.polygon = PolygonGateway(self.accountant)
     self.investor = Investor()
Example #14
0
 def createInvestor(self):
     self.investor = Investor(self.totalManey)
def createByerWithParm(nBuy, exp, parm1):
    Byer = []
    for i in xrange(nBuy):
        Byer.append(Investor(exp, 1, parm1, 0))
    return Byer
def createSler(nSel):
    Sler = []
    for i in xrange(nSel):
        Sler.append(
            Investor(random.randint(2700, 3300), -1, random.uniform(0, 1), 0))
    return Sler
Example #17
0
class Backtest():
    def __init__(self, sdate, edate, buy_solver, db, cash=1000, buy_size=25.0, liquidity_limit=1.0):
        self.investor = Investor(cash)
        self.month = pd.Period(sdate, freq='M')
        self.end_month = pd.Period(edate, freq='M')
        self.buy_solver = buy_solver
        self.db = db
        self.buy_size = buy_size
        self.liquidity_limit = liquidity_limit

        self.buy_solver_name = self.buy_solver_lookup(self.buy_solver)
        
        self.stats = defaultdict(dict)
        self.loans = pd.DataFrame()
        self.current_loans = dict()

    def buy_solver_lookup(self, function):
        return {
            simple_filter_buy_solver: 'Simple Filter',
            generic_buy_solver: 'Generic n-Loan',
            single_buy_solver: 'Single Buy',
            zero_buy_solver: 'Zero Buy'
        }[function]
    
    def solve_month(self):
        self.investor.get_payments()
        new_loans, matching_new_loans, available_new_loans = self.buy()
        
        self.loans = pd.concat([self.loans, new_loans], axis=0)
        self.current_loans[self.month] = [loan for loan in self.investor.loans]
        self.stats['loans added'][self.month] = new_loans.shape[0]
        self.stats['strategy available loans'][self.month] = matching_new_loans
        self.stats['available loans'][self.month] = available_new_loans
        self.stats['loans held'][self.month] = len(self.investor.loans)
        self.stats['cumulative loans held'][self.month] = self.loans.shape[0]
        self.stats['cumulative defaults'][self.month] = self.investor.cum_defaults
        self.stats['cash held'][self.month] = self.investor.balance
        self.stats['net worth'][self.month] = self.investor.get_net_worth()
        self.stats['imbalance'][self.month] = self.investor.cum_imbalance
        self.stats['abs imbalance'][self.month] = self.investor.abs_cum_imbalance
        self.stats['imbalance %'][self.month] = self.stats['imbalance'][self.month] / self.stats['net worth'][self.month]
        self.stats['abs imbalance %'][self.month] = self.stats['abs imbalance'][self.month] / self.stats['net worth'][self.month]
        
        self.month += 1
        
    def buy(self):
        month_db = self.db[self.db['issue_d'] == self.month]
        purchase_count = np.floor(self.investor.balance / self.buy_size)
        # if purchase_count > 0: ### We can just pass 0 to the solver and get back an empty dataframe for now
        buy_dict = self.buy_solver(self.month, self.investor, month_db, purchase_count, self.liquidity_limit)

        buy_df = buy_dict['loans']
        buy_matching = buy_dict['matching quantity']
        buy_available = buy_dict['available quantity']

        if buy_df.empty:
            buy_df = pd.DataFrame()

        new_loans = buy_df.apply(self.map_loan_row, axis=1)

        self.investor.buy_loans(new_loans)
        return new_loans, buy_matching, buy_available   

    
    def map_loan_row(self, row):
        return Loan(
            loan_id=row['id'],
            grade=row['grade'],
            int_rate=row['int_rate'],
            term = row['term'],
            amount=row['funded_amnt'],
            issue_date=row['issue_d'],
            last_date=row['last_pymnt_d'],
            investment=self.buy_size,
            defaults=row['defaulted'],
            total_payment=row['total_pymnt'],
            total_principle=row['total_rec_prncp'],
            recoveries=row['recoveries']
        )
        
    def run(self):
        while self.month <= self.end_month:
            print self.month, self.end_month
            self.solve_month()
            
        self.stats = pd.DataFrame(self.stats)
        self.stats['defaults'] = self.stats['cumulative defaults'].diff()
        self.stats['monthly return'] = self.stats['net worth'].diff().shift(-1) / self.stats['net worth']
        self.stats['annualized return'] = self.stats['monthly return'].resample('A', how='mean').resample('M', fill_method='ffill')
        self.stats['total liquidity'] = self.stats['loans added'] / self.stats['available loans']
        self.stats['strategy liquidity'] = self.stats['loans added'] / self.stats['strategy available loans'].replace(0, np.nan)
        self.stats['strategy vs total liquidity'] = self.stats['strategy available loans'] / self.stats['available loans'].replace(0, np.nan)
        self.stats['default rate'] = self.stats['defaults'] / self.stats['loans held'].replace(0, np.nan)
        self.stats['growth of $1'] = self.stats['net worth'] / self.stats['net worth'].iloc[0]
        
        self.stats_dict = dict()

        try:
            self.stats_dict['sharpe'] = self.stats['net worth'].diff().mean() / self.stats['net worth'].diff().std() * np.sqrt(12)
        except ZeroDivisionError as e:
            warnings.warn('Division by zero: Sharpe Ratio')
            self.stats_dict['sharpe'] = np.nan

        self.stats_dict = pd.Series(self.stats_dict)

        self.loan_stats = dict()
        self.current_loans = {month: pd.DataFrame([loan.to_dict() for loan in self.current_loans[month]]) for month in self.current_loans}
        self.loan_stats['grade'] = pd.DataFrame({month: self.current_loans[month]['grade'].value_counts() for month in self.current_loans if not self.current_loans[month].empty}).T.reindex(self.stats.index)
        self.loan_stats['grade_int_rate'] = pd.DataFrame({month: self.current_loans[month].groupby('grade')['int_rate'].mean() for month in self.current_loans if not self.current_loans[month].empty}).T.reindex(self.stats.index)
        self.loan_stats['duration'] = pd.DataFrame({month: (self.current_loans[month]['end_date'] - month) for month in self.current_loans if not self.current_loans[month].empty}).T.reindex(self.stats.index) / 12
        self.loan_stats['int_rate'] = pd.DataFrame({month: self.current_loans[month]['int_rate'] for month in self.current_loans if not self.current_loans[month].empty}).T.reindex(self.stats.index)
        self.loan_stats['defaulted'] = pd.DataFrame({month: self.current_loans[month]['defaulted'] for month in self.current_loans if not self.current_loans[month].empty}).T.reindex(self.stats.index)
        self.loan_stats['remaining_amount'] = pd.DataFrame({month: self.current_loans[month]['remaining_amount'] for month in self.current_loans if not self.current_loans[month].empty}).T.reindex(self.stats.index)
        self.loan_stats['imbalance_percentage'] = pd.DataFrame({month: self.current_loans[month]['imbalance_percentage'] for month in self.current_loans if not self.current_loans[month].empty}).T.reindex(self.stats.index)

        self.loan_stats_total = dict()
        for category in ['duration', 'int_rate', 'imbalance_percentage']: # self.loan_stats:
            self.loan_stats_total[category] = pd.Series(self.loan_stats[category].values.flatten()).dropna()

        self.loan_stats_total['imbalance_percentage'] = pd.Series(self.loan_stats_total['imbalance_percentage'].value_counts().index) # small hack to remove duplicates between months
        
        self.loan_stats_total['grade'] = self.loan_stats['grade'].sum()

            
        return self.stats

    def generate_report(self):
        pass
Example #18
0
class marketPlace():
    def __init__(self, totalManey):
        self.totalManey = totalManey
        self.lstpri = 0

    def createInvestor(self):
        self.investor = Investor(self.totalManey)

    def trading(self,
                strStockName,
                week=7,
                month=30,
                riseThr=0.1,
                fallThr=-0.10,
                buyRate=1.0):

        self.investor.chooseStock(strStockName)
        stock = self.investor.stok1
        print("longOfStockHistData:{}".format(stock.longOfStockHistData))
        start = 260
        ifChuQuan = 0
        for date in range(start, stock.longOfStockHistData):

            stock.updateCurPrice(date)
            r = (stock.curPrice -
                 stock.stockHistData[date - 1]) / stock.curPrice

            if r < -0.15:  # 当派股时,清仓,且month天后再操作
                if stock.stockHands > 0:
                    self.investor.chuquanAndQingCang(date)
                    stock.showStockInfor()
                    self.investor.showIvestorInfor()
                ifChuQuan = date + month
                continue

            if ifChuQuan != 0 and date < ifChuQuan:  # 如果除权了,month天后再操作
                continue
            ifChuQuan = 0

            stock.updateStockStatisticsInfo(date, week, month)

            buyrate = (stock.curPrice - stock.maxAverMinMonth[1]
                       ) / stock.curPrice  #以一个月的股价均值做为参照
            selrate = (stock.curPrice -
                       stock.maxAverMinMonth[1]) / stock.curPrice

            # 长线
            if buyrate < fallThr and stock.stockHands == 0:
                self.investor.jianCang(date, buyRate)
                stock.showStockInfor()
                self.investor.showIvestorInfor()

            if selrate > riseThr and stock.stockHands > 0:
                self.investor.qingCang(date)
                stock.showStockInfor()
                self.investor.showIvestorInfor()

            # 短线
            '''
            if rate > riseThr:
                self.investor.sell(date, int(stock.stockHands * selRate))               
                self.updateLstSelPriList(self.continuousSelTimes, stock.curPrice, int(investor.moneyfromSell//stock.curPrice//100))
                 
                self.lstProPri = stock.curPrice
                investor.showIvestorInfor()
                stock.showStockInfor()
                self.showMarkInfor()
                 
            if rate < fallThr:
                investor.buy(date, investor.freeMoney * buyRate)
                self.updateLstBuyPriList(self.continuousBuyTimes, stock.curPrice, int(investor.money2Buy//stock.curPrice//100))
                 
                self.lstProPri = stock.curPrice
                investor.showIvestorInfor()
                stock.showStockInfor()
                self.showMarkInfor()
            '''

    def showMarkInfor(self):
        print("lstThreeBuyPriAndHands:{}, lstThreeSelPriAndHands:{}".format(
            self.lstThreeBuyPriAndHands, self.lstThreeSelPriAndHands))
        print("continuousBuyTimes:{}, continuousSelTimes:{}".format(
            self.continuousBuyTimes, self.continuousSelTimes))
Example #19
0
    # build base world
    from indicators import Moving_Average, RSI
    from world import world_from_live
    w = world_from_live(
        basket,
        cash=10000,
        indicators=[Moving_Average(n=200),
                    Moving_Average(n=10),
                    RSI(2)])
    # get model
    from models import Mean_Reversion
    mr = Mean_Reversion('Mean Reversion', 200, 10, 2)
    # build investor
    from investor import Investor
    i = Investor(models=[mr], world=w, live=False)
    # set up backtest
    from backtest import Backtest
    b = Backtest(name='mean_reversion_backtest_000', investor=i, base_world=w)
    # show/export results
    b.do_backtest()
    b.export_history(path='backtests/')

    # --- workflow 4 ---

    # neural ODE model class / some other trainable model
    # that will allow us to good make use of the backtesting tools

    # --- workflow 5 ---

    # exporting, importing model
class FinancialDataUseCase:
    def __init__(self):
        self.accountant = Accountant()
        self.polygon = PolygonGateway(self.accountant)
        self.investor = Investor()
        # self._ticker_repo = TickerRepository()
        # self._financial_statement_repo = FinancialStatementRepository()
        # self._company_repo = CompanyRepository()

    def user_asks_for_evaluation_of_stock(self, security):
        financial_statements = self.polygon.get_polygon_financial_statement(
            security.name, security.limit)
        evaluation = self.investor.evaluate(financial_statements)
        return evaluation

    # def store_all_possible_ticker_symbols(self, pages=None):
    #     for page in range(0, pages):
    #         ticker_set = self.polygon.get_polygon_ticker_symbols(pages=page, perpage=50)
    #         print(page, len(ticker_set), ticker_set)
    #         self._ticker_repo.post_many(ticker_set)

    # def store_financial_statement(self, symbol=None):
    #     if not symbol:
    #         return None
    #     financial_statement = polygon.get_polygon_financial_statement(symbol=symbol)
    #     return self._financial_statement_repo.post(financial_statement)

    # def _get_many_tickers(self, offset=None, limit=None):
    #     return self._ticker_repo.get_many(offset, limit)

    # def store_company_information_from_ticker_table(
    #     self, offset=0, limit=20, total=34277
    # ):
    #     offset = 9980
    #     while offset < total:
    #         print("the start:", offset)
    #         tickers = self._ticker_repo.get_many(offset=offset, limit=limit)
    #         company_details = []
    #         for ticker in tickers:
    #             company_detail = polygon.get_polygon_company_info(symbol=ticker.symbol)
    #             if company_detail:
    #                 company_details.append(company_detail)
    #         self._company_repo.post_many(company_details)
    #         offset += limit
    #     return

    # def store_financial_statement_from_ticker_table(
    #     self, offset=0, limit=100, total=34277
    # ):
    #     while offset < total:
    #         print("the start:", offset)
    #         tickers = self._ticker_repo.get_many(offset=offset, limit=limit)
    #         for ticker in tickers:
    #             fs_list = polygon.get_polygon_financial_statement(
    #                 symbol=ticker.symbol, limit=10
    #             )
    #             if fs_list:
    #                 self._financial_statement_repo.post_many(fs_list)
    #         offset += limit
    #         print(offset)
    #     return

    # def get_financial_statements(self, offset=0, limit=10):
    #     return self._financial_statement_repo.get(offset, limit)


# class TrackingUseCase:
#     def __init__(self):
#         self._alpaca_interface = AlpacaInterface()
#         self._polygon_interface = PolygonInterface()
#         watchlists = self._alpaca_interface.get_watchlists()
#         self.stocks_on_watchlists = []
#         for watchlist in watchlists:
#             watchlist_entity = self._alpaca_interface.get_watchlist(watchlist.id)
#             self.stocks_on_watchlists += watchlist_entity.assets

#     def _get_snapshot(self):
#         snapshot = self._polygon_interface.get_snapshot_of_tickers()

#         tickers = snapshot['tickers']

#         for stock in self.stocks_on_watchlists:
#             match = next((ticker for ticker in tickers if ticker['ticker'] == stock['symbol']), None)
#             print(match)

#     def _run_tracking_and_store_financial_data(self, wait_time_minutes):
#         tracking_job = Job(interval=timedelta(seconds=wait_time_minutes*60), execute=self._get_snapshot)
#         financial_statement_store_job = Job(interval=timedelta(seconds=1), execute=FinancialDataUseCase().store_financial_statement_from_ticker_table)
#         financial_statement_store_job.run()
#         tracking_job.run()

#         while True:
#             try:
#                 time.sleep(1)
#             except ProgramKilled:
#                 print("Program killed: running cleanup code")
#                 financial_statement_store_job.stop()
#                 break