File size: 7,764 Bytes
8689777
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62e92f6
8689777
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import json
import psycopg2
import streamlit as st
import openai
from decimal import Decimal

PINECONE_API_KEY = st.secrets["PINECONE_API_KEY"]
OPENAI_API_KEY = st.secrets["OPENAI_API_KEY"]
INDEX_NAME = 'realvest-data-v2'
EMBEDDING_MODEL = "text-embedding-ada-002"  # OpenAI's best embeddings as of Apr 2023
MAX_LENGTH_DESC = 200
MATCH_SCORE_THR = 0.0
TOP_K = 20

def net_operating(rent, tax_rate, price):
    
    #Takes input as monthly mortgage amount and monthly rental amount
    #Uses managment expense, amount for repairs, vacancy ratio
    #Example input: net_operating(1000,1,400,200)
    #879.33
    #1000 - 16.67 (tax) - 100 (managment) - 4 (repairs)
    
    mortgage_amt = mortgage_monthly(price,20,3)
    prop_managment = rent * 0.10
    prop_tax = (price * (tax_rate/100)/12)
    prop_repairs = (price * 0.02)/12
    vacancy = (rent*0.02)
    #These sections are a list of all the expenses used and formulas for each
    
    net_income = rent - prop_managment - prop_tax - prop_repairs - vacancy - mortgage_amt
    #Summing up expenses
    output = [prop_managment, prop_tax, prop_repairs, vacancy, net_income]
  
    
    return output

def down_payment(price,percent):
    #This function takes the price and the downpayment rate and returns the downpayment amount 
    #Ie down_payment(100,20) returns 20
    amt_down = price*(percent/100)
    return(amt_down)

def mortgage_monthly(price,years,percent):
    
    
    #This implements an approach to finding a monthly mortgage amount from the purchase price,
    #years and percent. 
    #Sample input: (300000,20,4) = 2422
    #
    
    
    percent = percent /100
    down = down_payment(price,20)
    loan = price - down
    months = years*12
    interest_monthly = percent/12
    interest_plus = interest_monthly + 1
    exponent = (interest_plus)**(-1*months)
    subtract = 1 - exponent
    division = interest_monthly / subtract
    payment = division * loan
    
    
    return(payment)

#to do
def price_mine(pid):
    #Currently this function takes an input of a URL and returns the listing prices 
    #The site it mines is remax
    #The input must be a string input, we can reformat the input to force this to work
    #Next we use regex to remove space and commas and dollar signs
    #need to get from a product id to a price
    prices = 0
    prices = float(prices)
  
    return prices
    
    
def cap_rate(monthly_income, price):
    #This function takes net income, and price and calculates the cap rate
    #
    cap_rate = ((monthly_income*12) / price)*100
    
    return cap_rate


def cash_on_cash(monthly_income, down_payment):
    cash_return = ((monthly_income*12)/down_payment)*100
    return cash_return



def query_postgresql(
    query: str, 
    database: str, 
    user: str, 
    password: str, 
    host: str,
    port: str,
    named_columns: bool=True
    ):
    
    conn = psycopg2.connect(
            database=database,
            user=user,
            password=password,
            host=host,
            port=port
        )
    
    cur = conn.cursor()
    cur.execute(query)
    rows = cur.fetchall()

    if named_columns:
        column_names = [desc[0] for desc in cur.description]
        return [ dict(zip(column_names, r)) for r in rows ]

    return rows

def query_postgresql_realvest(query: str, named_columns: bool=True):
    import streamlit as st
    POSTGRESQL_REALVEST_USER = st.secrets["POSTGRESQL_REALVEST_USER"]
    POSTGRESQL_REALVEST_PSWD = st.secrets["POSTGRESQL_REALVEST_PSWD"]

    return query_postgresql(
        query, 
        database="realvest", 
        user=POSTGRESQL_REALVEST_USER, 
        password=POSTGRESQL_REALVEST_PSWD, 
        host="realvest.cdb5lmqrlgu5.us-east-2.rds.amazonaws.com",
        port="5432",
        named_columns=named_columns
        )

def summarize_products(products: str) -> str:
    """
    Input:
    products = [
        {text information of product#1},
        {text information of product#2},
        {text information of product#3},
    ]

    Output:
    summary = "{summary of all products}"
    """
    NEW_LINE = '\n'
    prompt = f"""
    You are a highly experienced commercial asset investor. You are writing an investement analysis report based on the data provided. You tends to be critical as your goal is to sift through and to identify promising oppurtunities.  Try to use the following instructions to write it. 
    For Executive Summary: 
    Brief overview of the property, location, asking price, and the potential investment opportunity.
    Property Description: Detailed description of the property, including number of units, age of the building, renovations, amenities, and other notable features. 
    
    for Demographics Analysis: based on the location, come up with basic population, income, age, crime, tax, traffic information. 
    
    for Market Analysis: Detailed analysis of the local market, including demographics, competition, growth projections, and other relevant factors. Make sure to call out the specific category of the business and its typical range of multipliers. 
    
    for Financial Analysis: Detailed review of the property's financials, look into the finance_info and description, including the key metrics like CAP, COC, GRM, NIM, DCR, ER per Unit, Price per Unit, GOI, NOI, Total Debt Service, Cash Flow, ROI, IRR, Equity Buildup Rate, BER, and LTV. Each metric should be calculated and explained. Given the specific business category, provide the key metrics specific to this category.  Export in a format that is in a table. Most important information: cash flow, cap rate and EBITDA

    for Risk Assessment: Detailed analysis of potential risks, including economic, industry, and location-specific risks. Call out specific risks that are relevant to the property.

    for Follow up questions: come up with questions and to do list with contact info. 
    
    for Conclusion and Recommendation:  Final thoughts on the investment opportunity, including whether it meets your investment criteria and objectives.
    
    Here is the input data in JSON format, try to parse out the metrics and location information, if the data is not include, try to use your own knoweldge and expertise to fill in.
    
    
    {products}
    
    
    Please write a insightful summary (display as Markup) and try your best to fill in data and what you know with the following format:
    
    #Investment Sample Report: 

    ##Executive Summary: 
      
    ##Demographics Analysis: 
    
    ##Market Analysis: 
    
    ##Financial Analysis: 
    
    ##Risk Assessment: 

    ##Follow up questions: 
      
    ##Conclusion and Recommendation: 
    
    """
    #print(f"prompt: {prompt}")
    
    openai.api_key = OPENAI_API_KEY
    completion = openai.ChatCompletion.create(
        model="gpt-4",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": prompt}
        ]
    )

    summary = completion.choices[0].message
    return summary




if __name__ == "__main__":
    query = """
    select  productid, category, established_year name, alternatename, 
    offers,asking_price, cash_flow, finance_info, rent, listing_profile, description 
    from main_products 
    limit 1
    """
  
    results = query_postgresql_realvest(query)
    #loop through results and cancatenate each row into a json string
    
    
    # Assuming results are a list of tuples

    for row in results:
        print(row['productid'])
        str_data = ""
        str_data += json.dumps({k: str(v) if isinstance(v, Decimal) else v for k, v in row.items()})

        summary = ""
        summary = summarize_products(str_data)
        print(summary['content'])