Open In App

Create a Stock Market Prediction App using React-Native

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We’ll walk through the process of building a Stock Market Prediction App using React Native. The app will allow users to input a stock symbol, fetch real-time stock data, and even predict the price for the next trading day. Let’s dive into the details!

Preview of final output: Let us have a look at how the final output will look like.

imresizer-1706370076612 Prerequisites:

Approach to create Stock Market Portfolio App:

  • User inputs a stock symbol.
  • App fetches real-time stock data using the Alpha Vantage API.
  • The fetched data is displayed, including various stock details.
  • An additional feature predicts the stock price for the next trading day.

Steps to create the project:

Step 1: Set up a new React Native project using Expo or React Native CLI.

npm install -g expo-cli
expo init StockMarketPredictionApp
cd StockMarketPredictionApp

Step 2: Create an account on Alpha Vantage.

imresizer-1706374881300

Step 3: Then you will be directed to API Documentation’s page, Choose the api url from there and copy it:

imresizer-1706374989881

Step 4: You can create the API Key using with the link given in the documentation, Get your API Key.

imresizer-1706375359938

Step 5: Copy the API Key.

Project Structure:

Screenshot-2024-01-27-225429

The updated dependencies in package.json file will look like:

"dependencies": {
"react-native-paper": "4.9.2",
"@expo/vector-icons": "^13.0.0",
"react-native-chart-kit": "*",
"react-native-svg": "13.9.0",
"d3-shape": "*"
}

Explanation:

  • The React Native functional component, named App, employs the useState hook to manage state for the stock symbol, fetched stock data, and predicted stock price.
  • An asynchronous function is utilized to fetch stock data from the Alpha Vantage API, updating the state with the retrieved data and predicting the next trading day’s stock price.
  • The JSX structure incorporates a title, input field, button featuring an animation effect, and displays for the predicted price and fetched stock data.
  • The styling, characterized by modern and sleek design with dark colors, enhances visual appeal, while interactive elements like the button employ TouchableOpacity for responsive touch feedback, with input field enabling dynamic updates as users type and presenting structured layouts for fetched stock data.

Example: Modify the following code to create the stock prediction app:

Javascript




import React,
{
    useState,
    useEffect
} from 'react';
import {
    StyleSheet, Text,
    View, TextInput,
    TouchableOpacity
} from 'react-native';
 
export default function App() {
    const [symbol, setSymbol] = useState('');
    const [stockData, setStockData] = useState(null);
    const [predictedPrice, setPredictedPrice] = useState(null);
 
    const fetchData = async () => {
        try {
            const apiKey = '46V2UYT1MGA2H1LX'; // Replace with your API key
            const response = await fetch(
`https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${symbol}&apikey=${apiKey}`
            );
            const data = await response.json();
 
            if (data['Global Quote']) {
                setStockData(data['Global Quote']);
                predictNextTradingDayPrice(data['Global Quote']);
            } else {
                console.error('Invalid response format');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };
 
    const predictNextTradingDayPrice =
        (stockInfo) => {
            // Simple prediction logic for demonstration purposes
            const latestPrice =
                parseFloat(stockInfo['05. price']);
            const changePercent =
                parseFloat(
                    stockInfo['10. change percent']
                        .replace('%', '')) / 100;
            const predictedPrice =
                latestPrice * (1 + changePercent);
 
            setPredictedPrice(predictedPrice.toFixed(4));
        };
 
    return (
        <View style={styles.container}>
            <Text style={styles.title}>
                Stock Market Prediction App
            </Text>
            <TextInput
                style={styles.input}
                placeholder="Enter Stock Symbol"
                value={symbol}
                onChangeText={(text) => setSymbol(text)} />
            <TouchableOpacity style={styles.btn}
                onPress={fetchData}>
                <Text style={styles.btnText}>
                    <Text style={styles.animation}>
                    </Text>
                    Get Stock Data
                    <Text style={styles.animation}></Text>
                </Text>
            </TouchableOpacity>
            {predictedPrice && (
                <Text style={styles.result}>
                    Predicted Price for Next
                    Trading Day: {predictedPrice}
                </Text>
            )}
            {stockData && (
                <View style={styles.stockInfoContainer}>
                    {
                        Object.entries(stockData)
                            .map(([key, value]) => (
                                <View key={key}
                                    style={styles.stockInfoItem}>
                                    <Text style={styles.stockInfoLabel}>
                                        {key}:
                                    </Text>
                                    <Text style={styles.stockInfoText}>
                                        {value}
                                    </Text>
                                </View>
                            ))
                    }
                </View>
            )}
 
 
        </View>
    );
}
 
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'black',
        padding: 20,
    },
    title: {
        fontSize: 24,
        marginBottom: 20,
        color: 'white',
        fontWeight: 'bold',
    },
    input: {
        height: 40,
        borderColor: 'white',
        borderWidth: 1,
        marginBottom: 10,
        paddingLeft: 10,
        paddingRight: 10,
        color: 'white',
        borderRadius: 5,
    },
    btn: {
        backgroundColor: '#40B3A2',
        padding: 16,
        borderRadius: 4,
        minWidth: 200,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        shadowColor: 'rgba(0, 0, 0, 0.1)',
        shadowOffset: { width: 0, height: 4 },
        shadowOpacity: 1,
        shadowRadius: 12,
        overflow: 'hidden',
        marginVertical: 10,
    },
    btnText: {
        color: 'white',
        fontSize: 12,
        fontWeight: '600',
        letterSpacing: 1.2,
        textTransform: 'uppercase',
        overflow: 'hidden',
    },
    animation: {
        borderRadius: 100,
        backgroundColor: 'rgba(255, 255, 255, 0.1)',
        height: 80,
        width: 80,
        position: 'absolute',
    },
    stockInfoContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 20,
    },
    stockInfoItem: {
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 10,
        marginBottom: 10,
        backgroundColor: '#001F3F',
        padding: 10,
        borderRadius: 5,
    },
    stockInfoLabel: {
        fontWeight: 'bold',
        marginRight: 5,
        color: 'white',
    },
    stockInfoText: {
        color: 'white',
    },
    result: {
        marginTop: 20,
        fontSize: 16,
        fontWeight: 'bold',
        color: 'white',
    },
});


Step 7: Run Your App: Start the Expo development server:

expo start

Step 8: Open the Expo Go app on your smartphone or use an emulator to scan the QR code from the Expo DevTools.

Output:

stockmarket-ezgifcom-video-to-gif-converter



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads