Created
January 14, 2021 15:11
-
-
Save dhenry/ace9b3bc35531da4d2c71a599e2430a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import robin_stocks as r | |
from datetime import datetime | |
import pandas as pd | |
import pprint | |
import webbrowser | |
import os | |
def currency_format(x): | |
return "${:.2f}".format(x) | |
def open_orders_df(open_options): | |
values = [] | |
profits = [] | |
tickers = [] | |
expirations = [] | |
costs = [] | |
_credits = [] | |
types =[] | |
for option in open_options: | |
ticker = option['chain_symbol'] | |
market_data = r.get_option_market_data_by_id(option['option_id']) | |
instrument_data = r.get_option_instrument_data_by_id(option['option_id']) | |
value = float(market_data[0]['mark_price']) * float(option['quantity']) * 100 | |
if option['type'] == 'short': | |
credit = -(float(option['average_price']) * float(option['quantity'])) | |
cost = 0.0 | |
profit = credit - value | |
type = 'short' | |
else: | |
credit = 0.0 | |
cost = (float(option['average_price']) * float(option['quantity'])) | |
profit = value - cost | |
type = 'long' | |
date = datetime.strptime(instrument_data['sellout_datetime'], '%Y-%m-%dT%H:%M:%S%z').date() | |
tickers.append(ticker) | |
costs.append(cost) | |
_credits.append(credit) | |
values.append(value) | |
profits.append(profit) | |
expirations.append(date) | |
types.append(type) | |
df = pd.DataFrame() | |
df['Ticker'] = tickers | |
df['Cost'] = costs | |
df['Credit'] = _credits | |
df['Value'] = values | |
df['Profit'] = profits | |
df['Type'] = types | |
df['Expiration'] = expirations | |
df.loc['Total'] = df.sum(numeric_only=True) | |
df.sort_values('Expiration', inplace=True) | |
return df | |
def all_orders_df(market_options): | |
tickers = [] | |
costs = [] | |
_credits = [] | |
dates = [] | |
for option in market_options: | |
ticker = option['chain_symbol'] | |
if option['direction'] == 'debit': | |
cost = float(option['processed_premium']) | |
credit = 0.0 | |
else: | |
cost = 0.0 | |
credit = float(option['processed_premium']) | |
date = datetime.strptime(option['updated_at'], '%Y-%m-%dT%H:%M:%S.%fZ').date() | |
tickers.append(ticker) | |
dates.append(date) | |
costs.append(cost) | |
_credits.append(credit) | |
df = pd.DataFrame() | |
df['Ticker'] = tickers | |
df['Cost'] = costs | |
df['Credit'] = _credits | |
df['Date'] = dates | |
df.loc['Total'] = df.sum(numeric_only=True) | |
df.sort_values('Date', inplace=True, ascending=False) | |
return df | |
def fetch_options_data(): | |
# !!! Fill out username and password | |
username = '' | |
password = '' | |
# !!! | |
login = r.login(username, password) | |
market_options = list(filter(lambda x: x['state'] != 'cancelled', r.get_market_options())) | |
open_options = r.get_open_option_positions() | |
open_df = open_orders_df(open_options) | |
all_df = all_orders_df(market_options) | |
total_value = open_df.iloc[-1]['Value'] | |
total_profit = open_df.iloc[-1]['Profit'] | |
total_cost = all_df.iloc[-1]['Cost'] | |
total_credit = all_df.iloc[-1]['Credit'] | |
print() | |
print("Open contracts:") | |
print(open_df) | |
print() | |
print("All contracts:") | |
print(all_df) | |
print() | |
print("Total value of open contracts is ${:.2f}".format(total_value)) | |
print("Total profit of open contracts is ${:.2f}".format(total_profit)) | |
print("Total P/L from closed contracts is ${:.2f}".format(total_credit - total_cost)) | |
print("Total P/L if I close all open contracts today: ${:.2f}".format( | |
total_value + total_credit - total_cost)) | |
print() | |
# t = open_options[0] | |
# t2 = r.get_option_instrument_data_by_id('3f4a6c15-5b35-46c0-bf20-9a9f19a3fa5e') # 'option_id' | |
# t3 = r.get_option_market_data_by_id('3f4a6c15-5b35-46c0-bf20-9a9f19a3fa5e') | |
# pp = pprint.PrettyPrinter(width=41, compact=True) | |
# pp.pprint(t) | |
# pp.pprint(t2) | |
# pp.pprint(t3) | |
today = datetime.today() | |
filename = "options_{:s}.html".format(today.strftime("%m_%d_%y")) | |
with open(filename, "w") as f: | |
f.write("<p>Report generated: {:s}</p>".format(today.strftime("%B %d, %Y"))) | |
f.write("<p>Total value of open contracts: ${:.2f}</p>".format(total_value)) | |
f.write("<p>Total profit of open contracts: ${:.2f}</p>".format(total_profit)) | |
f.write("<p>Total P/L from closed contracts: ${:.2f}</p>".format(total_credit - total_cost)) | |
f.write("<p>Total P/L if I close all open contracts today: ${:.2f}</p>".format( | |
total_value + total_credit - total_cost)) | |
f.write("<p>Open contracts:</p>") | |
f.write(open_df.to_html()) | |
f.write("<p>All contracts:</p>") | |
f.write(all_df.to_html()) | |
webbrowser.open('file://' + os.path.realpath(filename)) | |
if __name__ == '__main__': | |
fetch_options_data() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment