Sunday, 5 January 2020

react django yahoo_fin get daily stock price

get 9849 days of apple price (open, high, low, close, adjclose)

#django/view
from yahoo_fin import stock_info as si

@csrf_exempt
def history(request):
    ticker = json.loads(request.body)['ticker']

    if not ticker:
        return HttpResponse('ticker not received')
    else:
        info = si.get_data(ticker)

        price = info['adjclose'].values
        #replace nan with last number for price
        if np.isnan(price[0]): price[0] = 0
        lastnum = 0
        for i in range(0, len(price)):
            if np.isnan(price[i]):
                price[i] = lastnum
            else:
                lastnum = price[i]

         open = info['open'].values
        #replace nan with adjclose for open
        for i in range(0, len(open)):
            if np.isnan(open[i]):
                open[i] = adjclose[i]

        high = info['high'].values
        # replace nan with adjclose for high
        for i in range(0, len(high)):
            if np.isnan(high[i]):
                high[i] = adjclose[i]

        low = info['low'].values
        # replace nan with adjclose for low
        for i in range(0, len(low)):
            if np.isnan(low[i]):
                low[i] = adjclose[i]

        close = info['close'].values
        # replace nan with adjclose for close
        for i in range(0, len(close)):
            if np.isnan(close[i]):
                close[i] = adjclose[i]

        volume = info['volume'].values
        #replace nan with 0 for volume
        volume[np.isnan(volume)] = 0

        #convert datetime to string
        date = info.index
        date = [x.strftime("%m/%d/%Y") for x in date]

        output = json.dumps({'price': price.tolist(),
                             'volume': volume.tolist(),
                             'date': date})

        return HttpResponse(output)

--------------------------------------
//react/app.js

import React, { useState, useEffect } from 'react';
import './App.css';
import { Button, Tabs, Progress, Menu, Radio, Input } from 'antd';
import ReactHtmlParser from 'react-html-parser';
import StickyHeader from 'react-sticky-header';
import HistoryGraph from './HistoricGraph';
const axios = require('axios');
const { TabPane } = Tabs;
const { SubMenu } = Menu;

function App() {
  const [tickers, settickers] = useState(null)
  const [ticker_loaded, setticker_loaded] = useState(0)
  const [ticker_radio, setticker_radio] = useState('AAPL')
  const [about_api, setabout_api] = useState(null)
  const [active_menu, setactive_menu] = useState('dow')
  const [analyst_info, setanalyst_info] = useState(null)
  const [balance_sheet, setbalance_sheet] = useState(null)
  const [cash_flow, setcash_flow] = useState(null)
  const [holder, setholder] = useState(null)
  const [income, setincome] = useState(null)
  const [quote, setquote] = useState(null)
  const [stats, setstats] = useState(null)
  const [historic_price, sethistoric_price] = useState(null)

  useEffect(() => {
    document.title = "yahoo_fin"

    //load all tickers
    axios({
      method: 'get',
      url: 'http://127.0.0.1:8000/stocks/tickers/',
      onDownloadProgress: progressEvent => {
        setticker_loaded(parseInt(progressEvent.loaded / progressEvent.total * 100))

      },
    })
      .then((response) => {
        settickers(response.data)
        console.log(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }, [])

  const about_yahoo_fin = () => {
    //yahoo_fin api page
    axios({
      method: 'get',
      url: 'http://127.0.0.1:8000/stocks/about_yahoo_fin/',
    })
      .then((response) => {
        setabout_api(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  const get_analysts_info = () => {
    //get_analysts_info
    axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/stocks/analysts/',
      data: {
        'ticker': ticker_radio,
      }
    })
      .then((response) => {
        setanalyst_info(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  const get_balance_sheet = () => {
    //get_balance_sheet
    axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/stocks/balance/',
      data: {
        'ticker': ticker_radio,
      }
    })
      .then((response) => {
        setbalance_sheet(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  const get_cash_flow = () => {
    //get_cash_flow
    axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/stocks/cash/',
      data: {
        'ticker': ticker_radio,
      }
    })
      .then((response) => {
        setcash_flow(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  const get_holders = () => {
    //get_holders
    axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/stocks/holder/',
      data: {
        'ticker': ticker_radio,
      }
    })
      .then((response) => {
        setholder(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  const get_income_statement = () => {
    //get_income_statement
    axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/stocks/income/',
      data: {
        'ticker': ticker_radio,
      }
    })
      .then((response) => {
        setincome(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  const get_quote_table = () => {
    //get_quote_table
    axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/stocks/quote/',
      data: {
        'ticker': ticker_radio,
      }
    })
      .then((response) => {
        setquote(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  const get_stats = () => {
    //get_stats
    axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/stocks/stats/',
      data: {
        'ticker': ticker_radio,
      }
    })
      .then((response) => {
        setstats(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  const get_history = () => {
    //get_data
    axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/stocks/history/',
      data: {
        'ticker': ticker_radio,
      }
    })
      .then((response) => {
        sethistoric_price(response.data)
        console.log(response.data)
      })
      .catch((error) => {
        console.log(error)
      })
  }

  //left tab click event
  const tabChange = (key) => {
    switch (key) {
      case '2':
        get_analysts_info()
        break
      case '3':
        about_yahoo_fin()
        break
      case '4':
        get_balance_sheet()
        break
      case '5':
        get_cash_flow()
        break
      case '6':
        get_holders()
        break
      case '7':
        get_income_statement()
        break
      case '8':
        get_quote_table()
        break
      case '9':
        get_stats()
        break
      case '10':
        get_history()
        break
      default:
        break
    }
  }
  //Tickers tab menu click event
  const menuClick = (e) => {
    setactive_menu(e.key)
  }
  //Tickers radio select event
  const radioSelect = (e) => {
    setticker_radio(e.target.value)
  }

  return (
    <div style={{ padding: '10px' }}>

      <Tabs tabPosition='left' defaultActiveKey="1" onChange={(key) => tabChange(key)}>
        <TabPane tab="Tickers" key="1">
          Loading tickers
          <StickyHeader
            header={<span style={{ float: 'right', backgroundColor: 'white', padding: '10px' }}>
              Selected ticker: {ticker_radio}</span>}>
          </StickyHeader>

          <Progress percent={ticker_loaded} size='small' />

          <Menu onClick={(e) => menuClick(e)} selectedKeys={[active_menu]} mode='horizontal'>
            <Menu.Item key='dow'>Dow</Menu.Item>
            <Menu.Item key='nasdaq'>Nasdaq</Menu.Item>
            <Menu.Item key='sp500'>SP500</Menu.Item>
            <Menu.Item key='other'>Other</Menu.Item>
          </Menu><br />

          {tickers ?
            <Radio.Group onChange={(e) => radioSelect(e)}>
              {
                tickers[active_menu].map((item, index) => {
                  return <Radio value={item} key={index}>{item}</Radio>
                })
              }
            </Radio.Group>
            : null}
        </TabPane>
        <TabPane tab="History" key="10">
          Ticker: {ticker_radio}<br />
          <HistoryGraph open={historic_price ? historic_price['open'] : null}
            close={historic_price ? historic_price['close'] : null}
            high={historic_price ? historic_price['high'] : null}
            low={historic_price ? historic_price['low'] : null}
            adjclose={historic_price ? historic_price['adjclose'] : null}
            volume={historic_price ? historic_price['volume'] : null}
            date={historic_price ? historic_price['date'] : null}>
          </HistoryGraph>
        </TabPane>
        <TabPane tab="Analyst" key="2">
          Ticker: {ticker_radio}<br />
          <pre>{analyst_info}</pre>
        </TabPane>
        <TabPane tab="Balance" key="4">
          Ticker: {ticker_radio}<br />
          <pre>{balance_sheet}</pre>
        </TabPane>
        <TabPane tab="Cash" key="5">
          Ticker: {ticker_radio}<br />
          <pre>{cash_flow}</pre>
        </TabPane>
        <TabPane tab="Holder" key="6">
          Ticker: {ticker_radio}<br />
          <pre>{holder}</pre>
        </TabPane>
        <TabPane tab="Income" key="7">
          Ticker: {ticker_radio}<br />
          <pre>{income}</pre>
        </TabPane>
        <TabPane tab="Quote" key="8">
          Ticker: {ticker_radio}<br />
          <pre>{quote}</pre>
        </TabPane>
        <TabPane tab="Stats" key="9">
          Ticker: {ticker_radio}<br />
          <pre>{stats}</pre>
        </TabPane>
        <TabPane tab="Yahoo_fin" key="3">
          {ReactHtmlParser(about_api)}
        </TabPane>
      </Tabs>

    </div>
  );
}

export default App;


reference:
http://chuanshuoge2.blogspot.com/2020/01/react-canvasjs-django-yahoofin.html

No comments:

Post a Comment