def get_portfolios(client, acc_names) -> [Portfolio]:
    portfolios = list()
    for acc in acc_names.keys():
        portfolio = Portfolio(acc, acc_names[acc])
        portfolio.df = get_df(client, acc)
        portfolios.append(portfolio)
    return portfolios
Exemple #2
0
def snapshot(save=True):
    stocks = polling()
    from models import Portfolio
    portfolio = Portfolio(stocks)
    if save:
        portfolio.save()
    return portfolio
Exemple #3
0
def check_user(view):
    c_user = users.get_current_user()
    if c_user:
        log = users.create_logout_url(url_for('index'))
    else:
        if view[0] in ('security'):
            log = users.create_login_url(url_for(view[0], pos=view[1]))
        elif view[0] in ('sec_info', 'edit_security'):
            log = users.create_login_url(url_for(view[0], pos=view[1], sec_id=view[2]))
        else:
            log = users.create_login_url(url_for(view[0]))
    
    # Create a new portfolio if new user
    if c_user:
        ptfs = Portfolio.query(Portfolio.user == c_user)
        ptfs = list(ptfs)
        if len(ptfs) == 0:
            ptf = Portfolio(
                user = c_user,
                points = START_POINTS
            )
            ptf.put()
            ptf_id = ptf.key.id()
            flash(u'Portfolio %s successfully created.' % ptf_id, 'success')
    
    return [c_user, log]
def snapshot(save=True):
    stocks = polling()
    from models import Portfolio
    portfolio = Portfolio(stocks)
    if save:
        portfolio.save()
    return portfolio
Exemple #5
0
def crypto_tokens():
    """ Crypto currency tokens """
    try:
        with open('crypto.csv', 'rb') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            positions = [Position(symbol=row[0], quantity=row[1]) 
                for row in reader]

            return Portfolio(positions)

    except IOError:
        return Portfolio()
Exemple #6
0
    def __init__(self, scenario: str):
        if scenario not in self.SCENARIOS:
            raise NotImplementedError(
                f'Unknown scenario {scenario}. Choose from: {sorted(self.SCENARIOS)}'
            )

        self.scenario = scenario
        self.data_dir = os.path.join(settings.SIMULATION_DIR, scenario)
        self.portfolio = Portfolio.read_from_file(
            os.path.join(self.data_dir, 'start.csv'))
        self.reference_portfolio = Portfolio.read_from_file(
            os.path.join(self.data_dir, 'start.csv'))
Exemple #7
0
def portfolio(portfolio_id):
    """Message of /port_*id* command"""
    port = Portfolio(portfolio_id)
    if port.count_papers() > 0:
        message = 'Your papers\n'
        port.current_prices()
        for paper in port.papers:
            message += f'{paper}\n' \
                       f'{paper.change()} {paper.currency} ({paper.percent()}%) \n' \
                       f'{paper.market()}\n\n'
        return message
    else:
        return "No papers"
Exemple #8
0
def portfolio():
    """ Stock market portfolio """

    try:
        with open('portfolio.csv', 'rb') as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            positions = [Position(symbol=row[0], quantity=row[2]) 
                for row in reader ]

            return Portfolio(positions)

    except IOError as err:
        return Portfolio()
Exemple #9
0
def picture_get(site, host, netloc, site_id, user_id, portfolio_id,
                picture_id):
    """
    Get portfolio url
    """

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id,
                                  Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Picture
    try:
        picture = Picture.get(Picture.id == picture_id, Picture.site == site,
                              Picture.portfolio == portfolio)
    except Picture.DoesNotExist:
        return dict(status=False, info='Imagem não encontrada')

    # Images data
    site_img_url = '%s/%s/' % (host, IMAGE_DIR)
    original_url = site_img_url + picture.original_image
    normalized_url = site_img_url + picture.normalized_image
    thumbnail_url = site_img_url + picture.thumbnail_image

    # Return OK
    return dict(status=True,
                info='Imagem encontrada com sucesso',
                original=original_url,
                normalized=normalized_url,
                thumbnail=thumbnail_url,
                **picture.get_dictionary())
Exemple #10
0
def add_user():
    name = request.form['username']
    psw = request.form['passw']
    con_psw = request.form['conf_pass']

    user_with_that_name = User.query.filter_by(username=name).count()
    if user_with_that_name > 0:
        flash("That name is already in use, come up with another", "negative")
        return render_template('sign-up-form.html')
    elif len(psw) < 6 or len(psw) > 20:
        flash("Passwords must be at least 6 chars long, 20 at most.",
              "negative")
        return render_template('sign-up-form.html', username=name)
    elif psw != con_psw:
        flash("Passwords didn't match!!", "negative")
        return render_template('sign-up-form.html', username=name)
    else:
        new_user = User(name, psw)
        db.session.add(new_user)
        db.session.commit()
        # need to do this AFTER new_user commited so id is generated
        new_user_portfolio = Portfolio(holder_id=new_user.id)
        #start a schedule for user's updates (jobs) to be added to
        skedge_start_with_check()
        db.session.add(new_user_portfolio)
        db.session.commit()
        session['username'] = new_user.username
        flash("Logged IN!", "positive")
        return render_template('edit.html', username=session['username'])
 def test_total_expected_earnings(self):
     position_1 = Position(stock=Stock('ticker', 'name', 20, 30),
                           quantity=2)
     position_2 = Position(stock=Stock('ticker', 'name', 20, 40),
                           quantity=2)
     portfolio = Portfolio(position_1, position_2)
     self.assertEqual(Decimal('1.5'), portfolio.total_expected_earnings)
