def get_stock_buy_info(stock: Stock, start_date: str, end_date: str):
    sql_text = '''
                SELECT 
                       FIRST_SERVICE_NAME,
                       SECOND_SERVICE_NAME,
                       BRAND_NAME,
                       MODEL_NAME,
                       BALANCE,
                       ifnull(sum(s.number), 0) AS sale_number
                  FROM stock_info si
                  LEFT JOIN stock_detail sd on sd.stock_id = si.id
                  LEFT JOIN Sales s on s.id = sd.changed_id and sd.type in ({}, {},{})''' \
        .format(StockDetail.by_write_off(), StockDetail.by_negative(), StockDetail.by_bought())
    if start_date != end_date:
        sql_text += ''' AND s.sale_date BETWEEN '{}' AND '{}\''''.format(start_date, end_date)

    if stock.second_service_id():
        sql_text += ''' WHERE si.second_service_id = {}'''.format(stock.second_service_id())
    if stock.first_service_id():
        sql_text += ''' AND si.first_service_id = {}'''.format(stock.first_service_id())
    if stock.brand_name():
        sql_text += ''' AND si.brand_name like '%{}%\''''.format(stock.brand_name())
    if stock.model_name():
        sql_text += ''' AND si.model_name like '%{}%\''''.format(stock.model_name())

    sql_text += ''' GROUP BY FIRST_SERVICE_NAME,
                       SECOND_SERVICE_NAME,
                       BRAND_NAME,
                       MODEL_NAME,
                       BALANCE '''
    result = execute(sql_text)
    return result
    def test_value_should_return_the_weighted_stock_amount_for_all_stocks_in_the_wallet(self):
        # Given
        rate_provider = Mock()
        rate_provider.rate.side_effect = [89, 7000]

        # When
        wallet_value = Wallet([Stock(10, PETROLEUM), Stock(2, BITCOIN)]).value(EUR, rate_provider)

        # Then
        self.assertEqual(wallet_value, Amount(14890, EUR))
        rate_provider.rate.assert_has_calls(
            [
                call(PETROLEUM, EUR),
                call(BITCOIN, EUR)
            ])
    def export_stock_data(self, fileformat="xls"):
        """Retrieve a user's options data and save as JSON and transposed requested file format.

        Args:
            fileformat (string): Requested file format to export data to, default XLS.
        """
        order_history = self.get_order_history()
        self.rhApihelper.save_to_json_file(order_history, "orders")

        stockTranData = tablib.Dataset(title="Transactions")
        stockTranData.headers = ['Ticker', 'Name', 'Date', 'Quantity', 'Price', 'TranType', 'Fees', 'Total']

        stockDict = {}

        for order_entry in order_history:
            if order_entry["state"] not in ["cancelled", "confirmed", "rejected"]:
                order_entry_instrument = self.rhApihelper.api_get(order_entry["instrument"])

                stock = Stock()
                stock.name = order_entry_instrument["simple_name"]
                stock.ticker = order_entry_instrument["symbol"]
                stock.fees = order_entry["fees"]
                stock.price = order_entry["average_price"]
                stock.totalPrice = order_entry["executed_notional"]["amount"]
                stock.quantity = order_entry["cumulative_quantity"]
                stock.date = order_entry["executions"][0]["settlement_date"]
                stock.tranType = order_entry["side"]

                stockTranData.append([stock.ticker, stock.name, stock.date, stock.quantity, stock.price, stock.tranType, stock.fees, stock.totalPrice])

                # Group the stocks into dictionary for further processing.
                if order_entry_instrument["symbol"] not in stockDict:
                    stockDict[stock.ticker] = [stock]
                else:
                    stockDict[stock.ticker].append(stock)

        stockSummaryData = self.create_summary(stockDict)

        stockExcelBook = tablib.Databook((stockTranData, stockSummaryData))

        self.rhApihelper.save_dataset_to_excel(
            "stockdata",
            fileformat,
            stockExcelBook
        )
    def test_value_should_return_the_stock_amount(self):
        # Given
        rate_provider = Mock()
        rate_provider.rate.return_value = 80

        # When
        wallet_value = Wallet([Stock(1, PETROLEUM)]).value(EUR, rate_provider)

        # Then
        self.assertEqual(wallet_value, Amount(80, EUR))
    def test_something(self):
        # Given
        rate_provider = FixedRateProvider()

        # When
        value = Wallet([Stock(5, PETROLEUM)]).value(EUR, rate_provider)
        rate = 5 * rate_provider.rate(PETROLEUM, EUR)

        # Then
        self.assertEqual(value, Amount(rate, EUR))
Exemple #6
0
    def search(self):
        start_date = self.start_date.date().toString('yyyy-MM-dd')
        end_date = self.end_date.date().toString('yyyy-MM-dd')
        brand_name = self.brand.text()
        model_name = self.model.text()

        first_srv_id = self.first_srv_combo.currentData()
        second_srv_id = self.second_srv_combo.currentData()

        stock = Stock()

        stock.brand_name(brand_name)
        stock.model_name(model_name)
        stock.first_service_id(first_srv_id)
        stock.second_service_id(second_srv_id)

        record = stock_handler.get_stock_buy_info(stock, start_date, end_date)
        table_utils.set_table_content_with_merge(self.tableView, record, self.table_title, 0)
        self.tableView.resizeColumnsToContents()
    def test_value_should_return_the_weighted_stock_amount_using_the_rate_and_stock_volume(self):
        # Given
        rate_provider = Mock()
        rate_provider.rate.return_value = 7500

        # When
        wallet_value = Wallet([Stock(2, BITCOIN)]).value(USD, rate_provider)

        # Then
        self.assertEqual(wallet_value, Amount(15000, USD))
        rate_provider.rate.assert_called_once_with(BITCOIN, USD)
    def test_value_should_return_the_stock_amount_using_the_rate_provider(self):
        # Given
        rate_provider = Mock()
        rate_provider.rate.return_value = 78

        # When
        wallet_value = Wallet([Stock(1, PETROLEUM)]).value(USD, rate_provider)

        # Then
        self.assertEqual(wallet_value, Amount(78, USD))
        rate_provider.rate.assert_called_once_with(PETROLEUM, USD)
Exemple #9
0
def add_stock_info(model, brand, model_id, brand_id, unit, second_service_id):
    second_service = service_handler.get_service_by_id(second_service_id)

    stock_info = Stock()

    stock_info.model_id(model_id).model_name(model)
    stock_info.brand_id(brand_id).brand_name(brand)
    stock_info.first_service_id(second_service['father_id']).first_service_name(second_service['father_name'])
    stock_info.second_service_id(second_service_id).second_service_name(second_service['name'])
    stock_info.unit(unit)
    stock_info.name(brand + '-' + model)
    stock_info.create_op(config.login_user_info[0]).create_time(time_utils.get_now())

    stock_id = stock_handler.add_stock_info(stock_info)
    stock_info.id(stock_id)
    return stock_info
Exemple #10
0
    def _submit(self):
        stock = Stock()

        brand = self.brand_comboBox
        stock.brand_name(brand.currentText()).brand_id(brand.currentData())

        model = self.model_combo_box
        stock.model_name(model.currentText()).model_id(model.currentData())

        first_service = self.first_service_combo_box
        stock.first_service_id(first_service.currentData()).first_service_name(
            first_service.currentText())

        second_service = self.second_service_combo_box
        stock.second_service_name(
            second_service.currentText()).second_service_id(
                second_service.currentData())

        name = brand.currentText() + '-' + model.currentText()
        stock.name(name)
        stock.unit(self.unit.text())
        stock.create_op(common.config.login_user_info[0])
        stock.create_time(get_now())

        stock_id = stock_handler.add_stock_info(stock)

        stock.id(stock_id)
Exemple #11
0
def add_stock_info(stock: Stock):
    sql_text = '''
                INSERT INTO stock_info(
                                        UNIT,
                                        first_service_name,
                                        first_service_id,
                                        model_id,
                                        model_name,
                                        brand_id,
                                        brand_name,
                                        name,
                                        second_service_id,
                                        second_service_name,
                                        balance,
                                        total_cost,
                                        create_time,
                                        create_op
                                        )
                VALUES(
                        '{}',
                        '{}',
                         {},
                         {},
                        '{}',
                         {},
                        '{}',
                        '{}',
                         {},
                        '{}',
                         {},
                        {:.2f},
                        '{}',
                        {}                    
                )''' \
        .format(stock.unit(), stock.first_service_name(), stock.first_service_id(), stock.model_id(),
                stock.model_name(), stock.brand_id(), stock.brand_name(), stock.name(), stock.second_service_id(),
                stock.second_service_name(), stock.balance(), stock.total_cost(), stock.create_time(),
                stock.create_op())
    new_stock_id = execute(sql_text)

    return new_stock_id
Exemple #12
0
https://junpyopark.github.io/MACD_Plotting/


참고자료
http://blog.naver.com/anthouse28/221410326641
https://www.facebook.com/pg/TheAlphaSquare/photos/?tab=album&album_id=1229946413826362
"""

import pandas as pd
from domain.stock import Stock
from datetime import datetime

start = datetime(2018, 1, 1)
end = datetime(2019, 12, 31)
name = '삼성전자'
stock = Stock()
data = stock.get_stock(name, start, end)

print(data.head())
index = data.index.astype('str')
print("Period from ", index[0], " To ", index[-1])
print(list(data.columns.values))
# 5일 이동평균선과 20일 이동평균선을 계산하여 저장합니다.
ma5 = data['Close'].rolling(window=5).mean()
ma20 = data['Close'].rolling(window=20).mean()

# https://www.facebook.com/pg/TheAlphaSquare/photos/?tab=album&album_id=1229946413826362
# MACD 계산 공식 참조


# Exponential Moving Average : 지수이동평균
Exemple #13
0
def get_stock(code, start=None, end=None):
    return Stock().get_stock_from_fdr(code, start, end)
Exemple #14
0
def get_korea_stock_list():
    return Stock().get_stock_code_kr()
Exemple #15
0
def get_kospi_list():
    return Stock().get_stock_code_kospi()
Exemple #16
0
    def _add_stock_info(self, model, brand, model_id, brand_id, line_number, total, number, unit):
        service_id = getattr(self, 'service_' + line_number).currentData()
        service_name = getattr(self, 'service_' + line_number).currentText()
        stock_info = Stock()

        services = service_name.split('-')
        service_ids = service_id.split('-')

        first_service_id = int(service_ids[0])
        first_service_name = services[0]
        second_service_id = int(service_ids[1])
        second_service_name = services[1]

        stock_info.model_id(model_id).model_name(model)
        stock_info.brand_id(brand_id).brand_name(brand)
        stock_info.first_service_id(first_service_id).first_service_name(first_service_name)
        stock_info.second_service_id(second_service_id).second_service_name(second_service_name)
        stock_info.unit(unit).name(brand + '-' + model)
        stock_info.create_op(config.login_user_info[0]).create_time(time_utils.get_now())
        stock_info.total_cost(total).balance(number)

        stock_id = stock_handler.add_stock_info(stock_info)

        return stock_id