# Generated by Django 3.0.6 on 2020-05-14 12:31
import os
from django.db import migrations
import pandas as pd
from datetime import datetime, date

path = r"C:\Users\adsk1\Documents\Coding portfolio\mysite\main\python\\"

os.chdir(path)

from main.python.generate_component_prices import import_FTSE_100_component_data
from main.python.generate_index_prices import import_FTSE_100
from main.python.generate_component_features import current_features

# Import data
ticker_list = pd.read_csv("ticker_list.csv")
current_df = pd.read_csv("current_features_FTSE_100.csv")
index_df = pd.read_csv("index_prices.csv")
historical_component_prices_df = pd.read_csv("component_prices.csv")
risk_df = pd.read_csv("risk_plots.csv")
stock_prices_html = pd.read_csv("stock_prices_html.csv")
current_df.dropna(subset = ['Ticker'],inplace = True)
index_prices_html = pd.read_csv("index_prices_html.csv")

print(current_df[current_df['Ticker']=='AAL']['Industry'].iloc[0])

os.chdir(r"C:\Users\adsk1\Documents\Coding portfolio\mysite")

from django.conf import settings

user = settings.DATABASES['default']['USER']
password = settings.DATABASES['default']['PASSWORD']
database_name = settings.DATABASES['default']['NAME']

database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format(
    user=user,
    password=password,
    database_name=database_name,
)


def ticker_data(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    
    ComponentFeatures = apps.get_model('main', 'ComponentFeatures')
    
    component_features = current_features()
    
    entries = []
    for e in component_features.T.to_dict().values():
        entries.append(ComponentFeatures(date = date.today(),
                                    ticker = e['Ticker'], 
                                    ticker_slug = e['Ticker'],
                                    industry = e['Industry'],
                                    market_cap = e['Market cap'],
                                    enterprise_value = e['Enterprise value'],
                                    trailing_PE = e['Trailing P/E'],
                                    forward_PE = e['Forward P/E'],
                                    PEG_ratio = e['PEG ratio (5-yr expected)'],
                                    price_sales = e['Price/sales'],
                                    price_book = e['Price/book'],
                                    enterprise_value_revenue = e['Enterprise value/revenue'],
                                    enterprise_value_EBITDA = e['Enterprise value/EBITDA'],
                                    profit_margin = e['Profit margin'],
                                    operating_margin = e['Operating margin'],
                                    return_on_assets = e['Return on assets'],
                                    return_on_equity = e['Return on equity'],
                                    revenue = e['Revenue'],
                                    revenue_per_share = e['Revenue per share'],
                                    quarterly_revenue_growth = e['Quarterly revenue growth'],
                                    gross_profit = e['Gross profit'],
                                    EBITDA = e['EBITDA'],
                                    net_income = e['Net income avi to common'],
                                    diluted_EPS = e['Diluted EPS'],
                                    quarterly_earnings_growth = e['Quarterly earnings growth'],
                                    total_cash = e['Total cash'],
                                    total_cash_per_share = e['Total cash per share'],
                                    total_debt = e['Total debt'],
                                    current_ratio = e['Current ratio'],
                                    book_value_per_share = e['Book value per share'],
                                    operating_cash_flow = e['Operating cash flow'],
                                    levered_free_cash_flow = e['Levered free cash flow']))
    
    ComponentFeatures.objects.bulk_create(entries)
        
def ticker_plot(apps, schema_editor):

    TickerPlot = apps.get_model('main', 'TickerPlot')
    
    for tick in stock_prices_html['Ticker']:
    
        object = TickerPlot(ticker = tick,
                            candlestick_html = stock_prices_html[stock_prices_html["Ticker"]==tick]["Candlestick html"].iloc[0],
                            MACD_html = stock_prices_html[stock_prices_html["Ticker"]==tick]["MACD html"].iloc[0],
                            RSI_html = stock_prices_html[stock_prices_html["Ticker"]==tick]["RSI html"].iloc[0],
                            stock_html = stock_prices_html[stock_prices_html["Ticker"]==tick]["Stock price html"].iloc[0])
                        
        object.save()
        
        
        
def index_plot(apps, schema_editor):

    IndexPlot = apps.get_model('main', 'IndexPlot')
    
    object = IndexPlot(index = "FTSE 100",
                        candlestick_html = index_prices_html["Candlestick html"].iloc[0],
                        SMA_html = index_prices_html["SMA html"].iloc[0],
                        MACD_html = index_prices_html["MACD html"].iloc[0],
                        RSI_html = index_prices_html["RSI html"].iloc[0],
                        stock_html = index_prices_html["Stock price html"].iloc[0])
                            
    object.save()
    print(object.RSI_html)
    
    
def component_prices(apps, schema_editor):

    ComponentPrices = apps.get_model('main', 'ComponentPrices')
    
    component_prices_df = import_FTSE_100_component_data()
    
    entries = []
    for e in component_prices_df.T.to_dict().values():
        entries.append(ComponentPrices(date = e['Date'],
                                       open = e['Open'],
                                       high = e['High'],
                                       low = e['Low'],
                                       close = e['Close'],
                                       adj_close = e['Adj Close'],
                                       volume = e['Volume'],
                                       ticker = e['Ticker']))
        
    ComponentPrices.objects.bulk_create(entries)


def index_prices(apps, schema_editor):

    IndexPrices = apps.get_model('main', 'IndexPrices')
    
    index_prices_df = import_FTSE_100()
    
    entries = []
    for e in index_prices_df.T.to_dict().values():
        entries.append(IndexPrices(date = e['Date'],
                                       open = e['Open'],
                                       high = e['High'],
                                       low = e['Low'],
                                       close = e['Close'],
                                       adj_close = e['Adj Close'],
                                       volume = e['Volume']))
    
    IndexPrices.objects.bulk_create(entries)
#def component_features(apps, schema_editor):

#    ComponentFeatures = apps.get_model('main', 'ComponentFeatures')

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(ticker_data),
        migrations.RunPython(ticker_plot),
        migrations.RunPython(index_plot),
        migrations.RunPython(component_prices),
        migrations.RunPython(index_prices),
    ]