Exemple #12
0
    def test_parse_recon_text(self):
        test_recon_text = """D0-POS
            AAPL 100
            GOOG 200
            SP500 175.75
            Cash 1000

            D1-TRN
            AAPL SELL 100 30000
            GOOG BUY 10 10000
            Cash DEPOSIT 0 1000
            Cash FEE 0 50
            GOOG DIVIDEND 0 50
            TD BUY 100 10000

            D1-POS
            GOOG 220
            SP500 175.75
            Cash 20000
            MSFT 10"""
        positions, transactions = recon.parse_portfolio_text(test_recon_text)

        self.assertEqual(2, len(positions))
        self.assertEqual(1, len(transactions))

        test_prtf = Portfolio.from_positions(positions[0])
        self.assertDictEqual({
            'AAPL': 100,
            'GOOG': 200,
            'SP500': 175.75
        }, test_prtf.positions)
        self.assertEqual(1000, test_prtf.cash)
Exemple #13
0
    def create_portfolio(payload):

        body = request.get_json()
        portfolio_name = body.get('portfolio_name', None)
        portfolio_compositions = body.get('portfolio_compositions', None)

        # check if portfolio compositions sum up to 100 %
        total_weight = 0
        for portfolio_composition in portfolio_compositions:
            total_weight += portfolio_composition['weight']
        if total_weight != 100:
            abort(422)

        portfolio = Portfolio(name=portfolio_name)

        for portfolio_composition in portfolio_compositions:
            composition = PortfolioComposition(
                security_id=portfolio_composition['security_id'],
                weight=portfolio_composition['weight'])
            composition.portfolio = portfolio
            composition.insert()

        return jsonify({
            'success': True,
            'portfolio_id': portfolio.id,
            'portfolio_name': portfolio.name,
        })
Exemple #14
0
def add_portfolio():
    if request.method == 'POST':
        portfolio = session.query(Portfolio).all()
        target = os.path.join(app.config['BASE_DIR'], 'static/image')

        if not os.path.isdir(target):
            os.mkdir(target)

        for file in request.files.getlist("image"):
            filename = file.filename
            destination = "/".join([target, filename])
            image = '../static/image/' + filename
            file.save(destination)

        # Creating a books object to add to the databse.
        image = '../static/image/' + request.form['image']
        port = Portfolio(title=request.form['title'],
                         skills_used=request.form['skills_used'],
                         demo_url=request.form['demo_url'],
                         github_url=request.form['github_url'],
                         description=request.form['description'],
                         client=request.form['client'],
                         created_month=request.form['created_month'],
                         created_year=request.form['created_year'],
                         service=request.form['service'],
                         image=image)
        session.add(port)
        session.commit()
        return redirect(url_for('portfolio.portfolio'))
    else:
        return render_template('modifyPortfolio.html', type='add')
Exemple #15
0
 def get(self):
     portfolios = Portfolio.query().fetch()
     self.tv["portfolios"] = []
     for this_data in portfolios:
         self.tv["portfolios"].append(this_data.to_object())
     self.tv["current_page"] = "EDIT PORTFOLIO"
     self.render('frontend/portfolio-edit.html')
Exemple #16
0
 def get(self):
     portfolios = Portfolio.query().fetch()
     self.tv["portfolios"] = []
     for this_data in portfolios:
         self.tv["portfolios"].append(this_data.to_object())
     self.tv["current_page"] = "EDIT PORTFOLIO"
     self.render('frontend/portfolio-edit.html')
Exemple #17
0
def picture_get(site, host, netloc, site_id, user_id, portfolio_id, picture_id):
    """
    Get portfolio url
    """

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Picture
    try:
        picture = Picture.get(Picture.id == picture_id, Picture.site == site, Picture.portfolio == portfolio)
    except Picture.DoesNotExist:
        return dict(status=False, info='Imagem não encontrada')

    # Images data
    site_img_url = '%s/%s/' % (host, IMAGE_DIR)
    original_url = site_img_url + picture.original_image
    normalized_url = site_img_url + picture.normalized_image
    thumbnail_url = site_img_url + picture.thumbnail_image

    # Return OK
    return dict(status=True,
                info='Imagem encontrada com sucesso',
                original=original_url,
                normalized=normalized_url,
                thumbnail=thumbnail_url,
                **picture.get_dictionary())
