Beispiel #1
0
 def get_interest_rate(self, date):
     #print(date)
     #print("Date type "+str(type(date.to_pydatetime())))
     #print(self.interest_rate_list[0].maturity)
     if hasattr(self, "interpolation"):
         return self.interpolation(utils.toTimestamp(date.to_pydatetime()))
     else:
         return 0
Beispiel #2
0
 def candle(self, ticker, field='Adj Close'):
     week_formatter = DateFormatter('%b %d')
     mondays = WeekdayLocator(MONDAY)
     data = self.DataReader(ticker)
     z = data.reset_index()
     fig, ax = plt.subplots()
     ax.xaxis.set_major_locator(mondays)
     ax.xaxis.set_major_formatter(week_formatter)
     z['date_num']=z['Date'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
     subset = [tuple(x) for x in z[['date_num', 'Open', 'High', 'Low', 'Close']].values]
     candlestick_ohlc(ax, subset, width=0.6, colorup='g', colordown='r')
Beispiel #3
0
 def candle(self, ticker, field='Adj Close'):
     week_formatter = DateFormatter('%b %d')
     mondays = WeekdayLocator(MONDAY)
     data = self.DataReader(ticker)
     z = data.reset_index()
     fig, ax = plt.subplots()
     ax.xaxis.set_major_locator(mondays)
     ax.xaxis.set_major_formatter(week_formatter)
     z['date_num'] = z['Date'].apply(
         lambda date: mdates.date2num(date.to_pydatetime()))
     subset = [
         tuple(x)
         for x in z[['date_num', 'Open', 'High', 'Low', 'Close']].values
     ]
     candlestick_ohlc(ax, subset, width=0.6, colorup='g', colordown='r')
def parse_ibkr_report_tradelog(path: Path) -> TradesSet:

    header_prefix = "Trades,Header,"
    data_prefix = "Trades,Data,Order,Stocks,"

    with path.open("r") as f:
        lines = f.readlines()

    columns = None
    data_lines = []
    for line in lines:
        line = line.strip()
        if line.startswith(header_prefix) and columns is None:
            # skip Order,Stocks columns on top of the prefix cols
            columns = line[len(header_prefix):].split(",")[2:]
        elif line.startswith(data_prefix):
            data_lines.append(line[len(data_prefix):])

    out: TradesSet = defaultdict(set)

    if not data_lines:
        return out

    df = pd.read_csv(StringIO("\n".join(data_lines)),
                     thousands=",",
                     header=None)
    df.columns = columns
    df = df[["Date/Time", "Symbol", "Quantity", "T. Price", "Comm/Fee"]]

    # the account management reports use eastern time natively
    # noinspection PyUnresolvedReferences
    df["Date/Time"] = pd.to_datetime(
        df["Date/Time"]).dt.tz_localize(TZ_EASTERN)

    for date, symbol, qty, price, comm in df.itertuples(index=False):

        if qty == 0:
            continue

        t = date.to_pydatetime()
        # if qty < 0, we lower price; else we increase.
        price -= comm / qty
        out[symbol].add(Trade(symbol, t, qty, price))

    return out
def download_single_day(date, path, overwrite):
    formatted_date = date.to_pydatetime().strftime('%m-%d-%Y')

    destination_file = path.joinpath(f'{formatted_date}.csv')

    if destination_file.exists() and not overwrite:
        logger.info(f'{formatted_date} -- already exists')
        return

    url = DATA_URL + f'{formatted_date}.csv'

    logger.info(f'{formatted_date} -- downloading file: {url}')
    response = requests.get(url)

    assert meets_expectations(response)

    with open(destination_file, 'w') as fh:
        fh.write(response.text)

    logger.info(f'{formatted_date} -- saved to {destination_file}')
Beispiel #6
0
    def grab_historical_prices(self,
                               start: datetime,
                               end: datetime,
                               bar: str = '1d',
                               symbols: Optional[List[str]] = None) -> dict:
        self._bar = bar

        new_prices = []

        if not symbols:
            symbols = self.portfolio.positions.keys()

        for symbol in symbols:
            historical_price_response = yf.download(
                symbol,
                start=start.strftime("%Y-%m-%d"),
                end=end.strftime("%Y-%m-%d"),
                group_by="ticker",
                interval=bar)
            historical_price_response_dict = historical_price_response.to_dict(
                orient='index')

            for date in historical_price_response_dict:
                new_price_mini_dict = {}
                new_price_mini_dict['symbol'] = symbol
                new_price_mini_dict['open'] = historical_price_response_dict[
                    date]['Open']
                new_price_mini_dict['close'] = historical_price_response_dict[
                    date]['Close']
                new_price_mini_dict['low'] = historical_price_response_dict[
                    date]['Low']
                new_price_mini_dict['high'] = historical_price_response_dict[
                    date]['High']
                new_price_mini_dict['volume'] = historical_price_response_dict[
                    date]['Volume']
                new_price_mini_dict['datetime'] = date.to_pydatetime()
                new_prices.append(new_price_mini_dict)

        self.historical_prices['aggregated'] = new_prices
        return self.historical_prices
Beispiel #7
0
#creates a copy of the dataMU for simpler graphing
dataMU2 = dataMU[1:100]
#creates a copy of myMU data
subset = myMU.copy()
#creates a date column setting to date from another DF instance
subset['Date'] = myMU.index
#moves the data index into its own column
subset.reset_index(inplace=True)
#drops the index named column
subset.drop(['index'], axis=1, inplace=True)

#creates new column, dateNum, as a number from date
subset['dateNum'] = pd.to_datetime(subset['Date'])
#creates a number from the date
subset['dateNum'] = subset['dateNum'].apply(
    lambda date: mdates.date2num(date.to_pydatetime()))

subsetAsTuples = [
    tuple(x) for x in subset[
        ['dateNum', '1. open', '2. high', '3. low', '4. close']].values
]

#graph based on months
from matplotlib.dates import DateFormatter
#monthFormatter = DateFormatter('%b %d')
import matplotlib.dates as mdates

yearFormatter = DateFormatter('%b %Y')

#months = mdates.MonthLocator()
years = mdates.YearLocator()