def download_historic_prices(trades):
    # Get symbols of all stocks traded
    symbols = trades.Symbol.unique().tolist()

    for symbol in symbols:
        symbol_trades = trades.loc[trades['Symbol'] == symbol]

        start_date = symbol_trades['Date'].min().strftime("%Y-%m-%d")
        # TODO: Fetch last traded date, if all sold, otherwise today's date
        today = datetime.date.today().strftime("%Y-%m-%d")

        # Download the historic prices from Yahoo Finance
        # TODO: Handle dates when stock isn't traded on the first of the month
        prices = yf.Ticker(symbol).history(start=start_date,
                                           end=today,
                                           interval="1mo")[['Close']]

        # Drop all corporate actions (for simplicity). Later we can separate these out into
        # their own files and use them to calculate portfolio performance
        prices = prices.dropna()

        # If historic prices exist, write them to a CSV file
        if not prices.empty:
            output_file = file.make_path(symbol)
            prices.to_csv(output_file)
def read_trades_csv():
    """Read in the trades csv and store it in a dataframe"""
    path = file.make_path('trades', '')

    # Read data in from csv file
    # Google Finance has some weird special character in the column name for 'Symbol'
    col_names = [
        'Date', 'Symbol', 'Type', 'Currency', 'Shares', 'Price', 'Commission'
    ]
    df = pd.read_csv(path, parse_dates=['Date'], names=col_names, header=0)

    # Drop rows where any column is empty
    df = df.dropna(axis=0)

    return df
Esempio n. 3
0
def construct_forex_dataframe(currencies, dates):
    df = pd.DataFrame(index=dates)

    for currency in currencies:
        if currency == BASE_CURRENCY:
            df[currency] = 1
            continue

        path = file.make_path(currency + BASE_CURRENCY, 'forex')
        dfForex = pd.read_csv(path,
                              index_col='Date',
                              names=['Date', currency],
                              header=0,
                              parse_dates=True)

        df = df.join(dfForex)

    return df
Esempio n. 4
0
def read_historical_csv(symbol):
    path = file.make_path(symbol)

    # Read data in from csv file
    try:
        df = pd.read_csv(path,
                         index_col='Date',
                         parse_dates=True,
                         usecols=['Date', 'Close'],
                         na_values=['nan'])

    # If there are any data errors, just print an error and skip this stock
    except ValueError as err:
        print('Failed to read data for: ' + symbol, err)
        return None
    except FileNotFoundError as err:
        print(f'No pricing data for: {symbol}. Skipping this stock.')
        return None

    # Rename close column to symbol name
    df = df.rename(columns={'Close': symbol})

    return df
def download_forex(trades):
    # Get the currencies of all stocks traded
    currencies = trades.Currency.unique().tolist()

    for currency in currencies:
        # No need to fetch the base currency (no conversion needed)
        if currency == BASE_CURRENCY:
            continue

        currency_trades = trades.loc[trades['Currency'] == currency]

        start_date = currency_trades['Date'].min().strftime("%Y-%m-%d")
        # TODO: Fetch last traded date if all sold, otherwise today's date
        today = datetime.date.today().strftime("%Y-%m-%d")

        # Download the Forex prices with the base currency from Yahoo Finance
        # TODO: Handle dates when forex isn't traded on the first of the month
        forex = yf.Ticker(currency + BASE_CURRENCY + '=X').history(
            start=start_date, end=today, interval="1mo")[['Close']]

        # If historic prices exist, write them to a CSV file
        output_file = file.make_path(currency + BASE_CURRENCY, 'forex')
        forex.to_csv(output_file)
def write_to_file(content, ticker_symbol):
    path = file.make_path(ticker_symbol)
    with open(path, 'wb') as handle:
        for block in content.iter_content(1024):
            handle.write(block)
def write_to_file(content, ticker):
    path = file.make_path(ticker)
    with open(path, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        for row in content:
            writer.writerow(row)