Exemple #18
0
def portfolio_update(site, host, netloc, csrf, logged_in, user_id_logged_in):
    """
    Edit portfolio post url
    """

    # POST parameters
    site_id = int(request.POST.get('site'))
    user_id = int(request.POST.get('user'))
    portfolio_id = int(request.POST.get('portfolio'))
    title = request.POST.get('title')
    description = request.POST.get('description')

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id,
                                  Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Update upload portfolio image
    if request.files.get('upload'):
        img_path = site.get_image_path(IMAGE_PATH)
        original_file = os.path.join(img_path, portfolio.original_image)
        normalized_file = os.path.join(img_path, portfolio.normalized_image)
        thumbnail_file = os.path.join(img_path, portfolio.thumbnail_image)
        upload_response = upload_image(request, original_file, normalized_file,
                                       thumbnail_file, ORIG_SIZE, NORM_SIZE,
                                       THUMB_SIZE)
        if not upload_response['status']:
            return upload_response

    # Upload data
    portfolio.title = title
    portfolio.description = description
    portfolio.save()

    # Images data
    img_url = '%s/%s/' % (host, IMAGE_DIR)
    original_url = img_url + portfolio.original_image
    normalized_url = img_url + portfolio.normalized_image
    thumbnail_url = img_url + portfolio.thumbnail_image

    # Lista de portfolios atualizada
    try:
        portfolio_list = template('portfolios_admin_list.html',
                                  site=site,
                                  host=host,
                                  csrf=csrf,
                                  img_url=img_url)
    except Exception as exp:
        return dict(status=False, info='%s' % exp)

    # Return OK
    return dict(status=True,
                info='Atualizado com sucesso',
                portfolio_id=portfolio.get_id(),
                original=original_url,
                normalized=normalized_url,
                thumbnail=thumbnail_url,
                portfolio_list=portfolio_list)
 def mutate(self, info, user_data=None):
     # NOTE: Netlify creates the account regardless of this response
     portfolio = Portfolio()
     settings = Settings()
     metrics = UserMetrics()
     try:
         user = User.objects.get(pk=user_data.email)
         # If no query error, then either the user exists or
         # user variable becomes None. In both cases the response fails.
         return CreateUserMutation(user=None, success=False)
     except Exception as e:  # email not taken
         if "matching query does not exist" not in str(e):
             # unexpected error during query
             return CreateUserMutation(user=None, success=False)
         user = User(name=user_data.name,
                     bio=user_data.bio,
                     email=user_data.email,
                     password=user_data.password,
                     profile_pic=user_data.profile_pic,
                     metrics=metrics,
                     achievements=[],
                     personal_portfolio=portfolio,
                     groups=[],
                     settings=settings)
         checkAchievements(user)
         user.save()
         return CreateUserMutation(user=user, success=True)
Exemple #20
0
def portfolio():
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,
                                range=RANGE).execute()
    values = result.get('values', [])

    positions = [
        Position(symbol=row[0], quantity=float(scrub(row[2])))
        for row in values if len(row) > 1
    ]

    return Portfolio(positions)
Exemple #21
0
 def update_portfolio_model(self, portfolio):
     with create_session() as session:
         portfolio_model = Portfolio(btc_value=portfolio)
         account_model = session.query(ExchangeAccount).filter_by(
             id=self.account_model_id).first()
         account_model.portfolio.append(portfolio_model)
         session.add(account_model)
         session.commit()
def init_db():
    art = [
        Artwork(title="Street Art", description="A true masterpiece", location=[7,80]),
        Artwork(title="Hidden Subway Mural", description="Far side of the subway station has a double walled mural.", location=[10,132]),
        Artwork(title="Blue Bridge", description="Neon blue tentacles of paint wind up the struts of the bridge", location=[0,0], tags=["amazing"]),
        Artwork(title="Artistic Underpass", description="Bridge ceiling covered in art", location=[0,0], tags=["surreal", "amazing"]),
        Artwork(title="Fire Wall", description="Tongues of flame comemorate the historic fire of this district", tags=["sad", "historic", "amazing"], location=[0,0]),
        Artwork(title="Street Corner Fresco", description="This popular street has a decorative fresco spilling out of the alley behind a popular restaurant", tags=["amazing", "unreal"], location=[0,0])
    ]

    for a in art:
        a.save()

    portfolios = [
        Portfolio(artworks=[art[0], art[1]]),
        Portfolio(artworks=[art[2], art[4]]),
        Portfolio(artworks=[art[1], art[2], art[3]]),
        Portfolio(artworks=[art[3], art[5]]),
    ]
    for p in portfolios:
        p.save()

    users = [
        User(name="Grant", portfolio=portfolios[0], bio="Love me some AI and maybe web dev."),
        User(name="Braden", portfolio=portfolios[1], bio="Spending some time on CSC 400."),
        User(name="Kyle", portfolio=portfolios[2], bio="Fitness, meditation and good books."),
        User(name="John", portfolio=portfolios[3], bio="Looking around for some art. Wasn't satisfied with my dope Windows Vista wallpaper.")
    ]
    for user in users:
        user.save()

    achievements = [
        Achievement(title="Noob", description="You signed up for the service!", points=10)
    ]
    for a in achievements:
        a.save()

    for user in users:
        user.achievements.append(achievements[0])
    for user, portfolio in zip(users, portfolios):
        portfolio.owner = user

    
    for portfolio in portfolios:
        portfolio.save()
Exemple #23
0
def picture_update(site, host, netloc, csrf, logged_in, user_id_logged_in):
    """
    Edit picture post url
    """

    # POST parameters
    site_id = int(request.POST.get('site'))
    user_id = int(request.POST.get('user'))
    portfolio_id = int(request.POST.get('portfolio'))
    picture_id = int(request.POST.get('picture'))
    title = request.POST.get('title')
    description = request.POST.get('description')

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Picture
    try:
        picture = Picture.get(Picture.id == picture_id, Picture.site == site, Picture.portfolio == portfolio)
    except Picture.DoesNotExist:
        return dict(status=False, info='Imagem não encontrada')

    # Update upload picture image
    if request.files.get('upload'):
        img_path = site.get_image_path(IMAGE_PATH)
        original_file = os.path.join(img_path, picture.original_image)
        normalized_file = os.path.join(img_path, picture.normalized_image)
        thumbnail_file = os.path.join(img_path, picture.thumbnail_image)
        upload_response = upload_image(request, original_file, normalized_file, thumbnail_file, ORIG_SIZE, NORM_SIZE, THUMB_SIZE)
        if not upload_response['status']:
            return upload_response

    # Upload data
    picture.title = title
    picture.description = description
    picture.save()

    # Images data
    img_url = '%s/%s/' % (host, IMAGE_DIR)
    original_url = img_url + picture.original_image
    normalized_url = img_url + picture.normalized_image
    thumbnail_url = img_url + picture.thumbnail_image

    # Lista de pictures atualizada
    try:
        picture_list = template('pictures_admin_list.html', site=site, host=host, csrf=csrf,
                                portfolio=portfolio, img_url=img_url)
    except Exception as exp:
        return dict(status=False, info='%s' % exp)

    # Return OK
    return dict(status=True, info='Atualizada com sucesso', picture_id=picture.get_id(),
                original=original_url, normalized=normalized_url, thumbnail=thumbnail_url,
                picture_list=picture_list)
Exemple #24
0
def buy(request):
    if not request.session.get('id'):
        return redirect('login')

    if request.method == 'POST':
        if not request.POST.get('symbol'):
            return apology('Symbol field cannot be empty')
        if not request.POST.get('quantity'):
            return apology('Quantity field cannot be empty')

        symbol = request.POST.get('symbol').upper()
        quantity = int(request.POST.get('quantity'))
        stock_info = lookup(symbol)
        if not stock_info:
            return apology("No such symbol exists")

        user_info = Users.objects.filter(id=request.session.get('id'))
        if not user_info:
            return apology("Your session is invalid")

        available_cash = user_info[0].cash
        if available_cash >= quantity * stock_info.get('price'):
            user_portfolio = Portfolio.objects.filter(
                id=request.session.get('id')).filter(symbol=symbol)
            if user_portfolio:
                user_portfolio[0].price += stock_info.get('price') * quantity
                user_portfolio[0].quantity += quantity
                user_portfolio[0].save()
            else:
                user_portfolio = Portfolio(
                    id=request.session.get('id'),
                    symbol=symbol,
                    price=stock_info.get('price') * quantity,
                    quantity=quantity,
                    stock_name=stock_info.get('name'),
                )
                user_portfolio.save()
            user_info[0].cash -= quantity * stock_info.get('price') * quantity
            user_info[0].save()
            return redirect('index')
        else:
            return apology("You do not have enough cash")
    else:
        return render(request, 'app/buy.html')
Exemple #25
0
    def get(self):
        if self.user:
            self.redirect(self.uri_for('www-dashboard-admin'))
            return
        portfolios = Portfolio.query().fetch()
        self.tv["portfolios"] = []
        for this_data in portfolios:
            self.tv["portfolios"].append(this_data.to_object())

        self.tv["current_page"] = "PORTFOLIO"
        self.render('frontend/portfolio.html')
Exemple #26
0
    def get(self):
        if self.user:
            self.redirect(self.uri_for('www-dashboard-admin'))
            return
        portfolios = Portfolio.query().fetch()
        self.tv["portfolios"] = []
        for this_data in portfolios:
            self.tv["portfolios"].append(this_data.to_object())

        self.tv["current_page"] = "PORTFOLIO"
        self.render('frontend/portfolio.html')
Exemple #27
0
def register(request):
    uname = request.POST["username"]
    passw = request.POST["password"]

    if request.POST["username"] == "" or request.POST["password"] == "":
        return render_to_response('index.html',
            {'error': 'You did not fill out the form completely'})
    
    if User.objects.filter(username = request.POST["username"]).count() != 0:
        return render_to_response('index.html',
            {'error':  'There is already a user with this username'})
    
    User.objects.create_user(uname, '', passw)
    u = auth.authenticate(username=uname, password=passw)
    auth.login(request, u)
    
    p = Portfolio(user = u, balance = 10000, value = 0)
    
    p.save()
    
    return HttpResponseRedirect('/')
 def _calculate_ideal_portfolio(self, input_filename: str,
                                reference_filename: str):
     input_file = os.path.join(settings.TEST_DIR, input_filename)
     reference_file = os.path.join(settings.TEST_DIR, reference_filename)
     generated_file = os.path.join(settings.TMP_DIR, reference_filename)
     portfolio = Portfolio.read_from_file(input_file)
     calculator = Calculator(portfolio)
     calculator.calculate_ideal_portfolio()
     portfolio.write_to_file(generated_file)
     self.compare_file_with_file(generated_file,
                                 reference_file,
                                 write_first=True)
     os.remove(generated_file)
Exemple #29
0
def portfolio_alloc(raw_data, candidate_list, candidate_pick_num,
                    user_selectFund, user_selectFund_weights,
                    extraPortfolio_ratio, ivt_loop_num):

    minimum_weight = 0.1
    candidate_combs = list(combinations(candidate_list, candidate_pick_num))
    weight_alloc_combs = weight_alloc(candidate_pick_num,
                                      (1 - extraPortfolio_ratio) * 100, 3, 3)

    new_weight_alloc_combs = []
    for weight_comb in weight_alloc_combs:
        if min(weight_comb) > minimum_weight:
            new_weight_alloc_combs.append(weight_comb)

    # print(new_weight_alloc_combs)

    portfolio_alloc_list = []
    if len(new_weight_alloc_combs) > 0:
        for candidate_comb in candidate_combs:
            # print(candidate_comb)
            for weight_alloc_comb in new_weight_alloc_combs:
                new_return_list = []
                weight_alloc_comb_perms = set(
                    list(permutations(weight_alloc_comb)))
                for weight_alloc_comb_perm in weight_alloc_comb_perms:
                    final_candidate_comb = candidate_comb + tuple(
                        user_selectFund)
                    final_weight_alloc_comb_perm = weight_alloc_comb_perm + tuple(
                        user_selectFund_weights)
                    new_return_list = newFund_return(
                        raw_data, final_candidate_comb,
                        final_weight_alloc_comb_perm)

                    q = index_q(new_return_list, ivt_loop_num)
                    portfolio_alloc_list.append([
                        q, final_candidate_comb, final_weight_alloc_comb_perm
                    ])

    # check no recommend
    if len(portfolio_alloc_list) == 0:
        return None

    temp_min = min(portfolio_alloc_list)

    co_risk = cal_co_risk(temp_min[1], temp_min[2], raw_data, "downside")
    co_return = cal_co_return(temp_min[1], temp_min[2], raw_data)
    # print(co_risk,co_return)
    min_portfolio = Portfolio(temp_min[0], temp_min[1], temp_min[2],
                              co_return / co_risk)

    return min_portfolio
Exemple #30
0
def reconcile(initial_positions_day=0,
              compare_to_day=1,
              in_file='./data/recon.in',
              out_file='./data/recon.out'):
    '''
    Main entry point for positional reconciliation. 
    Parses command line arguments for which days to compare. Transactions will be 
    accounted for all days between the dates being compared
    Writes diff to outfile in format specified
    '''

    log.debug('Reading file {}'.format(in_file))
    with open(in_file, 'r') as f:
        text = f.read()

    positions, transactions = parse_portfolio_text(text)
    log.debug('Parsed positions and transactions text')
    initial_portfolio = Portfolio.from_positions(
        positions[initial_positions_day])
    log.debug('Initial portfolio: {}'.format(initial_portfolio))
    latest_prtf_state = Portfolio.from_positions(positions[compare_to_day])
    log.debug('Compare to portfolio: {}'.format(latest_prtf_state))

    for day_idx in range(initial_positions_day, compare_to_day + 1):
        if day_idx in transactions:
            for trn in transactions[day_idx]:
                initial_portfolio.process_transaction(trn)

    log.debug('Portfolio after processing transactions: {}'.format(
        initial_portfolio))
    prtf_diff = initial_portfolio.reconcile(latest_prtf_state)

    log.debug('Reconciliation diff: {}'.format(prtf_diff))

    with open(out_file, 'w') as f:
        for ticker, diff in prtf_diff.items():
            f.write('{} {}\n'.format(ticker, diff))
    log.debug('Wrote outfile {}'.format(args.out_file))
