{"action":"published","release":{"url":"https://api.github.com/repos/SmithaShivakumar/ChiPyMentorship/releases/5035646","assets_url":"https://api.github.com/repos/SmithaShivakumar/ChiPyMentorship/releases/5035646/assets","upload_url":"https://uploads.github.com/repos/SmithaShivakumar/ChiPyMentorship/releases/5035646/assets{?name,label}","html_url":"https://github.com/SmithaShivakumar/ChiPyMentorship/releases/tag/v0.2","id":5035646,"tag_name":"v0.2","target_commitish":"master","name":"data flowing from yahoo finance","draft":false,"author":{"login":"SmithaShivakumar","id":12981723,"avatar_url":"https://avatars.githubusercontent.com/u/12981723?v=3","gravatar_id":"","url":"https://api.github.com/users/SmithaShivakumar","html_url":"https://github.com/SmithaShivakumar","followers_url":"https://api.github.com/users/SmithaShivakumar/followers","following_url":"https://api.github.com/users/SmithaShivakumar/following{/other_user}","gists_url":"https://api.github.com/users/SmithaShivakumar/gists{/gist_id}","starred_url":"https://api.github.com/users/SmithaShivakumar/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/SmithaShivakumar/subscriptions","organizations_url":"https://api.github.com/users/SmithaShivakumar/orgs","repos_url":"https://api.github.com/users/SmithaShivakumar/repos","events_url":"https://api.github.com/users/SmithaShivakumar/events{/privacy}","received_events_url":"https://api.github.com/users/SmithaShivakumar/received_events","type":"User","site_admin":false},"prerelease":true,"created_at":"2016-12-29T00:34:33Z","published_at":"2016-12-29T22:06:54Z","assets":[{"url":"https://api.github.com/repos/SmithaShivakumar/ChiPyMentorship/releases/assets/2901869","id":2901869,"name":"RiskFlipV0.2.py","label":null,"uploader":{"login":"SmithaShivakumar","id":12981723,"avatar_url":"https://avatars.githubusercontent.com/u/12981723?v=3","gravatar_id":"","url":"https://api.github.com/users/SmithaShivakumar","html_url":"https://github.com/SmithaShivakumar","followers_url":"https://api.github.com/users/SmithaShivakumar/followers","following_url":"https://api.github.com/users/SmithaShivakumar/following{/other_user}","gists_url":"https://api.github.com/users/SmithaShivakumar/gists{/gist_id}","starred_url":"https://api.github.com/users/SmithaShivakumar/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/SmithaShivakumar/subscriptions","organizations_url":"https://api.github.com/users/SmithaShivakumar/orgs","repos_url":"https://api.github.com/users/SmithaShivakumar/repos","events_url":"https://api.github.com/users/SmithaShivakumar/events{/privacy}","received_events_url":"https://api.github.com/users/SmithaShivakumar/received_events","type":"User","site_admin":false},"content_type":"text/plain","state":"uploaded","size":7010,"download_count":0,"created_at":"2016-12-29T22:06:46Z","updated_at":"2016-12-29T22:06:47Z","browser_download_url":"https://github.com/SmithaShivakumar/ChiPyMentorship/releases/download/v0.2/RiskFlipV0.2.py"}],"tarball_url":"https://api.github.com/repos/SmithaShivakumar/ChiPyMentorship/tarball/v0.2","zipball_url":"https://api.github.com/repos/SmithaShivakumar/ChiPyMentorship/zipball/v0.2","body":"\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime as dt\r\nimport pandas.io.data as web\r\nimport statsmodels.api as sm\r\n\r\n\r\n\r\nSTART = dt.datetime(2011,1,1)\r\nEND = dt.datetime(2016,12,31)\r\n\r\n#######################################################################################################\r\n\r\nfiles_dict = {0:'AAPL',\r\n              1:'CSCO',\r\n              2:'BAC',\r\n              3:'GOOGL',\r\n              4:'GS',\r\n              5:'JPM',\r\n              6:'MSFT',\r\n              7:'IBM',\r\n              8:'AMZN',\r\n              9:'GM',\r\n              10:'I am done with adding assets to my portfolio'}\r\n\r\n\r\n\r\n##########################################VALIDATIONS#################################################\r\n\r\ndef validate_asset_name(userInput,files_dict):\r\n    try:\r\n        val = int(userInput)\r\n    except ValueError:\r\n        return False\r\n    if (val in files_dict):\r\n        assetname = files_dict[val] \r\n        return True\r\n    else:\r\n        return False\r\n    \r\n    \r\ndef validate_num_shares(userInput):\r\n    try:\r\n        val = int(userInput)\r\n        if abs(val) == 0:  # if not a positive int print message and ask for input again\r\n            print(\"Sorry, input cannot be 0, try again!\")\r\n        else:\r\n            position = np.sign(val)\r\n            return True\r\n    except ValueError:\r\n        return False\r\n\r\n\r\n\r\ndef validate_hedge_pct(userInput):\r\n    try:\r\n        val = int(userInput)\r\n        if val < 0:  # if not a positive int print message and ask for input again\r\n            print(\"Sorry, input cannot be negative, try again!\")\r\n        elif val > 100:\r\n            print(\"Sorry, input cannot be greater than 100%, try again!\")\r\n        else:\r\n            return True\r\n    except ValueError:\r\n        return False\r\n\r\n################################# ASSET ######################################################\r\n\r\nclass Asset(object):\r\n\r\n\r\n    def __init__(self,assetname):\r\n        self.assetname = assetname\r\n        self.data = self.pull_data_from_yahoo()\r\n        self.market_price = self.data['Adj Close'][-1]\r\n        self.returns = self.returns_data()\r\n\r\n\r\n    def pull_data_from_yahoo(self):\r\n        symbol = self.assetname\r\n        data = web.get_data_yahoo(symbol, start=START, end=END)\r\n        # import pdb; pdb.set_trace()\r\n        # print(data)\r\n        return (data)\r\n\r\n\r\n\r\n    def returns_data(self):\r\n        self.data['returns'] = self.data['Adj Close'].shift(1)/self.data['Adj Close'] - 1\r\n        return self.data['returns']\r\n\r\n\r\n######################################## POSITION ################################################# \r\n\r\nclass Position(object):\r\n\r\n    def __init__(self, assetname, num_of_shares):\r\n        self.num_of_shares = num_of_shares\r\n        self.asset = Asset(assetname)\r\n        self.value = self.calc_market_value()\r\n\r\n    def calc_market_value(self):\r\n        price_of_asset = self.asset.market_price \r\n        value = self.num_of_shares * price_of_asset\r\n        return value\r\n\r\n    def create_position(self):\r\n        position = np.sign(num_of_shares)\r\n        return position\r\n\r\n########################################## PORTFOLIO ####################################################\r\n\r\nclass Portfolio(object):\r\n\r\n    def __init__(self):\r\n        self.positions = []\r\n\r\n    def add_position(self,asset_name,num_of_shares):\r\n        position = Position(asset_name,num_of_shares)\r\n        self.positions.append(position)\r\n\r\n    def market_val_portfolio(self):\r\n        total_market_value = 0\r\n        for position in self.positions:\r\n            total_market_value += position.value\r\n        return total_market_value\r\n\r\n\r\n\r\n    def get_hedge(self):\r\n\r\n        percentage_position = 0\r\n        total_returns = 0\r\n        \r\n         \r\n        for position in self.positions:\r\n            percentage_position = position.value/self.market_val_portfolio()\r\n            total_returns += position.asset.returns * (percentage_position)\r\n\r\n\r\n        spy_data = web.get_data_yahoo('SPY', start=START, end=END)#pd.read_csv(r'C:\\Users\\smitha\\Documents\\Python_Scripts\\chipy\\chipydata\\SPY.csv')\r\n        spy_returns = spy_data['Adj Close'].shift(1)/spy_data['Adj Close'] - 1\r\n        \r\n        total_returns.dropna(inplace=True)\r\n        spy_returns.dropna(inplace=True)\r\n        spy_returns.corr(total_returns, method='pearson', min_periods=None)\r\n        total_returns = sm.add_constant(total_returns)\r\n        # print(total_returns)\r\n        \r\n        model = sm.OLS(spy_returns,total_returns).fit()\r\n\r\n        beta = model.params[1]\r\n        print(\"You have {} percent of Beta exposure\".format(beta*100))\r\n        # print(model.summary())\r\n        hedge_pct = get_capital_hedge()\r\n        # import pdb; pdb.set_trace()\r\n        num_futures = np.round((beta* self.market_val_portfolio() * (int(hedge_pct)/100))/(spy_data['Adj Close'][-1]))\r\n        \r\n        return num_futures\r\n\r\n\r\n################################### GETTING USER INPUTS ###############################################\r\n\r\ndef get_capital_hedge():\r\n\r\n    print(\"\\n\\nWhat percentage of capital and the Beta exposure do you want to hedge?\")\r\n    hedge_pct = input()\r\n    while not validate_hedge_pct(hedge_pct):\r\n        print(\"Please input a valid integer!\")\r\n        hedge_pct = input()\r\n\r\n    return hedge_pct \r\n\r\n\r\n\r\ndef get_position_from_user():\r\n    \r\n    asset_dict = files_dict \r\n\r\n    print(\"\\nPlease select an asset from our dictionary of assets\")\r\n    for key, val in asset_dict.items():\r\n        print(\"{key}: {val}\".format(key=key, val=val))\r\n    asset_name = input()\r\n    while not validate_asset_name(asset_name, asset_dict):\r\n        print(\"that is not a valid asset name!\")\r\n        print(\"Please try again\")\r\n        asset_name = input()\r\n        \r\n    assetnames = asset_dict[int(asset_name)]\r\n    if assetnames == \"I am done with adding assets to my portfolio\":\r\n        return (False, 0)\r\n\r\n    print(\"\\nHow many shares of the Asset do you want to invest in? (To Buy : positive number, To Sell : negative number)\")\r\n    asset_num_shares = input()\r\n    while not validate_num_shares(asset_num_shares):\r\n        print(\"Please input an integer!\")\r\n        asset_num_shares = input()\r\n        \r\n    return (assetnames, int(asset_num_shares))\r\n\r\n\r\n###################################################################################################\r\n######################################### UI RUN ##################################################\r\n###################################################################################################\r\n\r\n\r\ndef userinterface():\r\n\r\n    new_user = Portfolio()\r\n\r\n    asset_name, asset_num_shares = get_position_from_user()\r\n\r\n    while asset_name:\r\n        new_user.add_position(asset_name, asset_num_shares)\r\n        asset_name, asset_num_shares = get_position_from_user()\r\n\r\n    print(\"\\nYour Portfolio is worth: \", new_user.market_val_portfolio(), \"\\n\\n\")\r\n\r\n    hedge_units = new_user.get_hedge()\r\n    if hedge_units > 0:\r\n        print(\"\\nTo hedge you should buy {} shares of SPDR S&P 500 ETF\".format(hedge_units))\r\n    elif hedge_units < 0:\r\n        print(\"\\nTo hedge you should sell {} shares of SPDR S&P 500 ETF\".format(hedge_units))\r\n    else:\r\n        print(\"\\nYou are perfectly hedged! \")\r\n\r\n\r\nuserinterface()\r\n\r\n\r\n\r\n\r\n\r\n"}}
{"actor":{"display_login":"SmithaShivakumar"}}