Exemple #31
0
def generate_demo_csv():
    position_a = Position(quantity=2,
                          ticker='AA',
                          name='A & A',
                          current_value=20,
                          expected_value=30)
    position_b = Position(quantity=3,
                          ticker='BB',
                          name='B & B',
                          current_value=30,
                          expected_value=40)
    position_c = Position(quantity=4,
                          ticker='CC',
                          name='C & C',
                          current_value=40,
                          expected_value=50)
    position_d = Position(quantity=5,
                          ticker='DD',
                          name='D & D',
                          current_value=50,
                          expected_value=60)
    portfolio = Portfolio(position_a, position_b, position_c, position_d)
    portfolio.write_to_file(os.path.join(PORTFOLIO_DIR, 'demo.csv'))
    def mutate(self, info, group_data=None):
        user = UpdateUserMutation.getUser(group_data.member_to_add)
        group_portfolio = Portfolio()
        group = Group(name=group_data.name,
                      bio=group_data.bio,
                      members=[user],
                      metrics=GroupMetrics(artwork_count=0, member_count=1),
                      group_portfolio=group_portfolio,
                      chat=[])
        group.save()
        user.groups.append(group)
        user.save()

        return CreateGroupMutation(group=group)
Exemple #33
0
def picture_delete(site, host, netloc, csrf, logged_in, user_id_logged_in):
    """
    Delete picture post url
    """

    # POST parameters
    site_id = int(request.POST.get('site'))
    user_id = int(request.POST.get('user'))
    portfolio_id = int(request.POST.get('portfolio'))
    picture_id = int(request.POST.get('picture'))

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id,
                                  Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Picture
    try:
        picture = Picture.get(Picture.id == picture_id, Picture.site == site,
                              Picture.portfolio == portfolio)
    except Picture.DoesNotExist:
        return dict(status=False, info='Imagem não encontrada')

    # Delete picture
    site_img_path = site.get_image_path(IMAGE_PATH)
    picture.delete_all(site_img_path)

    # Images url
    img_url = '%s/%s/' % (host, IMAGE_DIR)

    # Lista de pictures atualizada
    try:
        picture_list = template('pictures_admin_list.html',
                                site=site,
                                host=host,
                                csrf=csrf,
                                portfolio=portfolio,
                                img_url=img_url)
    except Exception as exp:
        return dict(status=False, info='%s' % exp)

    # Return OK
    return dict(status=True,
                info='Apagado com sucesso',
                picture_id=picture_id,
                picture_list=picture_list)
Exemple #34
0
def pictures_admin_page(site, host, netloc, csrf, logged_in, user_id_logged_in, site_id, user_id, portfolio_id):
    """
    Admin picutes url
    """

    try:
        # Portfolio
        portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site)

        # Images url
        img_url = '%s/%s/' % (host, IMAGE_DIR)

        # Call template
        return dict(host=host, site=site, csrf=csrf, logged_in=logged_in, user_id_logged_in=user_id_logged_in,
                    portfolio=portfolio, img_url=img_url)
    except Portfolio.DoesNotExist:
        abort(404, 'Portfólio não encontrado')
Exemple #35
0
    def post(self):
        print('Adding new Portfolio')
        #app.logger.info(f'Received : {request.json}')
        #app.logger.info(f'Received : {request.get_json()}')

        # find the user id from JWT token
        logged_user_id = get_jwt_identity()
        new_portfolio = Portfolio(
            id=request.json["id"],
            portfolio_title=request.json["portfolio_title"],
            portfolio_desc=request.json["portfolio_desc"],
            date_created=request.json["date_created"],
            date_updated=request.json["date_updated"],
            user_id=logged_user_id  #request.json["user_id"]
        )

        db.session.add(new_portfolio)
        db.session.commit()

        return stockschema.dump([new_portfolio])
Exemple #36
0
    def save_portfolio(self, portfolio, name, date):
        #NOTE ndict annoying stuff
        session = self.manager.db.Session()

        # Cleaning
        session.execute(
            "delete from Positions where Positions.PortfolioName = '{}'".
            format(name))
        #session.execute("delete from Portfolios where Portfolios.Name = '{}'".format(name))

        pf_object = Portfolio(name=name,
                              date=date.strftime(format='%Y-%m-%d %H:%M'),
                              startdate=portfolio.start_date,
                              cash=portfolio.cash,
                              startingcash=portfolio.starting_cash,
                              returns=portfolio.returns,
                              capital=portfolio.capital_used,
                              pnl=portfolio.pnl,
                              portvalue=portfolio.portfolio_value,
                              posvalue=portfolio.positions_value)

        positions = json.loads(
            str(portfolio.positions).replace('Position(',
                                             '').replace(')',
                                                         '').replace("'", '"'))
        assert isinstance(positions, dict)
        #FIXME In remote mode with lot of portfolios: make it crash !
        for ticker in positions:
            positions[ticker]['name'] = name
            positions[ticker]['date'] = date
            session.add(Position(**positions[ticker]))
            #NOTE bug: 'not list-like object', but not an issue ?
            #pf_object.Positions = Position(**positions[ticker])
            #name=name,
            #ticker='pouet',
            #amount=0,
            #last_sale_price=0,
            #cost_basis=0)
        session.add(pf_object)
        session.commit()
        session.close()
Exemple #37
0
def get_stock_values(portfolio):
    query = {
        'symbols': ",".join(portfolio.tickers),
        'types': 'quote,news,chart',
        'range': '1m',
        'last': 5
    }

    url = HOSTNAME +\
    '/stock/market/batch?' +\
    query_s(query)

    resp = requests.get(url)
    params = resp.json()

    return Portfolio([
        Position(symbol=vals['quote']['symbol'],
                 price=vals["quote"]["latestPrice"],
                 quantity=portfolio[ticker].quantity)
        for ticker, vals in params.iteritems()
    ])
Exemple #38
0
def picture_delete(site, host, netloc, csrf, logged_in, user_id_logged_in):
    """
    Delete picture post url
    """

    # POST parameters
    site_id = int(request.POST.get('site'))
    user_id = int(request.POST.get('user'))
    portfolio_id = int(request.POST.get('portfolio'))
    picture_id = int(request.POST.get('picture'))

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Picture
    try:
        picture = Picture.get(Picture.id == picture_id, Picture.site == site, Picture.portfolio == portfolio)
    except Picture.DoesNotExist:
        return dict(status=False, info='Imagem não encontrada')

    # Delete picture
    site_img_path = site.get_image_path(IMAGE_PATH)
    picture.delete_all(site_img_path)

    # Images url
    img_url = '%s/%s/' % (host, IMAGE_DIR)

    # Lista de pictures atualizada
    try:
        picture_list = template('pictures_admin_list.html', site=site, host=host, csrf=csrf,
                                portfolio=portfolio, img_url=img_url)
    except Exception as exp:
        return dict(status=False, info='%s' % exp)

    # Return OK
    return dict(status=True, info='Apagado com sucesso', picture_id=picture_id, picture_list=picture_list)
Exemple #39
0
    def update_account_portfolio(self):
        with create_session() as session:
            timestamp = datetime.utcnow()
            account = session.query(AccountModel).filter_by(
                api_key=self.api_key).first()
            if not account:
                raise ValueError("account not found")
            assets = account.my_assets
            portfolio_in_eth = get_portfolio_in_eth(assets)
            default_quotes = portfolio_in_eth['default_quotes']
            quote_dict = {}
            for default_quote in default_quotes:
                quote_dict[default_quote['symbol']] = default_quote['price']
            for asset_portfolio in portfolio_in_eth['portfolio']:
                asset = [
                    asset for asset in assets
                    if asset.name == asset_portfolio['symbol']
                ]
                if asset:
                    asset = asset[0]
                    asset.eth_value = asset_portfolio['eth_cost']
                    asset.quote_price = asset_portfolio['price']
                    asset.pair_name = asset_portfolio['pair_name']
                    asset.timestamp = timestamp  #last time the asset eth value was update
                    session.add(asset)

                    port = Portfolio(account=account,
                                     asset=asset,
                                     asset_name=asset.name,
                                     total_value=asset.free + asset.fixed,
                                     eth_value=asset_portfolio['eth_cost'],
                                     quote_price=asset_portfolio['price'],
                                     pair_name=asset_portfolio['pair_name'],
                                     timestamp=timestamp,
                                     eth_btc_quote=quote_dict['ETHBTC'],
                                     bnb_eth_quote=quote_dict['BNBETH'],
                                     eth_usdt_quote=quote_dict['ETHUSDT'])
                    session.add(port)
            session.commit()
Exemple #40
0
 def post(self):
     newPortfolio = Portfolio()
     newPortfolio.title = self.request.get("title")
     newPortfolio.description = self.request.get("description")
     newPortfolio.put()
     self.render('frontend/portfolio-createlist.html')
Exemple #41
0
def picture_add(site, host, netloc, csrf, logged_in, user_id_logged_in):
    """
    Add picture post url
    """

    # POST parameters
    site_id = int(request.POST.get('site'))
    user_id = int(request.POST.get('user'))
    portfolio_id = int(request.POST.get('portfolio'))
    title = request.POST.get('title')
    description = request.POST.get('description')

    # Portfolio
    try:
        portfolio = Portfolio.get(Portfolio.id == portfolio_id, Portfolio.site == site)
    except Portfolio.DoesNotExist:
        return dict(status=False, info='Portfólio não encontrado')

    # Upload picture image
    start_index = 1
    try:
        pictures = site.pictures.order_by(Picture.id.desc())
        last_picture = pictures.get()
        start_index = last_picture.id + 1
    except Picture.DoesNotExist:
        pass
    img_path = site.get_image_path(IMAGE_PATH)
    img_url = '%s/%s/' % (host, IMAGE_DIR)
    upload_response = upload_new_image(request, 'picture', start_index, img_path, img_url, ORIG_SIZE, NORM_SIZE, THUMB_SIZE)
    if not upload_response['status']:
        return upload_response

    # Upload data
    original_image = upload_response['original_filename']
    normalized_image = upload_response['normalized_filename']
    thumbnail_image = upload_response['thumbnail_filename']
    original_url = upload_response['original_url']
    normalized_url = upload_response['normalized_url']
    thumbnail_url = upload_response['thumbnail_url']

    # Create Picture
    picture_created = None
    with db.transaction():
        try:
            picture_created = Picture.create(site=site,
                                             portfolio=portfolio,
                                             title=title,
                                             description=description,
                                             original_image=original_image,
                                             normalized_image=normalized_image,
                                             thumbnail_image=thumbnail_image)
        except IntegrityError as exp:
            if picture_created:
                picture_created.delete_instance(IMAGE_PATH)
            else:
                site_img_path = site.get_image_path(IMAGE_PATH)
                if original_image:
                    original_file = os.path.join(site_img_path, original_image)
                    if os.path.exists(original_file):
                        os.remove(original_file)
                if normalized_image:
                    normalized_file = os.path.join(site_img_path, normalized_image)
                    if os.path.exists(normalized_file):
                        os.remove(normalized_file)
                if thumbnail_image:
                    thumbnail_file = os.path.join(site_img_path, thumbnail_image)
                    if os.path.exists(thumbnail_file):
                        os.remove(thumbnail_file)
            # Return error
            return dict(status=False, info='%s' % exp)

    # Lista de pictures atualizada
    try:
        picture_list = template('pictures_admin_list.html', site=site, host=host, csrf=csrf,
                                portfolio=portfolio, img_url=img_url)
    except Exception as exp:
        return dict(status=False, info='%s' % exp)

    # Return OK
    return dict(status=True, info='Adicionada com sucesso', picture_id=picture_created.get_id(),
                original=original_url, normalized=normalized_url, thumbnail=thumbnail_url,
                picture_list=picture_list)
Exemple #42
0
 def mokarPortfolio(self):
     iDescricao1= 'GitHub'
     iPortfolio1= Portfolio(descricao= iDescricao1)
     iPortfolio1.save()
     
     iDescricao2= 'LinkedIn'
     iPortfolio2= Portfolio(descricao= iDescricao2)
     iPortfolio2.save()
     
     iDescricao3= 'CoderWall'
     iPortfolio3= Portfolio(descricao= iDescricao3)
     iPortfolio3.save()
     
     iDescricao4= 'SitePessoal'
     iPortfolio4= Portfolio(descricao= iDescricao4)
     iPortfolio4.save()
     
     iDescricao5= 'SiteEmpresa'
     iPortfolio5= Portfolio(descricao= iDescricao5)
     iPortfolio5.save()
Exemple #43
0
 def delete(self):
     portfolio_id = self.request.get("this_id")
     portfolio_id = Portfolio.get_by_id(int(portfolio_id))
     portfolio_id.key.delete()
Exemple #44
0
def match_orders(sec, buysell):
    """Match orders in cross"""
    # Get buy and sell lists
    b = Order.query(Order.security == sec, Order.buysell == 'Buy', Order.active == True, ancestor=sec.key).order(-Order.price, Order.timestamp)
    s = Order.query(Order.security == sec, Order.buysell == 'Sell', Order.active == True, ancestor=sec.key).order(Order.price, Order.timestamp)
    b = list(b)
    s = list(s)
    
    # Match orders until market uncrosses
    bn = 0
    sn = 0
    while(1):
        if bn + 1 > len(b):
            break
        if sn + 1 > len(s):
            break
        if b[bn].price >= s[sn].price:
            t = Trade()
            t.timestamp = datetime.utcnow()
            t.buy_user = b[bn].user
            t.sell_user = s[sn].user
            t.security = b[bn].security
            if buysell == "Buy":
                t.price = s[sn].price
            else:
                t.price = b[bn].price
            b[bn] = b[bn].key.get()
            s[sn] = s[sn].key.get()
            b_ptf = Portfolio.query(Portfolio.user == b[bn].user).get()
            s_ptf = Portfolio.query(Portfolio.user == s[sn].user).get()
            if b[bn].volume > s[sn].volume:
                t.volume = s[sn].volume
                b[bn].volume += -s[sn].volume
                s[sn].active = False
                b_ptf.points += s[sn].volume
                s_ptf.points += s[sn].volume
                b[bn].put()
                s[sn].put()
                sn += 1
            elif b[bn].volume < s[sn].volume:
                t.volume = b[bn].volume
                s[sn].volume += -b[bn].volume
                b[bn].active = False
                b_ptf.points += b[bn].volume
                s_ptf.points += b[bn].volume
                b[bn].put()
                s[sn].put()
                bn += 1
            elif b[bn].volume == s[sn].volume:
                t.volume = b[bn].volume
                b[bn].active = False
                s[sn].active = False
                b_ptf.points += b[bn].volume
                s_ptf.points += b[bn].volume
                b[bn].put()
                s[sn].put()
                bn += 1
                sn += 1
            b_ptf.put()
            s_ptf.put()
            t.put()
            flash(u'Trade %s successfully completed.' % t.key.id(), 'success')
            continue
        break